Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Traceback (most recent call last):
  File "c:\Users\athen\Desktop\personal assistant\main.py", line 195, in <module>
    weather = js["main"]
KeyError: 'main'


What I have tried:

import json
import requests

elif "weather" in query:
                    key = ""
                    weather_url = "https://api.openweathermap.org/data/2.5/weather?"
                    ind = query.split().index("in")
                    location = query.split()[ind +1:]
                    location = "".join(location)
                    url = weather_url + "appid=" + key + "&q=" + location
                    js = requests.get(url).json()
                    if js["cod"] != "404":
                        weather = js["main"]
                        temperature = weather["temp"]
                        temperature = temperature - 273.15
                        humidity = weather["humidity"]
                        desc = js["weather"][0]["description"]
                        weather_response = "the temperature in celcius is " + str(temperature) + "the humidity is" + str(humidity) + "and weather description is " + str(desc)
                        speak = speak + weather_response
                    else:
                        speak = speak + "city not found"
Posted
Updated 2-Nov-22 23:31pm

The documentation[^] suggests that the main property should exist. But you need to check that the code is 200, not just that it's anything other than 404 - you might be getting an error response.

Debug your code and inspect the js variable to see what is actually being returned. We can't do that for you, since we don't have access to your query or your API key, and nobody here is going to sign up to a commercial API just to test your code for you.
 
Share this answer
 
In addition to Richard's comment, the response will contain only those details that are relevant to the query, and the current situation.
Quote:
Weather fields in API response
If you do not see some of the parameters in your API response it means that these weather phenomena are just not happened for the time of measurement for the city or location chosen. Only really measured or calculated data is displayed in API response.


And since you can deserialize the JSON response into a Python dictionary, you can easily check to see which keys are present. You can start investigating by printing the response data to see what it returns.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900