Fetch Current Temperature with OpenWeatherMap API

  • Share this:

Code introduction


This function fetches the weather information for a given city name using the OpenWeatherMap API and returns the current temperature.


Technology Stack : requests, OpenWeatherMap API

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
import requests

def get_random_weather(city_name):
    # This function fetches the weather information for a given city name using the OpenWeatherMap API
    api_key = "your_api_key_here"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}&units=metric"
    response = requests.get(url)
    data = response.json()
    return f"The current temperature in {city_name} is {data['main']['temp']}°C"