TL;DR:
- Python makes it easy to access weather APIs for daily forecasts.
- Install Python3, get an API key, and find coordinates for your desired location.
- Use Tomorrow.io’s API documentation to generate Python code for weather forecasts.
- Expand the code snippet into a Python program to get weather forecasts.
- Parse and format the output of the weather API to display a nice table of daily forecasts.
Python is becoming an increasingly popular programming language, and one of its many advantages is its ease of making 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
How To Access a Weather API with Python
Letโs go through what you need to write, run this code successfully, and make API requests.
If you’re new to Python and just starting out, consider reviewing Pythons’s guide for beginners.
We’ve also included a refresher video explaining the capabilities of a weather API.
1.ย Python3ย must be installed on your computer
There are a few ways to installย Python3:ย
- Download official Python distributions from Python.org
- Install from a package manager
- Install specialized distributions for:
- Scientific computing
- Embedded systems
- IoT (Internet of Things)
2. Get an API Key for the Tomorrow.io Weather API
You must create an account to get your weather API key from Tomorrow.io.
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 your location’s latitude and longitude, search or scroll your map to your place of interest.
- Right-click the specific spot on the map, and youโll see two numbers, such as โ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 is 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โ is 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. It will enable you to better understand what you can do with the weather API.
We will work withย this example to retrieve timelines via a weather API.
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*, with an asterisk denoting a required parameter.
Paste your coordinates from earlier in the text field, 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)
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. When you drill down, eventually, youโll seeย โtemperatureโ: xx.xx, which is your first value.
And 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, it 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 on 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, such as Visual Studio Code, and copy the code to a file called weather.py.
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
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.
Below is short overview video of this process.
You can also 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 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.