Creating Daily Forecasts with a Python Weather API

Python is becoming an increasingly popular programming language, and one of its many advantages is that it is particularly easy to make HTTP calls to websites and APIs. With just a few lines of code – and access to the right Python Weather API – you can build a small program that provides a weather forecast of a given location anywhere on earth.

Prerequisites for accessing a Weather API with Python

Let’s go through what you need to write and run this code successfully:

  • Python3 installed on your computer.
  • An API Key for the Tomorrow.io API
  • The latitude and longitude of your favorite place on earth

Finding your coordinates is quite easy using your favorite online maps. Let’s use Google Maps as an example: Search or scroll your map to your place of interest. Right-click the specific spot on the map, and you’ll see two numbers, for example, “37.80873, -122.47361”. Click on the numbers, and they get copied to your clipboard too. You could store this in the same text file as your API key for now. Depending on your source, make sure that you don’t mix up latitude and longitude, or you’ll end up in another corner of our planet. Google Maps does use the same format as Tomorrow.io, making this a particularly suitable source.

Making a basic Weather API call in Python

Two lines of code are sufficient for a basic Python request: import requests and response = requests.request(“GET”, url, params=querystring).

Let’s review what is happening here: import requests adds a library that is not technically part of Python, but a de-facto standard, and used in millions of projects. If you have not used it before, you can install it using pip install requests from the command line. Next, let’s look at the one method we need to call: request(). In this basic use, the request takes three parameters:

  • “GET”, the type of HTTP request you want to make
  • url, a string containing the URL of your API, https://api.tomorrow.io/… in our case
  • params, which is a dict containing the parameter of your query (for example, the location we looked up earlier will go here, among other things)

Using the API documentation of Tomorrow.io to generate Python code

Of course, in the above example, we’ve left out two of the trickier parts: Choosing the right url and properly serializing your parameters as a JSON object. This is where the API documentation of Tomorrow.io comes in handy:

We will work with Retrieve Timelines (Basic) for this example. In the second column, you see the actual documentation, and a code snippet to the right. Of the available languages, select Python, and you’ll see Python code. Next, in the center of the screen look at the Query Parameters: The first one is location*, the asterisk denoting a required parameter. In the text field, paste your coordinates from earlier, and closely watch what happens with the Python code: As you enter the coordinates, they automatically get added to the Python code as part of the dict that will be submitted as the parameters:

weather API python documentation

Looking back at our query parameters, we notice that the following parameter, fields*, is also required. Click Add and enter temperature. ‘Try it’ again, and the query should now be successful, and return “200 OK”. Just below, you see the collapsed JSON object, and when you drill down, eventually, you’ll see “temperature”: xx.xx, which is your first value. Yay, success!

Let’s go through the rest of the parameters:

  • units: can be metric or imperial
  • timesteps: time between datapoints. Let’s choose 1d (one day) so that we get a data point every 24 hours.
  • startTime: If left empty, it defaults to now. Let’s do that.
  • endTime: If left empty, it will go as far as the forecast reaches, which depends on a variety of factors. Let’s leave this empty as well for now.
  • timezone: If left empty, will default to UTC.

Also, let’s add another field in addition to temperature: CloudCover. Click ‘Try It’ one last time to make sure all is good. Now that we’re all set, let’s copy the code (not the JSON result, just the Python code) by clicking into the code field and on the copy symbol that appears.

Expand the code snippet into a Python weather forecast program

Open your favorite code editor, for example, Visual Studio Code, and create a file weather.py with the copied code. (I usually put the querystring on multiple lines as below to make editing on the fly easier.)

import requests

url = "https://api.tomorrow.io/v4/timelines"

querystring = {
"location":"33, -84",
"fields":["temperature", "cloudCover"],
"units":"imperial",
"timesteps":"1d",
"apikey":"xxxxxxxxxxxxxxx"}

response = requests.request("GET", url, params=querystring)
print(response.text)

Parsing and formatting the output

Next, let’s pretty up the cryptic JSON object, and print it in a nice table. If you have experience with JSON, you will already know that it can be unforgiving and that nested elements have to be parsed correctly. Let’s head back to the documentation and study the returned object: It is a dict, containing a dict “data,” containing an array “timelines” containing dicts, containing an array “intervals” containing dicts, containing a dict “values” that finally contains our values. Or simply put in Python to get the temperature of the first data point:

t = response.json()['data']['timelines'][0]['intervals'][0]['values']['temperature']

Since ‘intervals’ is an array of unknown length, let’s cycle through it using a for loop:

    print("Weather Forecast")
print("================")

results = response.json()['data']['timelines'][0]['intervals']
for daily_result in results:
date = daily_result['startTime'][0:10]
temp = round(daily_result['values']['temperature'])
print("On",date,"it will be", temp, "F")

Resulting in something like this:

% python3 weather.py
Weather Forecast
================
On 2021-04-24 it will be 73 F
On 2021-04-25 it will be 73 F
On 2021-04-26 it will be 77 F
On 2021-04-27 it will be 80 F
On 2021-04-28 it will be 76 F
.
.
.
%

And just like that, with just a few simple lines of code, and a single Python Weather API call, we’ve created a weather forecast for your desired location for the next few days. This is just a glimpse of what’s possible with the Tomorrow.io weather API – Sign up today and get started for free!  

More from Tomorrow.io

Energy Companies Can Manage Price Spikes with Weather Intelligence

Weather Widgets to Wow Your Website Visitors With

CNN Announces Tomorrow.io’s $20M Satellite Contract With The US Air Force

Register for ClimaCon 2021

ClimaCon is a completely free, digital conference. Register below.