API request Weather Underground

1.3k Views Asked by At

Hello I am trying to get a API request with python 3 for weather underground to just do a simple print of the weather conditions, can someone give me a tip what I am doing wrong? I have a lot to learn here, so the learning curve is steep! Sorry if the question is super basic, what is the better code to use between the two? At least with one that I could get working and then build off of... Thank you. Both of these codes below are example scripts that I got from WU website & Github. The first code gives me an error "for observation in data (['history']['observations']): TypeError: list indices must be integers or slices, not str"

from urllib.request import urlopen
import json

api_key = ""
date = "20170901"
zip_code = "53711"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json" 
% (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data (['history']['observations']):
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

This is a second attempt at my first API request, but it give me an error "TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'"

from urllib.request import urlopen
import json

f = urlopen('http://api.wunderground.com/api//geolookup/conditions/q/IA/Cedar_Rapids.json')

json_string = f.read()

parsed_json = json.loads(json_string)

location = parsed_json['location']['city']

temp_f = parsed_json['current_observation']['temp_f']

print ("Current temperature in %s is: %s") % (location, temp_f)
f.close()

Any tip that a pro can give a newb on self teaching topics like this is greatly appreciated... I can see from WU that my API key is working... But the code is wrong :(

1

There are 1 best solutions below

1
On

The reason for the error you were encountering in your second example is because that appears to be invalid syntax. I think what you are looking for is something similar to the following.

print("this is a %s" % ("my string",))

That being said, I put together a package a little while ago to help with getting started with Weather Underground if you want to take a look for some pointers. Or just pip install WunderWeather. Here's the doc.