How to use different APIs

410 Views Asked by At

I'm trying to create a program that can successfully tell you the weather via using a weather api. This is the api I will be using http://www.wunderground.com/weather/api/d/docs

I'm struggling to understand how to use this Api. I'm finding it to be rather confusing. I have tried to use the sample code presented by wunderground however it doesn't seem to be working in my editor(possibility due to code being another version of python.) I'm using python 3.5 Any comments and any suggestions would be greatly appreciated on how I can go about using this api.

Thanks

1

There are 1 best solutions below

12
On

Here is the sample code modified for Python 3:

from urllib.request import Request, urlopen
import json

API_KEY = 'your API key'
url = 'http://api.wunderground.com/api/{}/geolookup/conditions/q/IA/Cedar_Rapids.json'.format(API_KEY)

request = Request(url)
response = urlopen(request)
json_string = response.read().decode('utf8')
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))
response.close()

Obviously you need to sign up and get an API key. Use that key as the value for API_KEY. If you look at the code sample whilst logged in the key will already be inserted into the URL for you.

You could also use the requests module which is easier to work with, and supports Python 2 and 3:

import requests

API_KEY = 'your API key'
url = 'http://api.wunderground.com/api/{}/geolookup/conditions/q/IA/Cedar_Rapids.json'.format(API_KEY)

response = requests.get(url)
parsed_json = response.json()
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))