LoginSignup
7
9

More than 3 years have passed since last update.

Pythonで天気予報API叩いてみた

Last updated at Posted at 2021-04-26

はじめに

住んでいる地域について天気予報を得るために、無料でAPIを提供している
OpenWeatherMapを使ってみる

概要

OpenWeatherMapはGUIで天気予報を取得することができるのですが、今回はAPIを使って天気や気温を取ってきます。
スクリーンショット (25).png

初期設定

いくつかプランがあるので、無料のプランに登録し、APIkeyを手に入れます。無料枠だと5日後までの天気予報を取得出来て、1分間に60回までのAPIコール制限があるみたいです。

天気予報を取得する

そもそもAPIを試したいならcurlを使えば簡単に試すことはできるのですが、今後システムに組み込んでいく予定なのでPythonで実装します。

エンドポイントはapi.openweathermap.org/data/2.5/weather
パラメータは下記の通り

パラメーター 説明
q 都市名
appid APIkey
mode 応答方式
units 測定単位
lang 出力言語

都市名を指定してAPIリクエストを送る

apicall.py
import json
import requests

#パラメーター
params={"q":"Kobe","appid":apikey}

url="http://api.openweathermap.org/data/2.5/forecast"
res=requests.get(url,params=params)

k=res.json()
jsonText = json.dumps(k["list"][0], indent=4)
print(jsonText)

Kobe(神戸)で試してみた結果

{
    "dt": 1619406000,
    "main": {
        "temp": 289.15,
        "feels_like": 287.75,
        "temp_min": 288.84,
        "temp_max": 289.15,
        "pressure": 1020,
        "sea_level": 1020,
        "grnd_level": 1016,
        "humidity": 36,
        "temp_kf": 0.31
    },
    "weather": [
        {
            "id": 801,
            "main": "Clouds",
            "description": "few clouds",
            "icon": "02d"
        }
    ],
    "clouds": {
        "all": 20
    },
    "wind": {
        "speed": 8.04,
        "deg": 3,
        "gust": 9.57
    },
    "visibility": 10000,
    "pop": 0,
    "sys": {
        "pod": "d"
    },
    "dt_txt": "2021-04-26 03:00:00"
}

天気予報は取得できたのですが14時に取得したデータが"dt_txt": "2021-04-26 03:00:00"なのでリアルタイムの情報ではなく日単位での取得になるっぽいです。まあ無料枠なので当然と言えば当然。一番近い時間帯の情報を取得することで解決。

天気予報を表示

情報自体は取得できたので気温、湿度、天気、風速、取得日時を抜き出して天気予報っぽく表示します。

#省略
jsonText=res.json()

print("都市:Kobe",end="\n\n")
for i in range(0,5):

    print("気温:",jsonText["list"][i]["main"]["temp"])#気温
    print("湿度:",jsonText["list"][i]["main"]["humidity"])#湿度
    print("天気:",jsonText["list"][i]["weather"][0]["main"])#天気
    print("風速:",jsonText["list"][i]["wind"]["speed"])#風速
    print("取得日時:",jsonText["list"][i]["dt_txt"],end="\n\n")#取得日時

結果

気温: 289.14
湿度: 27
天気: Clear
風速: 7.34
取得日時: 2021-04-26 06:00:00

気温: 286.29
湿度: 39
天気: Clouds
風速: 6.69
取得日時: 2021-04-26 09:00:00

気温: 283.53
湿度: 50
天気: Clouds
風速: 4.59
取得日時: 2021-04-26 12:00:00

気温: 282.36
湿度: 58
天気: Clouds
風速: 3.12
取得日時: 2021-04-26 15:00:00

気温: 281.99
湿度: 60
天気: Clouds
風速: 2.57
取得日時: 2021-04-26 18:00:00

温度表示がケルビンなのと最低間隔が3時間という制限はありますが、工夫次第では十分に使えそうです。表示設定を日本語にしたり、ほかにも取得できる情報はたくさんあるので、詳しい内容はドキュメントを参照してください。

さいごに

OpenWeatherMapを使うことで、比較的簡単に情報を取ってくることができました。今後はこれで夕立を通知してくれるBOTを開発したいです。

7
9
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
7
9