LoginSignup
0
2

More than 5 years have passed since last update.

Pythonでopenweatherapiを使って東京の天気を取得する

Posted at

前の記事と同じようなことを、Pythonでやってみた。

前の記事: Goでopenweatherapiを使って東京の天気を取得する

技術要件

  • Python 3.7
  • requests 2.20.1

実装

import requests

OPEN_WEATHER_API_KEY = 'YOUR_OPENWEATHERAPIKEY_HERE'

response = requests.get(
    'https://api.openweathermap.org/data/2.5/weather',
    params={'q': 'Tokyo', 'APPID': OPEN_WEATHER_API_KEY})

body = response.json()
if response.status_code != 200:
    print('Status code was {}. Reason: {}.'.format(body['cod'], body['message']))
    exit(1)

print('Current weather in Tokyo is {}.'.format(body['weather'][0]['main']))

特に変わったことはしていない。
個人的にPythonでWebAPIを使用する場合はrequestsを使うことが多いので、ここでもこれを利用している。
エラーハンドリングが必要な箇所が少なく、また結果を構造体に入れることもしていないので、コード自体は短くなっている。

逆に言えば、実装側が各メソッド呼び出しに対してそれがエラーを送出することを考慮しなければ行けない箇所が出てくる。
そういった点では、Goのほうがエラーハンドリングを実装側に明示させるので、良心的かも知れない。

> python3 get_weather.py
Current weather in Tokyo is Clouds.
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2