Lesson 2: Weather Tracker Blueprint with API Integration
Create a weather tracking application that stores city information and fetches current temperature data from a weather API.
Lesson Objectives
- Create the weather blueprint with database integration
- Build a weather database table to store cities and temperatures
- Implement forms to add new cities to track
- Integrate with a weather API to fetch current temperature data
- Create an 'Update Weather' button that retrieves live weather information
- Display weather data for multiple cities in an organized format
Weather Tracker Blueprint with API Integration - Notes
Weather Tracker Feature Overview
The weather blueprint allows users to:
- Add cities to track (e.g., Macon, Georgia)
- Store city and temperature data in a local database
- Update temperatures by fetching live data from a weather API
- View current weather for all tracked locations
Example: Add "Macon, Georgia" with an initial temperature of 15°. Click "Update Weather" and it will fetch the actual current temperature (e.g., 82°).
Database Schema
Create a weather table with the following columns:
- weather_id: Integer, Primary Key, Auto-increment
- city: Text (e.g., 'Macon')
- state: Text (e.g., 'Georgia') - optional but helpful
- temperature: Integer or Real (current temperature in degrees)
Blueprint Routes
Your weather blueprint should have these routes:
@weather_bp.route('/weather')
def index():
# Display all weather records
@weather_bp.route('/weather/add', methods=['POST'])
def add_weather():
# Add new city to database
@weather_bp.route('/weather/update/<int:weather_id>')
def update_weather(weather_id):
# Fetch live weather from API and update database Weather API Integration
Use weather.gov (National Weather Service API) - completely free, no API key required!
The NWS API requires a two-step process:
- Get the grid coordinates for a location
- Fetch the forecast for those coordinates
Example API call to fetch temperature:
import requests
def get_temperature(city, state):
# Step 1: Get coordinates (you can also hardcode these)
geocode_url = f'https://nominatim.openstreetmap.org/search'
params = {'q': f'{city}, {state}', 'format': 'json'}
geo_response = requests.get(geocode_url, params=params)
location = geo_response.json()[0]
lat, lon = location['lat'], location['lon']
# Step 2: Get weather from NWS
points_url = f'https://api.weather.gov/points/{lat},{lon}'
points_response = requests.get(points_url)
forecast_url = points_response.json()['properties']['forecast']
# Step 3: Get the forecast
forecast_response = requests.get(forecast_url)
current_temp = forecast_response.json()['properties']['periods'][0]['temperature']
return current_tempWhy weather.gov?
- 100% free, no API key needed
- Official US government data
- No rate limits for reasonable use
- US locations only
Form Implementation
Create an HTML form to add new weather locations:
<form action="/weather/add" method="POST">
<input type="text" name="city"
placeholder="City (e.g., Macon)" required>
<input type="text" name="state"
placeholder="State (e.g., Georgia)">
<input type="number" name="temperature"
placeholder="Initial Temperature">
<button type="submit">Add Weather Record</button>
</form> Update Weather Functionality
When a user clicks 'Update Weather' for a city:
- Retrieve the city and state from the database
- Make an API request to get the current temperature
- Update the database record with the live temperature
- Redirect back to the weather page to display updated information
Note: Make sure to handle API errors gracefully (e.g., city not found, API rate limit exceeded).