Preliminary Software Engineering
Unit 1 - Programming Fundamentals
Unit 1 - Programming Fundamentals
  • 1 - Programming Fundamentals
    • Programming Fundamentals Content
  • 2 - Python
    • Expected Python Knowledge
    • GitHub
    • Learning Python
    • Data Structures and File Management
      • Data Structures
        • Lists
        • Arrays
          • Single and Multi-Dimensional Arrays
        • Lists vs Arrays
          • Activities
        • Tuples
        • Sets
        • Dictionaries
          • Activities
      • File Handling
        • Loops, Lists, Dictionaries
        • Activities
  • 3 - Theory Content
    • Theory Content Explained
      • NESA Directional Verbs
      • Responding to Directional Verbs
  • 4 - Software Development and Management
    • Approaches to Software Development
      • Waterfall Model
      • Agile Model
      • Summary: Waterfall vs Agile
      • Activities
    • Software Development Steps
      • Sample Exam Question
      • Requirements Definition
        • Understanding the Need
        • Key Questions to Ask
        • Examples
        • Activities
        • Sample Exam Question
      • Determining Specifications
        • Functional Specifications
        • Non-Functional Specifications
        • Activities
      • Design
        • Top-Down Design Approach
        • Bottom-Up Design Approach
      • Development
        • Optimising Code
      • Integration
        • Example: Payment Program
        • Activity
        • Application Programming Interface (API)
          • Example: OpenWeather API
          • Example: WeatherAPI
          • Activity: Prepare Spells
      • Testing and Debugging
        • Test Data
          • Activities
        • Testing the System
          • Activities
        • Debugging
          • Types of Errors
            • Activities
          • Python Debugger
            • Activities
          • VS Code Debugger
            • Activities
      • Installation
        • Activities
        • Sample Exam Question
      • Maintenance
  • Charts and Algorithms
    • Example: IPO Charts and Pseudocode
      • Activities
    • Algorithms, Flowcharts, Pseudocode
      • Pseudocode Activities
      • Flowchart Activities
      • Sample Exam Questions
    • Structure Charts
      • Activities
      • Sample Exam Questions
    • Data Flow Diagrams
      • Activities
    • Data Dictionaries
      • Activities
    • Decision Trees
      • Activities
      • Sample Exam Questions
    • Gantt Chart
    • Class Diagrams
      • Sample Exam Question
    • Storyboards
      • Sample Exam Question
  • Testing and Debugging
    • Test Data
      • Activities
    • Testing the System
      • Activities
    • Debugging
      • Types of Errors
        • Activities
      • Python Debugger
        • Activities
      • VS Code Debugger
        • Activities
  • Computational Thinking
    • Decomposition
    • Abstraction
    • Activities
  • Version Control
    • Git
    • GitHub
    • Activities
  • Number Systems
    • Binary Systems
    • Hexadecimal Numbers
    • Using Two's Complement
    • Activities
  • 5 - Assessment Task 1
    • Data Science Project
      • Before we Start
        • Setting up GitHub Repository
        • Setting Up Markdown Documentation
      • Examples of API Usage
        • Starter Code: NASA Scenario
        • Starter Code: Spell Book
        • Starter: Pokédex Explorer
        • Starter Code: Weather App
        • Example: OpenWeather API
        • Example: WeatherAPI
        • Example: Prepare Spells
    • Task Guide
      • Requirements Definition
      • Determining Specifications
        • Use Cases
      • Design
        • Gantt Chart
        • Structure Chart
        • Algorithms
        • Data Dictionary
      • Development
        • Comments vs DocStrings
        • UI - main.py
        • Create Python Module
          • Example: NASA Module
          • Example: WeatherFetch Module
          • Example: SpellBook Module
      • Integration
        • Example: Pokedex
      • Testing and Debugging
        • Commit Changes
      • Installation
      • Maintenance
    • Submitting Your Task
Powered by GitBook
On this page
  1. 5 - Assessment Task 1
  2. Data Science Project
  3. Examples of API Usage

Example: OpenWeather API

The following Python program open_weather.py uses the OpenWeather API to tell the user current weather information.

The beauty of using this is that OpenWeather frequently update their data so you do not need to constantly be downloading datasets and reimporting them.

However, please note you MUST get your own API_KEY from the Open Weather Map website for this to work, and replace that in the code.

Unfortunately, since this program was written in 2024, the API has been subscription walled. Whilst most API calls are free, a subscription is required :''(

import requests
import json

# API Key for OpenWeatherMap
# Please note: You must go to openweather map and get you own API key.


# Function to get current weather conditions and 5-day forecast
def get_weather(location): 
    # API endpoint for current weather
    current_weather_url = f'http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric'
    # API endpoint for 5-day forecast
    forecast_url = f'http://api.openweathermap.org/data/2.5/forecast?q={location}&appid={api_key}&units=metric'

    # Make GET request to API
    current_weather_response = requests.get(current_weather_url)
    forecast_response = requests.get(forecast_url)

    # Parse JSON response
    current_weather_data = json.loads(current_weather_response.text) # <-- convert JSON response to Python dictionary
    forecast_data = json.loads(forecast_response.text) # <-- convert JSON response to Python dictionary

    # Extract current weather conditions
    current_temp = current_weather_data['main']['temp'] # <-- extract temperature from dictionary
    current_weather = current_weather_data['weather'][0]['description'] # <-- extract weather description from dictionary

    # Extract forecast for next 5 days
    forecast_list = forecast_data['list'] # <-- extract list of forecasts from dictionary
    forecast = {} # <-- create empty dictionary to store forecast
    for f in forecast_list: # <-- loop through list of forecasts
        date = f['dt_txt'][:10] # <-- extract date from forecast
        if date not in forecast: # <-- check if date is already in forecast dictionary
            forecast[date] = { # 
                'temp': f['main']['temp'],
                'weather': f['weather'][0]['description'] # 
            }

    return current_temp, current_weather, forecast # <-- return current weather conditions and 5-day forecast

# Get weather for a location
location = input("Enter a location: ") # <-- get location from user
current_temp, current_weather, forecast = get_weather(location) # <-- call get_weather function

# Print current weather conditions
print(f'Current temperature in {location}: {current_temp}') # <-- print current temperature
print(f'Current weather in {location}: {current_weather}') # <-- print current weather

# Print forecast for next 5 days
print("\n5-day forecast:") # <-- print header
for date, weather in forecast.items(): # <-- loop through forecast dictionary
    print(f'{date}: Temperature: {weather["temp"]}, Weather: {weather["weather"]}') # <-- print date, temperature, and weather

PreviousStarter Code: Weather AppNextExample: WeatherAPI

Last updated 3 months ago