How to Extract Weather Data from Rapid API in Python?

Posted in /  

How to Extract Weather Data from Rapid API in Python?
vinaykhatri

Vinay Khatri
Last updated on April 18, 2024

    There are many weather APIs present out there that can share real-time weather reports. We can use those APIs to get the current weather detail for a specific place or location.

    In this Python tutorial, we will explain step-by-step how to extract weather data from Rapid API in Python. To make this tutorial easy to understand, we have divided it into the following three sections:

    1. 1st section will discuss signing up on the RapidAPI website, subscribing to the Open Weather Map and API, and getting the API key.
    2. In the 2nd section, we will install the Requests library that we will use in this tutorial.
    3. 3rd section will detail writing the Python program to get the weather report for a specific place.

    How to Extract Weather Data from Rapid API in Python?

    Section 1: Get RapidAPI Key for Open Weather Map

    RapidAPI is the world's largest online market for public APIs. It has hundreds of thousands of open-source and proprietary APIs for developers. With RapidAPI, we just have to subscribe to the API we wish to use, and we get its API key, and with the API key and simple HTTP requests, we can connect to the API and get the API Data.

    For this tutorial, we will be using the Open Weather Map API, which is one of the best weather APIs available on rapidapi.com.

    To use any of the rapidapi.com APIs, we need to signup first. Only then can we subscribe to any API and get its API key.

    You can either create a new account on rapidapi.com or sign up with your other social media accounts like Google and Facebook.

    Subscribe to the Open Weather Map API

    After logging in or signing up on rapidapi.com, you need to subscribe to the Open Weather Map API for the API key.

    Select The plan

    After clicking on the Subscribe to Test button, you need to select the plan you want to pick. You can select the Basic plan, which is free to use and has only limited hits, which is around 500 per month. This is enough to get started with this API.

    API Key

    After you select the Basic plan, you can click on the Test Endpoint button, and you will be redirected to the Open Weather Map dashboard. Here, you can check your API key for the Open Weather Map API.

    On the right side, you can also see a Python code snippet and response that tells how this API works and how it responds.

    Section 2: Installing the Requests Library

    In this tutorial, we will be using the Python requests library to send GET requests to the API endpoint URL, along with the API key and query. The requests library is the de-facto Python library to send HTTP requests, and many other libraries also use it for sending HTTP requests.

    To install the requests library for your Python environment, you can run the following pip install command:

    pip install requests

    Section 3: How to Get Weather Data in Python?

    We have subscribed to rapidapi.com's Open Weather Map API and got its API key, and installed the Python requests library to send HTTP requests to the API endpoint.

    So now, let's get started with Python code. Let's begin with importing the requests and datetime modules.

    import requests
    
    from datetime import datetime

    Now, let's initialize the API URL endpoint and API key variables.

    api_url = "https://community-open-weather-map.p.rapidapi.com/weather"
    api_key="<ENTER YOUR API KEY HERE>"

    After defining the URL and the API key, let's define the place and query dictionary.

    place = "Delhi"
    query = {"q":place}

    place is the location whose weather report you want to find out, and the query is the Python dictionary with the q key and place as a value.

    Next, let's define the header dictionary that represents the header data for the get request. It contains the Host API URL and api_key.

    headers = {
             'x-rapidapi-key': api_key ,
             'x-rapidapi-host': "community-open-weather-map.p.rapidapi.com",
             }

    Now send the HTTP get request to api_url with the headers and params parameters.

    response = requests.get(api_url, headers=headers, params=query)

    The API URLs send back the response in the JSON format, so we need to convert the JSON data to a dictionary using the json() function.

    data = response.json()
    Now, we have the data in the dictionary. Next, let's print the data.
    
    print("-----------Location------------------ ")
    print( data["name"], data["sys"]["country"])
    
    print("-------------Date:--------------------- ")
    print("Sunrise: ", datetime.fromtimestamp(data["sys"]["sunrise"]))
    print("Sunset: ", datetime.fromtimestamp(data["sys"]["sunset"]))
    
    print("-------------------------Weather-------------------------")
    print("Description:", data["weather"][0]["description"])
    
    print("--------------------------Temperature------------------ ")
    print("Current Temperature: " ,f"{round(data['main']['temp']-273.15,2)} C" )
    print("Max Temperature: " ,f"{round(data['main']['temp_max']-273.15,2)} C" )
    print("Min Temperature: " ,f"{round(data['main']['temp_min']-273.15,2)} C" )

    The API returns temperature in Kelvin. To convert it into Celsius, we have subtracted the temperature from 273.15, and rounded off the decimal value up to 2 digits using the round() function. The sunrise and sunset times are returned in a timestamp, and that's why we have used the Python datetime fromtimestamp() function to convert the timestamp to readable date and time. Now put all the code together and execute.

    Python Program to Get Weather Data Using RapidAPI

    import requests
    from datetime import datetime
    
    api_url = "https://community-open-weather-map.p.rapidapi.com/weather"
    api_key="<ENTER YOUR API KEY HERE>"
    
    place = "Delhi"
    
    query = {"q":place}
    
    headers = {
        'x-rapidapi-key': api_key ,
        'x-rapidapi-host': "community-open-weather-map.p.rapidapi.com",
        }
    
    response = requests.get(api_url, headers=headers, params=query)
    
    data = response.json()
    
    print("-----------Location------------------ ")
    print( data["name"], data["sys"]["country"])
    
    print("-------------Date:--------------------- ")
    print("Sunrise: ", datetime.fromtimestamp(data["sys"]["sunrise"]))
    print("Sunset: ", datetime.fromtimestamp(data["sys"]["sunset"]))
    
    print("-------------------------Weather-------------------------")
    print("Description:", data["weather"][0]["description"])
    
    print("--------------------------Temperature------------------ ")
    print("Current Temperature: " ,f"{round(data['main']['temp']-273.15,2)} C"  )
    print("Max Temperature: " ,f"{round(data['main']['temp_max']-273.15,2)} C"  )
    print("Min Temperature: " ,f"{round(data['main']['temp_min']-273.15,2)} C"  )

    Output

    -----------Location------------------ 
    Delhi IN
    -------------Date:--------------------- 
    Sunrise: 2021-02-15 06:59:45
    Sunset: 2021-02-15 18:11:03
    -------------------------Weather-------------------------
    Description: haze
    --------------------------Temperature------------------ 
    Current Temperature: 26.49 C
    Max Temperature: 29.0 C
    Min Temperature: 22.78 C

    Conclusion

    In this tutorial, we learned how to extract weather data from Rapid API in Python. The Python program only accesses the current weather report because the Basic plan only allows us to access a single weather report. Nonetheless, there are many weather APIs present on rapidapi.com if you want to get weather reports for multiple locations.

    People are also reading:

    Leave a Comment on this Post

    0 Comments