Hakology – How to grab openweathermap data using python.

I’ve been playing with the openweathermap api thought i’d share a little code, the following pulls the json and constructs a string containing the location, temp, tax temp, min temp and humidity. You will need to sign up for an API key and free user account 1st. The free account at the time of writing this allows 50k calls a day so if you’re writing for a small personal project 50k calls should be fine.

Copy the code below to a file
eg. displayweather.py

chmod the file if needed …
sudo chmod +x displayweather.py

run the file using …
python displayweather.py

import requests
r = requests.get('http://api.openweathermap.org/data/2.5/forecast/city?id=YOURCITYIDGOESHERE&APPID=YOURAPIKEYGOESHERE')
data = r.json()
mystring = ""
mystring = mystring + data['city']['name'] + " "
mystring = mystring + "Temp:" + str(int(data['list'][0]['main']['temp'] - 273.15)) + "C "
mystring = mystring + "Max:" + str(int(data['list'][0]['main']['temp_max'] - 273.15)) + "C "
mystring = mystring + "Min:" + str(int(data['list'][0]['main']['temp_min'] - 273.15)) + "C "
mystring = mystring + "Hum:" + str(data['list'][0]['main']['humidity']) + "% "
print mystring

Click here to download the file.