Tomorrow.io’s Microwave Sounder Satellites Just Captured Critical Atmospheric Insights. 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.
May 1, 2024· 7 min

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.

    But what do you need to get started, and how do you use a weather API in Python?

    What You Need To Access a Weather API with Python

    Let’s review 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. Ensure that Python3 is 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.

    tomorrow.io's resilience platform supports the intermodal transportation industry

    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:

    • unitscan be metric or imperial
    • timestepstime between data points. Let’s choose 1d (one day) so that we get a data point every 24 hours.
    • startTimeIf 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

    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 Tomorrow.io’s Python Weather API.

    Sign Up for the Tomorrow.io Weather API for Free

    Try Now