Tomorrow.io's Resilience Platform is Here. Learn More.

X
Gareth Goh
By Gareth Goh
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.
Shahar Wider
Reviewed By Shahar Wider
Shahar Wider
Shahar Wider
As Director of Engineering at Tomorrow.io, Shahar Wider oversees the engineering group. In his role, he builds engineering-product-marketing capabilities and leads initiatives to scale the company's weather intelligence platform. With over 8 years of technical leadership experience, including 5 years in management roles, Shahar specializes in architecting innovative products powered by cutting-edge technologies. He believes in empowering teams to deliver robust solutions that drive business impact. Shahar holds a B.S. in Computer Science and enjoys staying on top of emerging tech trends.
Mar 26, 2024ยท 6 min, 52 sec

How To Create Daily Forecasts with A Python Weather API

climacell api v4

    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.

    1. 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.
    2. Right-click the specific spot on the map, and youโ€™ll see two numbers, such as โ€œ37.8199ยฐ N, 122.4783ยฐ W.โ€
    3. 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)

    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. 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.

    Sign Up for the Tomorrow.io Weather API for Free

    Try Now