OpenWeather から気象情報を取得する

OpenWeather
https://openweathermap.org/

はじめに

  • OpenWeather の API を調査し、気象データの取得をテストする
  • 2019/9/24(JST)の情報であることに注意

OpenWeather とは

  • 2014年に設立されたビッグデータ、データ処理、衛星画像処理の企業
  • 本社はイギリスにある。アメリカにはオフィスが、ラトビアには開発チームがある

どんな気象 API があるか

https://openweathermap.org/api

おおざっぱに、いくつか API をあげる。これらは無料でも使用可能。

基本的に API のレスポンスは JSON フォーマットで取得できる。さらに一部の API については XML フォーマットのレスポンスも対応している雰囲気。

価格

https://openweathermap.org/price

現在と今後の予測の API は無料でも使用できるが、有料プランもある。ここではプランごとの API 呼び出し回数上限(分ごと)を取り上げる。

プラン 料金(月ごと) API 呼び出し回数上限(1分間)
Free 無料 60 回
Startup 40 US$ 600 回
Developer 180 US$ 3,000 回
Professional 470 US$ 30,000 回
Enterprise 2,000 US$ 200,000 回

API キーを準備する

https://home.openweathermap.org/users/sign_up

  • 上のページからユーザ登録する
    • 「I am 16 years old and over」のチェックボックスがあるので、16歳以上しか登録できないようだ。

f:id:daisuke-t-jp:20190924041802p:plain:w400

  • ログインした状態で HOME (https://home.openweathermap.org/) にアクセスし、「API Keys」タブをクリックすると、 API キーが表示される
  • もしくはユーザ登録時に届くメールにも API キーは書かれている

API をテストする

前提

API リクエスト例

https://api.openweathermap.org/data/2.5/weather?appid=<APIキー>&q=Shinjuku,jp

API レスポンス例

{
   "coord":{
      "lon":139.71,
      "lat":35.7
   },
   "weather":[
      {
         "id":801,
         "main":"Clouds",
         "description":"few clouds",
         "icon":"02n"
      }
   ],
   "base":"stations",
   "main":{
      "temp":297.58,
      "pressure":1008,
      "humidity":65,
      "temp_min":294.82,
      "temp_max":299.82
   },
   "visibility":10000,
   "wind":{
      "speed":4.1,
      "deg":270
   },
   "clouds":{
      "all":20
   },
   "dt":1569268257,
   "sys":{
      "type":1,
      "id":8074,
      "message":0.0101,
      "country":"JP",
      "sunrise":1569270598,
      "sunset":1569314220
   },
   "timezone":32400,
   "id":1850144,
   "name":"Shinjuku",
   "cod":200
}

API 呼び出し回数上限

#!/bin/sh

for i in {0..100}
do
    curl "https://api.openweathermap.org/data/2.5/weather?appid=<API キー>&q=Shinjuku,jp"
done

1分間の API 呼び出し回数制限(60回)を超えた時の動作を試したく、上のシェルを複数に並列で動作させたが、上限を超えた旨を示すレスポンスは確認できなかった。すべて正常にデータを得られた。これについては不明。(2019/9/28 時点)

そのた

  • 気温の単位がデフォルトでケルビンになる。摂氏で取得したい場合は units=metricAPI を呼び出すこと(参照:https://openweathermap.org/current#data
    • https://api.openweathermap.org/data/2.5/weather?appid=<APIキー>&q=Shinjuku,jp&units=metric
  • 都市名ではなく、緯度経度指定したい場合は lat, lon パラメーターを使用する
    • https://api.openweathermap.org/data/2.5/weather?appid=<APIキー>&lat=35.690128&lon=139.701701