このサイトでは「APIとは何か」をやさしく解説し、プログラミング初心者でも理解できるように、OpenWeather APIを使った天気情報取得の流れと実例を紹介します。実際のJavaScriptコードを使って、東京の気温や湿度をリアルタイムで表示。JavaScript入門にも最適なシンプル構成で、API連携の基本を実践的に学べる内容です。
API(Application Programming Interface)とは、ソフトウェア同士が機能やデータをやり取りするための仕組みのことです。
プログラムのAPIは、他のプログラムやサービスと連携するための「入り口」のようなもので、開発者はそのAPIを使って、外部のサービスを自分のアプリに組み込むことができます。
APIは、ソフトウェア同士の会話を可能にする「共通言語」のようなもので、現代のプログラミングにおいて非常に重要な役割を果たしています。
APIを利用する際の一般的なプログラムの流れは、以下のようになります。
JSON形式が一般的)を受け取ります。
https://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=あなたのAPIキー にリクエストを送信APIを使えば、他のサービスと簡単に連携できるため、効率的に機能を拡張できます。特にWebアプリやモバイルアプリでは、APIは欠かせない要素です。
以下は、OpenWeatherのAPIを使って「東京の天気情報(気温・湿度)」を取得し、HTMLに表示するサンプルコードです。JavaScript(Fetch API)を使ってAPIにアクセスしています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>天気情報を取得する</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.weather {
background: #f0f8ff;
padding: 15px;
border-radius: 10px;
width: 300px;
}
</style>
</head>
<body>
<h2>東京の現在の天気</h2>
<div class="weather">
<p><strong>気温:</strong><span id="temperature">読み込み中...</span> ℃</p>
<p><strong>湿度:</strong><span id="humidity">読み込み中...</span> %</p>
</div>
<script>
const apiKey = "あなたのAPIキー"; // ←ここを自分のAPIキーに変更!
const city = "Tokyo";
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=ja`;
fetch(url)
.then(response => response.json())
.then(data => {
const temp = data.main.temp;
const humidity = data.main.humidity;
document.getElementById("temperature").textContent = temp;
document.getElementById("humidity").textContent = humidity;
})
.catch(error => {
console.error("天気情報の取得に失敗しました:", error);
document.getElementById("temperature").textContent = "取得失敗";
document.getElementById("humidity").textContent = "取得失敗";
});
</script>
</body>
</html>
こちらは、Pythonを使って同じ天気情報を取得するプログラムです。Flaskを使用して、ウェブサーバーを立て、HTMLテンプレートと連携します。APIキーを自分のものに変更して実行してください。
from flask import Flask, render_template
import requests
app = Flask(__name__)
@app.route('/')
def weather():
api_key = "あなたのAPIキー" # ←ここを自分のAPIキーに変更!
city = "Tokyo"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric&lang=ja"
try:
response = requests.get(url)
data = response.json()
temperature = data['main']['temp']
humidity = data['main']['humidity']
except Exception as e:
print(f"Error: {e}")
temperature = "取得失敗"
humidity = "取得失敗"
return render_template('weather.html', temperature=temperature, humidity=humidity)
if __name__ == '__main__':
app.run(debug=True)
weather.html ファイルを同じディレクトリの templates フォルダに保存します。内容は次の通りです:
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>天気情報を取得する</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.weather {
background: #f0f8ff;
padding: 15px;
border-radius: 10px;
width: 300px;
}
</style>
</head>
<body>
<h2>東京の現在の天気</h2>
<div class="weather">
<p><strong>気温:</strong>{{ temperature }} ℃</p>
<p><strong>湿度:</strong>{{ humidity }} %</p>
</div>
</body>
</html>
このコードを実行するには、以下の手順で必要なパッケージをインストールしてください:
pip install flask requests
APIキーの使い方に関する注意点を説明します。セキュリティや管理の観点から、APIキーは適切に保護する必要があります。APIキーをコードに直接埋め込むのは避け、環境変数や設定ファイルを使用する方法が推奨されます。
APIキーをコード内に直接記載するのではなく、外部の設定ファイルに保存する方法です。
# config.py
API_KEY = "あなたのAPIキー" # ここにAPIキーを記述
そして、アプリケーションのコードから設定ファイルをインポートして使用します。
# app.py
from flask import Flask, render_template
import requests
import config # config.pyをインポート
app = Flask(__name__)
@app.route('/')
def weather():
api_key = config.API_KEY # 設定ファイルからAPIキーを取得
city = "Tokyo"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric&lang=ja"
try:
response = requests.get(url)
data = response.json()
temperature = data['main']['temp']
humidity = data['main']['humidity']
except Exception as e:
print(f"Error: {e}")
temperature = "取得失敗"
humidity = "取得失敗"
return render_template('weather.html', temperature=temperature, humidity=humidity)
if __name__ == '__main__':
app.run(debug=True)
環境変数にAPIキーを設定して、コードからそれを読み取る方法です。
export API_KEY="あなたのAPIキー"
Pythonコードで以下のように取得します。
# app.py
from flask import Flask, render_template
import requests
import os
app = Flask(__name__)
@app.route('/')
def weather():
api_key = os.getenv('API_KEY') # 環境変数からAPIキーを取得
city = "Tokyo"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric&lang=ja"
try:
response = requests.get(url)
data = response.json()
temperature = data['main']['temp']
humidity = data['main']['humidity']
except Exception as e:
print(f"Error: {e}")
temperature = "取得失敗"
humidity = "取得失敗"
return render_template('weather.html', temperature=temperature, humidity=humidity)
if __name__ == '__main__':
app.run(debug=True)
.envファイルを使って環境変数を管理する方法です。
# .env
API_KEY=あなたのAPIキー
Pythonコード内で以下のように読み込みます。
# app.py
from flask import Flask, render_template
import requests
from dotenv import load_dotenv
import os
load_dotenv() # .env ファイルの内容を読み込む
app = Flask(__name__)
@app.route('/')
def weather():
api_key = os.getenv('API_KEY') # .env ファイルからAPIキーを取得
city = "Tokyo"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric&lang=ja"
try:
response = requests.get(url)
data = response.json()
temperature = data['main']['temp']
humidity = data['main']['humidity']
except Exception as e:
print(f"Error: {e}")
temperature = "取得失敗"
humidity = "取得失敗"
return render_template('weather.html', temperature=temperature, humidity=humidity)
if __name__ == '__main__':
app.run(debug=True)
APIプロバイダーによっては、APIキーに対してIPアドレス制限やドメイン制限を設定できることがあります。これを利用して、悪用されるリスクを減らしましょう。
このサイトは、一部のコンテンツに生成AIを使用しています。
情報が古かったり、間違っていることなどによる損害の責任は負いかねますので、ご了承ください。
Copyright (C) SUZ45. All Rights Reserved.