DE6412 - Computer Programming 2
This assignment will guide you to analyse, develop, and evaluate a simple web application that serves as a solution to an engineering application: displaying real-time weather forecasts for New Zealand cities. You will use Rapid Application Development (RAD) techniques, fetching data from a public weather API and using the Streamlit framework to create a user interface.
Learning Outcome Met: LO1 - Analyse an engineering application.
This part requires you to analyse the requirements of an external data source (the OpenWeatherMap API), which represents a component of a larger engineering application. You will perform a structured interpretation of the API's documentation to establish software requirements for fetching data, such as URL endpoints, parameters, and data structures. This process mirrors industry practice for integrating third-party services.
Your first task is to analyse a public API to get weather data. We will use OpenWeatherMap, as it provides a free tier sufficient for this assignment. Your analysis will help establish the software requirements for our application.
1. Get an API Key
2. Structured Interpretation of the API Documentation
We will use the 5 Day / 3 Hour Forecast data. Perform a structured interpretation of the documentation here: 5 Day / 3 Hour Forecast.
Based on your analysis, you will find an API request URL must be structured like this:
https://api.openweathermap.org/data/2.5/forecast?q={city_name},{country_code}&appid={API_key}&units=metric
The key requirements for this endpoint are:
q={city_name},{country_code}: The city and country code (NZ for New Zealand).appid={API_key}: Your personal API key.units=metric: To get the temperature in Celsius.# Implement a test request to confirm your analysis of the API requirements.
import requests
import json
# --- Your code here ---
# Replace 'YOUR_API_KEY' with the key from your analysis.
API_KEY = 'YOUR_API_KEY'
# The city we want the weather for
city = 'Auckland'
country_code = 'NZ'
# Construct the API URL based on the established software requirements
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city},{country_code}&appid={API_KEY}&units=metric"
# Make the request
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Get the JSON data from the response
data = response.json()
# Pretty print the JSON data to analyse its structure
print(json.dumps(data, indent=4))
else:
print(f"Error: {response.status_code}")
print(response.text)
# --- End of your code ---
The JSON response contains a lot of information. Analyse the structure and identify the key data points required for our application. We are interested in the list which contains the forecast.
For each item in the list, we need to extract:
dt_txt: The date and time of the forecast.main.temp: The temperature.weather[0].description: A description of the weather (e.g., "light rain").wind.speed: The wind speed.Now, write a function to parse this data based on your analysis.
def parse_weather_data(data):
"""
Parses the weather data based on the analysed structure.
"""
forecasts = []
if 'list' in data:
for item in data['list']:
forecast = {
"dt_txt": item['dt_txt'],
"temp": item['main']['temp'],
"description": item['weather'][0]['description'],
"wind_speed": item['wind']['speed']
}
forecasts.append(forecast)
return forecasts
# Test the parsing function with the data from the previous step
if 'data' in locals() and data:
auckland_forecast = parse_weather_data(data)
# Print the first few forecasts to verify
for forecast in auckland_forecast[:5]:
print(forecast)
Learning Outcome Met: LO2 - Develop a software solution.
In this section, you will develop a software solution using Rapid Application Development (RAD) techniques. Streamlit is a RAD tool, and you will demonstrate its valid application by creating a functional user interface. The goal is to make effective and efficient use of the RAD tool capabilities, such as widgets for user input and data display components, to build your engineering application.
Now that we have the logic to get weather data, let's develop the user interface. We will use Streamlit, a RAD tool perfect for creating simple data apps.
If you haven't installed it yet, run: pip install streamlit pandas
A Streamlit app is a Python script that you run from your terminal: streamlit run your_app_name.py
Your task is to develop a weather_app.py script that will:
Here is a list of NZ cities you can use:
['Auckland', 'Wellington', 'Christchurch', 'Hamilton', 'Tauranga', 'Dunedin', 'Palmerston North', 'Nelson', 'Rotorua', 'New Plymouth']
# This is the full code for your `weather_app.py` file.
# You must complete the implementation and ensure it functions correctly.
import streamlit as st
import requests
import pandas as pd
# --- Functions from Part 1 ---
API_KEY = 'YOUR_API_KEY' # Make sure to replace this with your actual key
def get_weather_data(city):
"""
Fetches weather data for a given city.
"""
country_code = 'NZ'
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city},{country_code}&appid={API_KEY}&units=metric"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return None
def parse_weather_data(data):
"""
Parses the weather data to extract relevant information for the next 24 hours.
"""
forecasts = []
if 'list' in data:
# We only want the next 8 * 3-hour intervals = 24 hours
for item in data['list'][:8]:
forecast = {
"Time": item['dt_txt'],
"Temperature (°C)": item['main']['temp'],
"Description": item['weather'][0]['description'],
"Wind Speed (m/s)": item['wind']['speed']
}
forecasts.append(forecast)
return forecasts
# --- Development of the Streamlit App (RAD techniques) ---
st.title('🇳🇿 New Zealand Weather Forecast')
nz_cities = ['Auckland', 'Wellington', 'Christchurch', 'Hamilton', 'Tauranga', 'Dunedin', 'Palmerston North', 'Nelson', 'Rotorua', 'New Plymouth']
# Use a RAD tool component for city selection
selected_cities = st.multiselect('Select up to 3 cities to see the forecast', nz_cities, max_selections=3)
# Develop the main logic of the application
if selected_cities:
for city in selected_cities:
st.header(f"Weather for {city}")
# Get the weather data
with st.spinner(f'Fetching latest data for {city}...'):
weather_data = get_weather_data(city)
if weather_data:
# Parse the data
forecasts = parse_weather_data(weather_data)
# Use a pandas DataFrame for effective display
df = pd.DataFrame(forecasts)
# Display the data as a table, demonstrating efficient use of the tool
st.table(df)
else:
st.error(f"Could not fetch weather data for {city}. Please check the city name or your API key.")
else:
st.info("Select a city to begin.")
st.sidebar.info("This app is a demonstration of RAD techniques using the OpenWeatherMap API and Streamlit.")
Learning Outcome Met: LO3 - Evaluate the performance of a RAD software solution.
The final part of this assignment focuses on evaluation. You will evaluate the performance of the RAD software solution you created. This involves a technical appraisal of your application, using informed judgement to identify its deficiencies. By reflecting on the app's functionality and limitations, you will evaluate the results to identify areas for improvement, a critical step in the development lifecycle that aligns with industry practice.
Now that you have developed your application, you must evaluate it. Create a new markdown cell in your submission file (or a separate text file) and write a brief evaluation report (200-300 words).
Your report must cover the following points:
To submit your assignment, you need to provide a zip file containing:
weather_app.py file containing the full application code..md or .txt file).requirements.txt file listing the libraries needed to run your app. It should contain:
requests
streamlit
pandas