Mini-Lab: Reading Data from a Web API
Weather Edition
This mini-lab is one of several short workshops that support the final project. You will call a real web API, pull values out of the JSON it returns, and turn a week of raw weather data into a forecast with a weather icon for each day. Even if your project does not use an API, the skills here (navigating nested data, splitting a program into small functions, and testing without the network) carry straight into your project.
Learning objectives
By the end of this lab, you should be able to:
- Explain what a web API is and what a request returns.
- Build a request from a base URL and query parameters, and read the JSON response as a Python dictionary.
- Pull values out of nested API data, and reshape it into a form that is easier to use.
- Separate the code that talks to the network from the code that processes data, so the processing code can be tested with
pytestusing a saved response.
Connection to earlier weeks
An API response is just nested data, the same kind you navigated in Week 12.
If you can trace data[2]["scores"][0] on paper, you already have the core skill this lab needs.
The only new step is where the data comes from.
Background
What is a web API?
An Application Programming Interface (API) defines how one program can ask another program for data or services.
A web API is an API you reach over the internet, using the same https protocol your browser uses.
The conversation always has two halves:
- Request: your program sends a URL to a server. The URL names what you want (the endpoint) and the details (the query parameters).
- Response: the server sends back a status code (
200means success) and a body of data, usually in JSON format.
Python's requests module handles the network part, and its .json() method turns the JSON body into ordinary Python dictionaries and lists.
The API we will use: Open-Meteo
Open-Meteo is a free weather API for non-commercial use. It does not require an account or an API key, so you can start making requests right away. Weather data in this lab is provided by Open-Meteo.com under the CC BY 4.0 license.
Here is a request for a 7-day forecast in Harrisonburg, VA, split across lines so you can read each part:
https://api.open-meteo.com/v1/forecast
?latitude=38.4496
&longitude=-78.8689
&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max
&temperature_unit=fahrenheit
&timezone=America/New_York
&forecast_days=7
| Part of the URL | Meaning |
|---|---|
https://api.open-meteo.com/v1/forecast |
The endpoint: which service you are asking |
? |
Marks the start of the query parameters |
latitude=38.4496 |
One parameter, written as name=value |
& |
Separates one parameter from the next |
daily=... |
A comma-separated list of the daily values you want back |
Try it in your browser first
Paste the URL above into a browser as one line (no spaces or line breaks). Firefox and Chrome both display the JSON response. Firefox shows a collapsible tree, and Chrome has a "Pretty-print" checkbox. Looking at real data before writing code is the most useful habit you can build when working with any API.
Weather codes
Open-Meteo does not send a word like "sunny."
Instead, each day has a weather_code, a number from the international WMO standard.
Your program will translate each code into a category, and each category has an icon.
| WMO codes | Meaning | Category | Icon |
|---|---|---|---|
| 0, 1 | Clear sky, mainly clear | "sunny" |
☀️ |
| 2 | Partly cloudy | "partly cloudy" |
⛅ |
| 3 | Overcast | "cloudy" |
☁️ |
| 45, 48 | Fog | "fog" |
🌫️ |
| 51, 53, 55, 56, 57 | Drizzle and freezing drizzle | "drizzle" |
🌦️ |
| 61, 63, 65, 66, 67, 80, 81, 82 | Rain, freezing rain, and rain showers | "rain" |
🌧️ |
| 71, 73, 75, 77, 85, 86 | Snow, snow grains, and snow showers | "snow" |
🌨️ |
| 95, 96, 99 | Thunderstorm, with or without hail | "storm" |
⛈️ |
Any code not in this table belongs to the category "unknown".
Icons always come with a word
Every icon in this lab is printed next to a text label (for example, ☀️ Sunny).
A screen reader may announce an emoji differently than you expect, and some terminals display certain emoji as empty boxes.
The label makes the output readable for everyone, everywhere.
Keep this habit in your project: never let an icon, image, or color carry meaning by itself.
Setup
- Create a folder named
webapiin yourCS149folder. - Download the starter files into that folder:
forecast.py: the program you will completesample_forecast.json: a saved API response for testingtest_forecast.py: starter tests
- Install the
requestsmodule if you don't have it yet:- Thonny: Tools → Manage packages, search for
requests, and select Install. - VS Code terminal:
pip install requests
- Thonny: Tools → Manage packages, search for
Part 1: Read the data before you code (paper)
Here is the daily section of sample_forecast.json, plus the daily_units section that describes it.
Notice the shape: daily is a dictionary of lists.
The lists are parallel: index 0 of every list describes the first day, index 1 describes the second day, and so on.
{
"daily_units": {
"time": "iso8601",
"weather_code": "wmo code",
"temperature_2m_max": "°F",
"temperature_2m_min": "°F",
"precipitation_probability_max": "%"
},
"daily": {
"time": ["2026-12-04", "2026-12-05", "2026-12-06", "2026-12-07",
"2026-12-08", "2026-12-09", "2026-12-10"],
"weather_code": [1, 2, 61, 80, 71, 0, 45],
"temperature_2m_max": [48.2, 45.9, 41.0, 43.7, 33.1, 38.6, 40.4],
"temperature_2m_min": [29.4, 31.8, 35.2, 30.1, 24.6, 20.3, 27.9],
"precipitation_probability_max": [3, 12, 85, 64, 70, 0, null]
}
}
Assume data holds this whole response after .json().
Without running any code, write the value and type of each expression, or describe the error it would cause.
data["daily"]["time"][2]data["daily"]["weather_code"][4]data["daily_units"]["temperature_2m_max"]len(data["daily"])data["daily"]["precipitation_probability_max"][-1]data["daily"][0]- Write one expression that gives the low temperature on
"2026-12-08".
When you finish, check your answers in the Python shell:
Discuss with a neighbor
JSON writes null, but Python shows something else for item 5. What is it?
Why might a weather service send "no value" for the last day of a forecast?
Part 2: Translate codes into icons
Open forecast.py.
The function that talks to the network, fetch_forecast(), is already written for you.
Read it, and match each line to the URL in the Background section.
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
def fetch_forecast(latitude: float, longitude: float) -> dict:
"""Request a 7-day daily forecast from Open-Meteo.
Args:
latitude: Latitude of the location, in degrees.
longitude: Longitude of the location, in degrees.
Returns:
The JSON response, converted to a dictionary.
"""
params = {
"latitude": latitude,
"longitude": longitude,
"daily": "weather_code,temperature_2m_max,temperature_2m_min,"
"precipitation_probability_max",
"temperature_unit": "fahrenheit",
"timezone": "America/New_York",
"forecast_days": 7,
}
response = requests.get(FORECAST_URL, params=params, timeout=10)
response.raise_for_status() # Stop with an error if the request failed
return response.json()
Notice that requests builds the ?name=value&... part of the URL from the params dictionary, so you never have to write it by hand.
The file also provides a dictionary that maps each category to an icon and a label:
ICONS = {
"sunny": ("☀️", "Sunny"),
"partly cloudy": ("⛅", "Partly cloudy"),
"cloudy": ("☁️", "Cloudy"),
"fog": ("🌫️", "Fog"),
"drizzle": ("🌦️", "Drizzle"),
"rain": ("🌧️", "Rain"),
"snow": ("🌨️", "Snow"),
"storm": ("⛈️", "Thunderstorm"),
"unknown": ("❔", "Unknown"),
}
get_category(code)
Complete this function.
Given a WMO weather code (an int), return its category string from the weather-code table above, or "unknown" if the code is not in the table.
Design decision
There are at least two reasonable ways to write this function: a chain of if/elif statements that checks groups of codes, or a dictionary that maps every code to its category.
Pick one, then write a sentence in the function's comments explaining why you chose it.
Which version would be easier to change if you wanted "drizzle" to count as "rain"?
Part 3: Reshape the data
Parallel lists are awkward to work with: to describe one day, you have to reach into five different lists using the same index. It is much easier to work with a list of dictionaries, one dictionary per day.
summarize_days(data)
Complete this function. Given a full API response, return a list with one dictionary per day. Each dictionary has exactly these keys:
| Key | Value |
|---|---|
"date" |
The date string, such as "2026-12-04" |
"high" |
The high temperature (a float) |
"low" |
The low temperature (a float) |
"precip" |
The chance of precipitation (an int, or None if missing) |
"category" |
The category string from get_category() |
For sample_forecast.json, the first item in the returned list is:
Tip
Your function should not assume there are exactly 7 days.
Use the length of one of the lists to decide how many times to loop.
Then ask yourself: should this be a for loop or a while loop, and why?
format_day(day)
Complete this function. Given one day's dictionary, return a single line of text in exactly this format:
- Round the temperatures to whole numbers, right-aligned in a width of 3.
- Show the precipitation chance as a percentage, right-aligned in a width of 4. If the value is
None, show--instead. - End the line with the category's icon and label, taken from
ICONS.
Why is the icon at the end?
Emoji take up different amounts of space in different terminals. If the icon came first, the columns after it would not line up. Putting it last keeps the numbers aligned no matter how the icon is drawn.
main()
Complete main() so the program:
- Fetches the forecast for Harrisonburg (the coordinates are in the URL above).
- Prints one formatted line for each day.
- Asks the user to pick a day by number (1 to 7), and keeps asking until the input is valid.
- Prints the chosen day's icon and label on a line by itself, followed by its high, low, and precipitation chance.
Here is the expected forecast for the saved sample data. Your live output will show the real dates and weather.
2026-12-04 High 48°F Low 29°F Precip 3% ☀️ Sunny
2026-12-05 High 46°F Low 32°F Precip 12% ⛅ Partly cloudy
2026-12-06 High 41°F Low 35°F Precip 85% 🌧️ Rain
2026-12-07 High 44°F Low 30°F Precip 64% 🌧️ Rain
2026-12-08 High 33°F Low 25°F Precip 70% 🌨️ Snow
2026-12-09 High 39°F Low 20°F Precip 0% ☀️ Sunny
2026-12-10 High 40°F Low 28°F Precip -- 🌫️ Fog
Part 4: Test without the network
Live data changes every hour, and the network is not always available.
A test that calls the API directly can't know what the "right" answer is, and it fails whenever the Wi-Fi does.
That's why fetch_forecast() is kept separate from everything else: the other functions take a dictionary as input, so you can test them with sample_forecast.json instead of a live request.
The starter test_forecast.py loads the saved response once and includes one test for each function.
Add tests until you have covered:
- At least one code from every category in the weather-code table, plus an unknown code.
- The number of days and the contents of at least two days returned by
summarize_days(). - A day with a
Noneprecipitation value informat_day().
Keep the three test functions from the starter file, and give each one at least two assert statements.
You may add more test functions too, as long as each of those also has at least two.
Run your tests with coverage in VS Code.
Any line in fetch_forecast() or main() will show as untested, and that is expected.
Every other line should be covered.
Submission
Submit forecast.py and test_forecast.py to Gradescope.
The autograder runs your functions against saved data only, so your code must work without a network connection everywhere except fetch_forecast() and main().
Stretch goals
Try any of these if you finish early, or if your project will use an API.
- Any city, not just Harrisonburg. Open-Meteo also has a free geocoding API that turns a city name into a latitude and longitude. Ask the user for a city, make a first request to find its coordinates, then make a second request for the forecast. Combining two API calls is a common project pattern.
- Today's weather on a web page. Write the forecast to a file named
forecast.htmlas an HTML table, then open it in a browser. Wrap each icon as<span role="img" aria-label="Sunny">☀️</span>so screen readers announce a meaningful label. - Day of the week. Use the
datetimemodule to turn"2026-12-04"into"Fri"and add it to each line.
Bringing an API into your project
If your project will use a web API, check these things before you commit to it:
- Does it need a key? Many APIs (for example, OpenWeatherMap) require an account and an API key, and a new key can take an hour or more to start working. Request it early. Never commit a key to git: store it in a separate file and list that file in
.gitignore. - What are the limits? Most free APIs limit how many requests you can make per minute or per day. Save responses to a file while you develop, instead of requesting the same data over and over.
- What shape is the data? Look at a real response in your browser before you write any code, and sketch its structure on paper.
- What does attribution require? Many free data sources ask you to credit them. Open-Meteo, for example, asks for attribution, so credit it in your project's README.
- Can you test it? Keep the network code in one small function, and test everything else with saved responses, exactly as in this lab.
