1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで東京の天気を取得してみる

1
Last updated at Posted at 2025-11-06

はじめに

最近、APIを使ってデータを扱う練習をしているのですが、今回は天気情報を取得できる OpenWeatherMap API を使って、シンプルなスクリプトを書いてみました。

「APIって実際どうやって使うの?」という方にも、ちょっとした練習になる内容です。

やりたいこと

特定の都市(今回は東京)の天気情報を取得して、
気温・天気・湿度などを表示する簡単なスクリプトを作ります。

実際のコード

code.py
import requests
import json
# APIから返ってくるデータはほとんどJSONなので、この2つは定番セット

API_KEY = "***" #API
CITY = "TOKYO"
URL = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units=metric&lang=ja"

def get_weather(city):
    try:
        response = requests.get(URL)
        if response.status_code == 200:
            data = response.json()  # JSONをPythonのdictに変換
            # 必要な情報を取り出す
            city_name = data["name"]
            temp = data["main"]["temp"]
            weather = data["weather"][0]["description"]
            humidity = data["main"]["humidity"]

            print(f"都市名: {city_name}")
            print(f"気温: {temp}")
            print(f"天気: {weather}")
            print(f"湿度: {humidity}")

        else:
            print("エラー:", response.status_code)
    except Exception as e:
        print("例外が発生しました:", e)

get_weather(CITY)

ポイント

✅requests を使ってAPIにアクセス
✅返ってきたデータ(JSON形式)を response.json() でPythonの辞書型に変換
✅必要な情報(気温・湿度など)だけを取り出して表示
✅今回はエラーハンドリングも少し入れてみました。
(通信エラーなどが起きたときにも原因がわかるようにしています。)

まとめ

とてもシンプルなスクリプトですが、
「APIからデータを取得して使う流れ」を体験するのにちょうど良い練習になりました。

今後はこのデータを定期的に取得してファイルに保存する処理や、
グラフ表示などにも挑戦してみたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?