Step 2 of 6
Fetch the forecast
Last time you saw the raw text. Now let’s make it useful.
Goal for this lesson: write a function that returns the forecast as Python data.
Why a function?
A function is a named little machine: you give it what it needs, and it hands back a result. Putting the request in a function means we can reuse it in every later lesson without copying code.
Step 1: Replace your file
Open weather.py and replace everything with this:
import requests
URL = (
"https://api.open-meteo.com/v1/forecast"
"?latitude=29.42&longitude=-98.49"
"&hourly=temperature_2m&temperature_unit=fahrenheit&forecast_days=2&timezone=auto"
)
def get_forecast():
response = requests.get(URL, timeout=10)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
data = get_forecast()
print(data.keys())
A few things worth knowing:
raise_for_status()stops the program with a clear error if the weather service has a problem, instead of letting a bad answer sneak through..json()turns the text into a Python dictionary, which is a collection of labeled values.- The
if __name__ == "__main__":line means “only run this part when I run this file directly.” It lets later files borrowget_forecastwithout running the print.
Step 2: Run it
python3 weather.py
You should see the labels inside the answer, something like dict_keys(['latitude', 'longitude', ..., 'hourly']). The one we care about is hourly.
Check yourself
Can you see hourly in the list? If so, you have the forecast as real Python data. Take a moment to enjoy that.