2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ShoheiAdvent Calendar 2022

Day 16

APIを使って天気情報を取得する

Posted at

今回使うAPIはこれ

OpenWeatherです。
現在の天気や、天気予報、過去の天気、降水マップなど様々な情報を取得できます。

無料枠でも、1000件/日まで利用できることもあり、お試し利用するにはちょうど良いです。
日本の情報だけで良い場合は、国産サービスを選択するのもいいと思います。

利用方法

アカウント登録〜APIキー取得

https://openweathermap.org/api
image.png

この辺りから、アカウント登録を行い、APIキーを取得しましょう。

現在の天気を取得してみる

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

今回は、ハワイの気温をunitsmetricを設定して、馴染みのある温度表記で取得しています。

% curl "https://api.openweathermap.org/data/2.5/weather?lat=21.2762123&lon=-157.8317062&units=metric&appid=xxxxxxxxxxxx"
{"coord":{"lon":-157.8317,"lat":21.2762},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main":{"temp":21.72,"feels_like":22.25,"temp_min":20.69,"temp_max":22.19,"pressure":1015,"humidity":88},"visibility":10000,"wind":{"speed":2.57,"deg":10},"clouds":{"all":20},"dt":1669723467,"sys":{"type":1,"id":7878,"country":"US","sunrise":1669740686,"sunset":1669780106},"timezone":-36000,"id":5850943,"name":"Maunalani Heights","cod":200}

データを展開すると。

{
  "coord": {
    "lon": -157.8317,
    "lat": 21.2762
  },
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 21.72,
    "feels_like": 22.25,
    "temp_min": 20.69,
    "temp_max": 22.19,
    "pressure": 1015,
    "humidity": 88
  },
  "visibility": 10000,
  "wind": {
    "speed": 2.57,
    "deg": 10
  },
  "clouds": {
    "all": 20
  },
  "dt": 1669723467,
  "sys": {
    "type": 1,
    "id": 7878,
    "country": "US",
    "sunrise": 1669740686,
    "sunset": 1669780106
  },
  "timezone": -36000,
  "id": 5850943,
  "name": "Maunalani Heights",
  "cod": 200
}

めちゃくちゃ簡単です。

lat/lonは、Google Mapから取得しても良いですし、この辺りの、ジオコーディングAPIを利用して住所から緯度経度に変換してもよさそうです。

最後に

APIは楽しい!

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?