Tomorrow.io Just Successfully Captured Precipitation Scans from Our Space Radars. Learn More

X
Gareth Goh
Gareth Goh
Apr 27, 2023· 6 min
Gareth Goh
Gareth Goh
Gareth Goh is a product marketing manager at Tomorrow.io, working on the company's enterprise and SMB products. He previously worked at DataRobot, an AI startup, and InsightSquared, a sales analytics startup, in the Boston area. When he isn't diving into weather technology he enjoys spending time with his young baby and watching sports.

How To Create Daily Forecasts with A Python Weather API

climacell api v4

Python is becoming an increasingly popular programming language, and one of its many advantages is how easy it is 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 for any given location anywhere on Earth.

What You Need To Access a Weather API with Python

Let’s go through what you need to write and run this code successfully and make API requests.

1. Python3 must be installed on your computer

There are a few ways to install Python3: you can download official Python distributions from Python.org, install from a package manager, or install specialized distributions for scientific computing, embedded systems, or IoT.

2. Get an API Key for the Tomorrow.io Weather API

To get your weather API key from Tomorrow.io you must sign up and create an account. When you create an account, your personal API key will be automatically created for you to use in your application.

3. Find the coordinates of your desired location on earth

Finding the coordinates for your desired location is quite easy using your favorite online maps.

  • Let’s use Google Maps as an example. To find the latitude and longitude of your location 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.8199° N, 122.4783° W”.
  • Click on the numbers, and they will get copied to your clipboard.

Our advice would be to store your desired coordinates in the 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.

How To Make a Basic Weather API Call in Python

In order to make a basic weather API request, or API Call, you’ll need two lines of code that are sufficient for a basic Python request:

import requests and response = requests.request(“GET”, url, params=querystring).

So, what is happening here?

import requests add 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)

How To Use Tomorrow.io’s API Documentation to Generate Python Code

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 Tomorrow.io’s API documentation comes in handy and will enable you to better understand what you can do with the weather API.

We will work with this example for retrieving timelines.

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 are automatically added to the Python code as part of the dict that will be submitted as the parameters: Retrieve Timelines (Basic)

weather API python documentation

Looking back at our query parameters, we notice that the following parameter, fields*, is also required.

Click ‘Add’ and enter the temperature.

‘Try it’ again, and the query should now be successful, and return “200 OK”.

Just below, you can 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 data points. 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.

How To Expand a 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.

We recommend putting the query string 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)

How To Parse and  Format the Output of a Weather API

After creating a file with the code, you’ll want to pretty up the cryptic JSON object and print it in a nice table.

If you have experience with JSON, you will know that it can be unforgiving and that nested elements have to be parsed correctly.

You can head back to the documentation and study the returned object document.

It is a dict, containing a dict of “data,” containing an array of “timelines” containing dicts, containing an array “intervals” containing dicts, containing a dict “values” that finally contains our values.

Or simply put it 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 weather forecast can be used to stay up-to-date with current weather, create weather reports, and provide weather conditions to your application.

This is just a glimpse of what’s possible with the Tomorrow.io weather API.

Sign Up for the Tomorrow.io Weather API for Free

Try Now