Intermediate

In this article we will cover how you can get current weather data using a weather API in python 3. For this task we can use various types of weather APIs that are available based on either satellite data, observatory data, or even crowdsourced data. Including weather information in your next python 3 program will help to add extra value or may even be a core part of your application whether it be for display in a dashboard visualisation or for a data science algorithm.

Overview Of Weather APIs

Here is an overview of most popular free weather APIs that’s available and can be called using python.

API NameFree / PaidFeatures
1. OpenWeatherMap Freemiumcurrent weather
weather forecasts
historical weather
weather stations
weather alerts
2. Weatherbit Freemium Current Weather Data
5 Day Forecast
Severe Weather Alerts
48 Hour Forecast
16 Day Forecast
3. AccuWeather free trial/
paid plans
Forecast
Current Conditions
Alerts
Imagery
4. Dark Sky FreemiumCurrent weather conditions
Minute-by-minute forecasts
Hour-by-hour and day-by-day forecasts
Hour-by-hour and day-by-day observations
Severe weather alerts in some locations
(as of 2022 will be discontinued)
6. ClimaCell Freemium Realtime, Short Term and Hourly Forecasts

For this article we will concentrate on using the openweathermap in python as an example to help show how you can get weather information easily. With Openweathermap you can:

  • Use basic feature for free
  • Create many API keys
  • Get current weather data, weather forecasts, historical weather, weather stations, weather alerts and other weather info

To make this easier to follow, the article is divided into a few steps. Here is an overview of those steps.

  1. Install pyowm (Python Open Weather Map API)
  2. Import pyowm to our project
  3. Get API Key
  4. How to configure pyowm easily
  5. Get current Weather Data
    • Get Temperature data
    • Get Humidity data
    • Get Wind data
    • Get Cloud data
    • How to access more data
  6. Get Forecast Weather
    • Forecast with no specific time
    • Forecast for specific time

Step 1 : Install pyowm (Python Open Weather Map API)

To get weather data we use the python pyowm (Python Open Weather Map) in our code. This was released under MIT License (MIT) and encapsulates a lot of the steps that are normally required to call the API. You may call the API’s directly as well but using this library simplifies a lot of the steps required. The library is well maintained and has at least yearly updates since its creation in 2013.

To begin with we will need install the library using pip (Package Installer for Python).

[ shell ]
pip install pyowm

Step 2 : Import pyowm to our project

In previous step we have successfully installed pyowm. In this step we are going to import pyowm to our project to use its functions. The main code will be written into a file named main.py and you can import the library with the following code as a first step. The program will not do anything yet.

#[ insert to main.py ]
import pyowm # import Python Open Weather Map to our project.

Step3 : Get OpenWeatherMap Weather API Key

To get data from API we need to get an API key for this go to https://home.openweathermap.org/users/sign_up to sign up to an account. Open Weather Map is a London based company that provides weather data service that was started back in 2014 which uses a series of convolutional neural network/machine learning data science models for weather forecasting and historical data calculation. Many individuals and even Fortune 500 companies have used the service to create things from a weather app all the way to support their operations such as in insurance, utilities, consumer services. In addition to be fast, the JSON weather API data is very convenient to manage.

To begin with when you sign up, you will be provided with the “Create New Account” screen:

You will need to be over 16 years of age and agree to the terms of service. In the next screen there will be some statistical details which will be collected:

Finally, a notification will be sent for you to confirm through a link sent to your email.

Once you have verified, you will get the following notification, then you can create the key to use the free weather API.

To get the API key, go to the menu from your user profile and chose the “My API Keys” option:

You will then be taken to the My API Keys page where you can manage all your different keys. The API Key acts like a password which you can use to access your account’s access to the json weather API. If you have multiple weather app programs, it is best to create a new key for each app. The reason is that if one of your API key’s gets compromised (e.g stolen), then you just need to change the API key just for that weather app so it can continue to search the weather data with little updates.

You will have a default key that is generated which you can copy and use in your program. Please copy it. If you want to create a new one, you can click on the “Generate” button, and then provide a “API key name” – this is just a descriptive text for yourself so that you can help manage all the different keys. You can use this to name which weather app is using this given key:

Step 4 : Get Current Weather Data in Python

In this step we are going to configure pyown json weather API to get current weather data. First, we need to store our API key to a variable. Then, we have to give that key to OWM( ... ) function in and get the return object. After getting the OWM object, we need to say the location using weather_at_place( ... ) function. This is because ultimately openweathermap is generally used as a local weather API. You can then finally retrieve data from the python weather API with get_weather( ... ) to return the data in a dictionary.

import pyowm, datetime

