Python Weather API Script
In this article, you will learn how to develop a weather API script using the Python programming language.
There are several APIs available to get weather information. In this tutorial, we will use the OpenWeatherMap API. Our weather API is easy to use and is advanced enough to utilise and convey weather information. This information is conveyed utilising standard HTTP demands, with our climate API returned in standard industry organizations, for example, XML and JSON. It allows developers and programmers to access current, past, and future weather data for use in apps and on websites. It permits organizations, designers, and developers to embed weather information into their applications and sites.
Before using the OpenWeatherMap API, we will have to get an API key from its official website. So, click on the given link, create an account, and get your API key.
https://openweathermap.org/api
It offers both free and commercial subscriptions. The free subscription provides 60 calls per minute. More than this requires a paid subscription starting at $40 per month.
Import Modules
To develop this application, we need two modules- requests and JSON. The requests module makes an HTTP request to the specified web page using Python and returns a response object. There's no need to manually add query strings to your URLs, or to form-encode your POST data. We can install this using the pip tool.
pip install requests
JSON is a data format consisting of key-value pairs. It is widely used to transmit and receive data in JSON format between a server and a web application. The JSON module is an in-built package of Python. Here, we used this application to work with the response. So, let's create a Python file and import both modules at the top.
import requests, json
Initialize URL, API and City
Next, we will initialize the URL, API, and the City. Make sure to replace the 'YOUR_API_KEY' with the generated API.
# API base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name
CITY = "New Delhi"
# Your API key
API_KEY = "YOUR_API_KEY"
# updating the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
Send a GET Request and receive response
Next, we will send a get request using the requests module and receive a response in the JSON format.
response = requests.get(URL)
data = response.json()
This response contains a main dict block from which we can extract the weather information using the JSON module.
main = data['main']
Complete code: Python Weather Script
Here, we have merged the above codes to get the complete code for getting weather information.
# importing modules
import requests, json
# API base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name
CITY = "New Delhi"
# Your API key
API_KEY = "YOUR_API_KEY"
# updating the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# Sending HTTP request
response = requests.get(URL)
# checking the status code of the request
if response.status_code == 200:
# retrieving data in the json format
data = response.json()
# take the main dict block
main = data['main']
# getting temperature
temperature = main['temp']
# getting feel like
temp_feel_like = main['feels_like']
# getting the humidity
humidity = main['humidity']
# getting the pressure
pressure = main['pressure']
# weather report
weather_report = data['weather']
# wind report
wind_report = data['wind']
print(f"{CITY:-^35}")
print(f"City ID: {data['id']}")
print(f"Temperature: {temperature}")
print(f"Feel Like: {temp_feel_like}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {weather_report[0]['description']}")
print(f"Wind Speed: {wind_report['speed']}")
print(f"Time Zone: {data['timezone']}")
else:
# showing the error message
print("Error in the HTTP request")
The above code returns the following results on execution-
Related Articles
Web scraping Python BeautifulSoupFind the stop words in nltk Python
Install NLTK for Python on Windows 64 bit
Python gmplot to add google map on a web page
Vader Sentiment Analysis Python
isalpha Python
Python YouTube Downloader Script
Python project ideas for beginners
Pandas string to datetime
Fillna Pandas Example
Lemmatization nltk
How to generate QR Code in Python using PyQRCode
OpenCV and OCR Python
PHP code to send SMS to mobile from website
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml