pythonでopenweathermapのAPIを叩こう

まず、jsonのapi request
http://api.openweathermap.org/data/2.5/weather?q=Tokyo,JP&APPID={apikey}

レスポンス

{"coord":{"lon":139.76,"lat":35.68},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50n"}],"base":"stations","main":{"temp":301.81,"pressure":1009,"humidity":66,"temp_min":301.15,"temp_max":302.15},"visibility":16093,"wind":{"speed":1.5,"deg":120},"clouds":{"all":1},"dt":1533250560,"sys":{"type":1,"id":7622,"message":0.0074,"country":"JP","sunrise":1533153003,"sunset":1533203030},"id":1850147,"name":"Tokyo","cod":200}

pythonで書きます。

import requests
import json

apikey = "hoge"

cities = ["Tokyo,JP", "London,UK", "New York, US"]
api = "http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={key}"

k2c = lambda k: k - 273.15

for name in cities:
	url = api.format(city=name, key=apikey)
	r = requests.get(url)
	data = json.loads(r.text)
	print("+ 都市=", data["name"])
	print("| 天気=", data["weather"][0]["description"])
	print("| 最低気温=", k2c(data["main"]["temp_min"]))
	print("| 最高気温=", k2c(data["main"]["temp_max"]))
	print("| 湿度=", data["main"]["humidity"])
	print("| 気圧=", data["main"]["pressure"])
	print("| 風向き=", data["wind"]["deg"])
	print("| 風速度=", data["wind"]["speed"])
	print("")

コマンドライン
[vagrant@localhost python]$ python3 app.py
+ 都市= Tokyo
| 天気= mist
| 最低気温= 28.0
| 最高気温= 29.0
| 湿度= 66
| 気圧= 1009
| 風向き= 120
| 風速度= 1.5

+ 都市= London
| 天気= clear sky
| 最低気温= 20.0
| 最高気温= 24.0
| 湿度= 64
| 気圧= 1023
| 風向き= 230
| 風速度= 2.6

+ 都市= New York
| 天気= light rain
| 最低気温= 27.0
| 最高気温= 29.0
| 湿度= 69
| 気圧= 1019
Traceback (most recent call last):
File “app.py”, line 21, in
print(“| 風向き=”, data[“wind”][“deg”])
KeyError: ‘deg’

New Yorkの風向きがエラーになりますね。
new yorkのjsonを叩きます。
http://api.openweathermap.org/data/2.5/weather?q=New%20York,US&APPID={key}

{“coord”:{“lon”:-73.99,”lat”:40.73},”weather”:[{“id”:500,”main”:”Rain”,”description”:”light rain”,”icon”:”10d”}],”base”:”stations”,”main”:{“temp”:300.55,”pressure”:1019,”humidity”:69,”temp_min”:300.15,”temp_max”:302.15},”visibility”:16093,”wind”:{“speed”:2.6},”clouds”:{“all”:75},”dt”:1533250560,”sys”:{“type”:1,”id”:2121,”message”:0.0072,”country”:”US”,”sunrise”:1533203668,”sunset”:1533254951},”id”:5128581,”name”:”New York”,”cod”:200}

NewYorkのwindはspeedだけのようです。何故だ?wall streetは風向きなんて関係ないのかな。