api_key = '<Your API Key>'     #your API Key here as string
owm = pyowm.OWM( api_key ).weather_manager()     # Use API key to get data

def print_weather( data):
    ref_time = datetime.datetime.fromtimestamp( data.ref_time ).strftime('%Y-%m-%d %H:%M')
    print( f"Time\t\t: {  ref_time }" )
    print( f"Overview\t: { data.detailed_status}" )
    print( f"Wind Speed\t: { data.wind()}" )
    print( f"Humidity\t: { data.humidity}" )
    print( f"Temperature\t: { data.temperature('fahrenheit')}" )
    print( f"Rain\t\t: { data.rain}" )
    print("\n")

def get_current_weather():
    weather_api = owm.weather_at_place('Bangalore')  # give where you need to see the weather
    weather_data = weather_api.weather          # get out data in the mentioned location

    print("***Current Weather***")
    print_weather( weather_data )
    print("\n")

if __name__ == '__main__':
    get_current_weather() 

That’s all that’s required! The output will be as follows:

So what’s happening in the code is that the call to owm.weather_at_place('Bangalore') will get live weather at Bangalore. You can provide any location in the globe you wish. The data is then returned in the object weather_data which has the following data fields:

  • weather_data.status – Single word status of the temperature (Rain, Thunderstorm, etc)
  • weather_data.detailed_status – provides a short description of the weather
  • weather_data.ref_time – The time the weather applies. This is a timestamp and hence will need to be converted to a readable format using the datetime.datetime library
  • weather_data.wind() – Returns a dictionary with the wind speed
  • weather_data.humidity – Returns the humidity
  • weather_data.temperature('<format>') – Returns the min, max, and current temperature in the requested format of either celsius or fahrenheit.
  • weather_data.rain – Provides the amount of rain in millimetres that have fallen in the last 1 hour (1h) or 3 hours (3h)
  • weather_data.sset_time – Time (as a timestamp) of sunset
  • weather_data.srise_time – Time (as a timestamp) of sun rise
  • weather_data.pressure – Pressure at sea level
  • weather_data.snow – How much snow
  • weather_data.visiblity_distance – Visibility distance in meters
  • weather_data.clouds – Percentage of cloud coverage
  • weather_data.weather_icon_url() – Get an icon for the current weather (such as https://openweathermap.org/img/wn/11n.png). All icons come from openweathermap api

Step 5 : Get Forecast  Weather API Data in Python

To get a forecast, only a slight modification to the above code is required. You just need to call the same openweathermap manager but with the additional function call to owm.forecast_at_place( '<location>', '3h').forecast. The function must be called with the second parameter of 3h for the free weather api and this provides a 5 day forecast in 3 hour intervals. For other options you will need to chose one of the paid options. The returned forecast object is in fact the same object format as the weather_data object mentioned in step 5.

The full code is as follows:

import pyowm, datetime

api_key = '<your API key>'     #your API Key here as string
owm = pyowm.OWM( api_key ).weather_manager()     # Use API key to get data

def print_weather( data):
    ref_time = datetime.datetime.fromtimestamp(  data.ref_time ).strftime('%Y-%m-%d %H:%M')
    print( f"Time\t\t: {  ref_time }" )
    print( f"Overview\t: {data.detailed_status}" )
    print( f"Wind Speed\t: { data.wind()}" )
    print( f"Humidity\t: { data.humidity}" )
    print( f"Temperature\t: { data.temperature('fahrenheit')}" )
    print( f"Rain\t\t: { data.rain}" )
    print("\n") 
    
def get_current_weather():
    weather_api = owm.weather_at_place('Bangalore')  # give where you need to see the weather
    weather_data = weather_api.weather          # get out data in the mentioned location

    print("***Current Weather***")
    print_weather( weather_data )
    print("\n")

def get_forecast_weather():
    print("***5 day forecast Weather***")
    for item in owm.forecast_at_place('Bangalore', '3h').forecast:
        print_weather( item )

if __name__ == '__main__':
    get_current_weather()
    get_forecast_weather()

Output is as follows:

Note that the time stamp shows the time that forecast applies to and it is in 3 hour intervals

Conclusion

This open data weather example should get you started in your next data science weather app with the easy to follow python weather API. The above openweathermap python example code can be readily copied and should save you time in getting the right data. You will have to be mindful of the timezone and also the location that you chose. In addition to specifying the name of the location, you can also specify latitude and longitude of a given location which the openweathermap team can provide the data based on their machine learning models and the sources of observatory and weather station data that they subscribe to.

Good luck with your application, and don’t forget to subscribe to our newsletter!

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden