People used to have a desire to understand and predict the weather since ancient times. They were noticing the hundreds of signs, trying to guess whether it will be snowing or raining tomorrow and still were wrong in most cases. Today everyone can become an unmistakable oracle. Moreover, with the help of a simple OpenWeatherMap API via RapidAPI you can endow your applications with an almost supernatural power to accurately predict tomorrow’s weather. Such ability is useful in many industries whether you are developing a travel application, an event management system or implementing smart city infrastructure management.
In order to find OpenWeatherMap API section, enter its name in the search box at the RapidAPI service or go to the “Weather” category from “All Categories” list and select this API from the list. Basic OpenWeatherMap API through RapidAPI is free, so you can use it freely but no more than 60 calls per minute.
OpenWeatherMap Endpoints
All of the API’s sections on the RapidAPI have such subsections as Endpoints, API Details, and Discussions. The main information on how to use the API is placed in the Endpoints subsection. If you need some additional details, you can find them under the API Details subsection. Also, you can ask support or community about something related to the API in the Discussions subsection.
The API functionality is presented in the Endpoints subsection of the OpenWeatherMap API section. The window is divided into three main areas. The first area on the left displays a list of available endpoints (tasks), each task displays its HTTP method. For the OpenWeatherMap API, the following tasks are presented:
- Current Weather Data – Using this kind of requests, you can get weather data in any location on the earth. The current weather data is updated online based on data from more than 40,000 weather stations.
- Forecast Weather Data – You can receive weather forecast in any location on the earth. The flexible algorithm of weather calculation provides weather data not only for cities but for any geographic coordinates. It is important for megapolises, for example, where weather is different on opposite city edges. You can get forecast data every 3 hours. The 3 hours forecast is available for 5 days. All weather data can be obtained in JSON or XML formats.
- Search Weather Data – You can search for data by city name. Put the city name or its part and get the list of the most proper cities in the world. Example – Lon or Lond or London. The more precise city name you put, the more precise list you will get. To make it even more accurate, put the city name or its part, then put a comma and write the name of the county or 2-letter country code. You will get all the proper cities in the chosen country. For example – Lon, UK or Lon, GB or London, GB or Lon, England.
For each endpoint, you can fill in required parameters in the second area of Endpoints subsection window and immediately test it by clicking the “Test Endpoint data” button. The response for current endpoint will be displayed in the third area on the right.
And here is the right side of the window showing the sample JSON response:
We should also mention the Request Snippet block. You can choose your preferred programming language and immediately get the code that implements the task that you have just tested. The OpenWeatherMap API is now available through RapidAPI for such programming languages as:
Example of API Calls
For example, here’s NodeJS snippet for getting current weather through OpenWeatherMap API (Weather API Javascript):
unirest.get("https://community-open-weather-map.p.rapidapi.com/weather?callback=test&id=2172797&units=%22metric%22+or+%22imperial%22&mode=xml%2C+html&q=London%2Cuk") .header("X-RapidAPI-Host", "community-open-weather-map.p.rapidapi.com") .header("X-RapidAPI-Key", "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") .end(function (result) { console.log(result.status, result.headers, result.body); });
Python snippet for weather forecasting through OpenWeatherMap API:
response = unirest.get("https://community-open-weather-map.p.rapidapi.com/forecast?q=london%2Cuk", headers={ "X-RapidAPI-Host": "community-open-weather-map.p.rapidapi.com", "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } )
C# snippet to search weather data through OpenWeatherMap API:
Task<HttpResponse<MyClass>> response = Unirest.get("https://community-open-weather-map.p.rapidapi.com/find?type=link%2C+accurate&units=imperial%2C+metric&q=london") .header("X-RapidAPI-Host", "community-open-weather-map.p.rapidapi.com") .header("X-RapidAPI-Key", "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") .asJson();
One important thing we want to focus your attention on is the Header Parameters section:
X-RapidAPI-Host and X-RapidAPI-Key parameters are used for identification and billing purposes. You should include these parameters in all requests generated from any environment. While viewing endpoints in a browser, you can change the RapidAPI Project to change the key. Projects (apps) are created on the RapidAPI Dashboard page (Add New App tab):
RapidAPI Dashboard provides additional useful functions. You can track all the API calls through RapidAPI in one place, analyze errors and billing information.
How to get an OpenWeatherMap API Key?
It’s easy. When you sign up for a free RapidAPI user account, you’ll receive a single API key for all APIs on the platform, including OpenWeatherMap API. Click Connect to API to get started!
How to Build a Weather App in Python
In this quick tutorial, we’ll show you how to build an app to estimate weather conditions by travel destination (using OpenWeatherMap API Example).</p
Best Travel Destination Estimation (by Weather Conditions) App
In order to demonstrate the capabilities of the OpenWeatherMap API, we will write a small Python application that can help us with choosing the best city for the next trip. At the input, it will receive a list of several cities, and at the output, it will show the rating of the best cities for travel (assessing each city by the number of predicted cloudless days in the near future and by the future average temperature).
Step 1. Import weather data into a Python program
Imagine that we choose between three cities: London, Porto, and Paris. City names along with country codes will be stored in cities list.
Also, note that we have slightly altered the Python snippet that generates the RapidAPI service for accessing the endpoint. We replaced the Python module unirest with requests since unirest is not fully supported in Python 3.
As we are predicting the weather for several cities, we will create city_forecast
function, which will receive the name of the city and using Forecast Weather Data endpoint return the dictionary with the weather forecast for this city. When calling endpoint, we will specify the necessary parameters (in our case, these are our credentials and the “q” parameter, into which we will enter the country code and the name of the city for which we want to see future weather).
Credentials will be stored in credentials.py file. RapidAPI credentials can be obtained in the My Apps section of the RapidAPI service by creating a new app or copying them from the “Security” subsection of one of the already created apps.
We will keep weather predictions for cities in weather_dict
.
import requests import credentials import re cities = ["London,uk", "Porto,pt", "Paris,fr"] weather_dict = {} def city_forecast(city): response = requests.get( "https://community-open-weather-map.p.rapidapi.com/forecast?q="+city, headers={ "X-RapidAPI-Host": "community-open-weather-map.p.rapidapi.com", "X-RapidAPI-Key": credentials.rapidapi_key }, ) return response.json() for city in cities: weather_dict[city] = city_forecast(city)
Step 2. Prepare data for estimation
Weather forecast for each city for the next five days is available now in the weather_dict [<city_name>] ['list']
dictionary. The forecast is divided into three hours blocks, and each block indicates the time (for example, 21:00:00) for which the prediction is made. Since we are interested in the average daily temperature, we need blocks with a specified time from 10:00:00 to 19:00:00. To select predictions for daytime only, we use regular expressions.
We will create get_day_weather
function that will return True if the forecast time is between 10:00:00 and 19:00:00. After that, we put it in the filter function, select the predictions of only the day temperature and save them in day_weather
dictionary.
def get_day_weather(pred): pattern = re.compile("s(?P<hour>dd):dd:dd") t = pattern.search(pred['dt_txt']) if int(t.group('hour')) >= 10 and int(t.group('hour')) <= 19: return True return False day_weather = {} for city in weather_dict.keys(): day_weather[city] = list(filter(get_day_weather, weather_dict[city]['list']))
Step 3. Estimate the best city for travel
While having data about daytime temperatures and a description of the cloudiness level (which is located by the key ['weather'] [0] ['description']
in each forecast block), we can create travel_estimator
function. After receiving the mentioned data, this function will calculate the average temperature, the number of cloudless weather predictions for each city and return the dictionary with this information.
Since we want to rank our cities somehow, we will sort them by the number of cloudless weather predictions. The sorting criterion can be much more complex, we could calculate a single aggregate indicator that takes into account the weather, average temperature, and any other parameters, but for our purposes (and since cloudless weather is the most important for us) sorting by cloudlessness level is enough.
def travel_estimator(weather_stat): estimation = {} for city in weather_stat.keys(): estimation[city] = {} estimation[city]['clear_sky_count'] = 0 estimation[city]['av_temp'] = 0 for prediction in day_weather[city]: estimation[city]['av_temp'] += prediction['main']['temp'] if prediction['weather'][0]['description'] in ['clear sky', 'few clouds']: estimation[city]['clear_sky_count'] += 1 estimation[city]['av_temp'] = round(estimation[city]['av_temp'] / len(day_weather[city]), 2) # convert temperature to celsius estimation[city]['av_temp_cels'] = round(estimation[city]['av_temp'] - 273.15, 2) return estimation travel_rating = travel_estimator(day_weather) # sort cities by clear sky forecasts sorted_travel_rating = sorted(travel_rating.items() , key=lambda x: x[1]['av_temp_cels'] ) for city in sorted_travel_rating: print(city[0]) print('Clear sky forecasts:', city[1]['clear_sky_count']) print('Average temperature:', city[1]['av_temp_cels'], "C") print('n')
App Output:
Porto,pt Clear sky forecasts: 7 Average temperature: 16.74 C London,uk Clear sky forecasts: 4 Average temperature: 18.36 C Paris,fr Clear sky forecasts: 3 Average temperature: 19.07 C
The app is ready! Now we won’t waste our time on the pains of choice and quickly find out where we’ll go in the next trip. By the way, Porto turned out to be the winner in our rating. An unexpected victory as we were betting on Paris.
Conclusion
In this article, we showed how to quickly and easily embed a weather API in our applications (Open Weather Map API in particular) and also explained when it might be useful.
Of course, the capabilities of a weather API are not limited to our example. By collecting the history of weather changes and using the power of machine learning, we can predict the weather on our own. The ability to make our own predictions using machine learning models will be useful in those cases when there is no data available for classical models, and will also enable us to predict the weather not just at the city level, but at the street or even at home level. All we need is historical weather data that can be collected using a lot of weather APIs. But this is a topic for another article.
More Weather APIs
To browse more top weather APIs, check out this blog post listing the best free weather APIs (such as AccuWeather API, DarkSky Weather API, Yahoo Weather API, NOAA Weather API.. etc.) to help you get started!
heron anson herald vas says
import requests
import credentials
import re
cities = [“London,uk”, “Porto,pt”, “Paris,fr”]
weather_dict = {}
def city_forecast(city):
response = requests.get(
“https://community-open-weather-map.p.rapidapi.com/forecast?q=”+city,
headers={
“X-RapidAPI-Host”: “community-open-weather-map.p.rapidapi.com”,
“X-RapidAPI-Key”: credentials.rapidapi_key
},
)
return response.json()
for city in cities:
weather_dict[city] = city_forecast(city)
in this code its giving me a error credentials doest have attribute rapidapi_key what should i do?