Get Weather Data Using Python and Openweather API

by tinkerbuildlearn in Teachers > Coding

7990 Views, 4 Favorites, 0 Comments

Get Weather Data Using Python and Openweather API

OpenWeather-Logo.jpg

Prerequisite:

  1. API key and url from openweather site.
  2. Request (for HTTP requests) library for Python.

Get API Key and URL From Openweather.org

OpenWeather-api.png
OpenWeather-api2.png
OpenWeather-api3.png

  1. Create account in https://openweathermap.org
  2. After you login you will get the API key as shown in image.
  3. Go to the API option
  4. Go to API doc option as shown in image.
  5. Now copy the link to paste it in the pyhton code.

Install Request Library for Python

request install.png

  1. Open cmd and type this (pip install requests)
  2. now open pyhton shell
  3. And type import requests
  4. if there is no error you are good to go.

Python Code

import requests

city = input("Enter City:")

url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={Enter your API key here}&units=metric'.format(city)

res = requests.get(url)
data = res.json()

humidity = data['main']['humidity']
pressure = data['main']['pressure']
wind = data['wind']['speed']
description = data['weather'][0]['description']
temp = data['main']['temp']

print('Temperature:',temp,'°C')
print('Wind:',wind)
print('Pressure: ',pressure)
print('Humidity: ',humidity)
print('Description:',description)