Using Python with the 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


Weather API

Login to or register a new account .

Get your API Key

In those images, the key is your API key from


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 = ''
url = base_url + 'appid=' + api_key + '&q=' + location

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}')