Using Python with the OpenWeathermap.org API

In these notes, we will explore how to utilize Python with a free weather API (Application Programming Interface) to retrieve the current weather for a specific city.

What You Need to Install and Obtain

  • Python and the 'requests' package
  • Access to a Weather API
  • Basic coding knowledge

Install requests package

$ python -m pip install requests  #install package
$ python -m pip show requests #display requests version

image-20230927111555155.png

Weather API

Login to openWeathermap.org or register a new account .

https://home.openweathermap.org/users/sign_in

Get your API Key
image-20230927111931734.png

In those images, the key is your API key from OpenWeatherMap.org

Coding

import datetime as dt
import requests

#api key 
api_key = 'YOUR API KEY'

# 温度转换 function 
def kelvin_to_celsius_fahrenheit(kelvin):
    celsius = kelvin - 273.15
    fahrenheit = celsius * (9/5) +32
    return celsius, fahrenheit

#等待用户输入城市名称
location = input('Please enter a city name: ')

#请求
base_url = 'https://api.openweathermap.org/data/2.5/weather?'
url = base_url + 'appid=' + api_key + '&q=' + location

#获取API结果(数据)
response = requests.get(url).json()
# print(response)  # check API information 

#取数据中的值(字典)
temp_kelvin = response['main']['temp']
temp_celsius, temp_fahrenheit = kelvin_to_celsius_fahrenheit(temp_kelvin)
feels_like_kelvin = response['main']['feels_like']
feels_like_celsius, feels_like_fahrenheit = kelvin_to_celsius_fahrenheit(feels_like_kelvin)
wind_speed = response['wind']['speed']
humidity = response['main']['humidity']
description = response['weather'][0]['description']
sunrise_time = dt.datetime.utcfromtimestamp(response['sys']['sunrise']+response['timezone'])
sunset_time = dt.datetime.utcfromtimestamp(response['sys']['sunset']+response['timezone'])
country = response['sys']['country']

#formart and print information 
print(f'Temperature in {location}: {temp_celsius:.2f}°C or {temp_fahrenheit}°F')
print(f'Feels like in {location}: {feels_like_celsius:.2f}°C or {feels_like_fahrenheit}°F')
print(f'Wind speed in {location}: {wind_speed}m/s')
print(f'Humidity in {location}: {humidity}%')
print(f'The weather in {location}: {description}')
print(f'Sunrise time in {location}: {sunrise_time}')
print(f'Sunset time in {location}: {sunset_time}')
print(f'Country: {country}')

Output

image-20230927112439996.png

Reference:
https://www.youtube.com/watch?v=9P5MY2i7K8