0
2

More than 1 year has passed since last update.

東京の天気情報を取得するAPIをPythonで書いてみた

Posted at

はじめに

Pythonで東京の天気を取得するAPIを作成してみました。
APIにはOpenWeatherという基本的に無料で使えるAPIを使用しました。

コード

必要なライブラリをインポートします

from flask import Flask, jsonify
import requests

Flaskアプリケーションを作成します

app = Flask(__name__)

APIエンドポイントを作成します。
ここでは、/weatherというパスをAPIエンドポイントとして定義しています。

@app.route('/weather')
def weather():
    # 天気を取得する処理をここに書く

次に、前項の「# 天気を取得する処理をここに書く」の箇所に天気を取得する処理を記述します。
ここでは、OpenWeatherMapのAPIを使用して、東京の天気を取得しています。

@app.route('/weather')
def weather():
    # OpenWeatherMapのAPIを使用して、東京の天気を取得する
    api_key = 'YOUR_API_KEY'
    city_id = '1863967'  # 東京のcity_id
    api_url = f'https://api.openweathermap.org/data/2.5/weather?id={city_id}&appid={api_key}'
    response = requests.get(api_url)
    data = response.json()

    # 取得した天気データを整形する
    weather_data = {
        'city': data['name'],
        'temperature': data['main']['temp'],
        'description': data['weather'][0]['description']
    }

    # 整形した天気データをJSON形式で返す
    return jsonify(weather_data)

Flaskアプリケーションを起動します。

if __name__ == '__main__':
    app.run()

コード

from flask import Flask, jsonify
import requests

@app.route('/weather')
def weather():
    # OpenWeatherMapのAPIを使用して、東京の天気を取得する
    api_key = 'YOUR_API_KEY'
    city_id = '1863967'  # 東京のcity_id
    api_url = f'https://api.openweathermap.org/data/2.5/weather?id={city_id}&appid={api_key}'
    response = requests.get(api_url)
    data = response.json()

    # 取得した天気データを整形する
    weather_data = {
        'city': data['name'],
        'temperature': data['main']['temp'],
        'description': data['weather'][0]['description']
    }

    # 整形した天気データをJSON形式で返す
    return jsonify(weather_data)

if __name__ == '__main__':
    app.run()
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