1

I want to pull only a few parts of an API Response and print them.

When I run this:

def get_weather(lat,lon):

    import requests

    r = requests.post('https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=hourly,daily&appid=92d93ccc6ac5587d35d3ccc4479083a1'.format(lat,lon))

    print(r.text)

get_weather(33,44)

the API Response Shows as :

{"lat":33,"lon":44,"timezone":"Asia/Baghdad","timezone_offset":10800,"current":{"dt":1604279014,"sunrise":1604287381,"sunset":1604326320,"temp":295.15,"feels_like":290.63,"pressure":1015,"humidity":35,"dew_point":279,"uvi":4.16,"clouds":0,"visibility":10000,"wind_speed":5.1,"wind_deg":140,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}]}}
Running: python (cwd=C:\Users\Daddy\Desktop\Cisco Problems\weatherForecast.py pid=6528). Exited with code=0 in 0.64 seconds.

Since I only want dt, temp, weather, humidity and wind_speed, I added print statements onto my code:

def get_weather(lat,lon):

    import requests

    r = requests.post('https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=hourly,daily&appid=92d93ccc6ac5587d35d3ccc4479083a1'.format(lat,lon))

    print(r["dt"])
    print(r["temp"])
    print(r["weather"])
    print(r["humidity"])
    print(r["wind_speed"])

get_weather(33,44)

And I am now getting this error:

TypeError: 'Response' object is not subscriptable
Ooka
  • 49
  • 5

1 Answers1

0

Use this to get the data and access it like a dictionary:

data = r.json()
dt = data["dt"]
temp = data["temp"]
YaTrippin
  • 46
  • 4
  • This didn't quite work out, I am getting "Key Error : dt" – Ooka Nov 02 '20 at 01:42
  • This is closed however, I think the reason you are getting key error is because of the way the response is structured. you should be using `dt = data["current"]["data"]` – YaTrippin Nov 02 '20 at 19:45