Home > Software engineering >  while using openweather.org api using for temperature and weather it shows an keyerror
while using openweather.org api using for temperature and weather it shows an keyerror

Time:10-05

In my voice assistant project, I want to set a forecast. Hence I am using api key from openweather.org and my code is as below

import requests
from os import *

api_address = "https://api.openweathermap.org/data/2.5/weather?id=bfbe606c8d661478b8132b49eee8051a"
json_data = requests.get(api_address).json()
# json_data = json_data.json()

def temp():
    temperature = round(json_data['main']['temp']-273.1)
    return temperature

def des():
    description = json_data["weather"][0]["description"]
    return description

print(temp())
print(des()) 

But here problem is console shows an error about 'keyerror':

line 9, in temp
    temperature = round(json_data['main']['temp']-273.1)

KeyError: 'main'

please suggest me any solution which can took out me from this problem.

CodePudding user response:

creator of Open-Meteo here. You could use the Open-Meteo API which does not require an API key:

import requests
from os import *

api_address = "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true"
json_data = requests.get(api_address).json()

def temp():
    temperature = json_data['current_weather']['temperature']
    return temperature

def des():
    description = json_data["current_weather"]["weathercode"]
    return description

print(temp())
print(des()) 

Output:

12.4
2

Please note to put in your correct latitude and longitude to get the forecast for your location

  • Related