简体   繁体   中英

KeyError in Weather API Response

I was making a python program which tells about weather but facing the following error

Please tell how to correct it?

CODE

import requests
import json

api = "<MY_API_KEY>"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
print("for which city?")
CITY = input("city?: ")
URL = BASE_URL + "q=" + CITY + "&appid=" + api

response = requests.get(URL)
if __name__ == "__main__":
    data = response.json()
    main = data['main']
    temperature = main['temp']
    humidity = main['humidity']
    pressure = main['pressure']
    report = data['weather']
    print(f"{CITY:-^30}")
    print(f"Temperature: {temperature}")
    print(f"Humidity: {humidity}")
    print(f"Pressure: {pressure}")
    print(f"Weather Report: {report[0]['description']}")

TERMINAL

PS C:\Users\mamta\Documents\PythonPanti\JARVISprj>  c:; cd 'c:\Users\mamta\Documents\PythonPanti\JARVISprj'; & 'C:\Users\mamta\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\mamta\.vscode\extensions\ms-python.python-2021.5.842923320\pythonFiles\lib\python\debugpy\launcher' 
'53873' '--' 'c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py'
for which city?
city?: Delhi
Traceback (most recent call last):
  File "c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py", line 13, in <module>
    main = data['main']
KeyError: 'main'

Your code is perfectly fine only problem here I see is when you enter any garbage value. You need to do error handling. 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM