APIとは何か?プログラマー必須の概念を理解しよう

API(Application Programming Interface)とは、異なるソフトウェア同士がデータやサービスを交換するための「窓口」です。

REST APIは、その中でも最も広く使われる設計規則に従ったAPIです。ChatGPT API・GitHub API・Slack API・天気API……現代のWebサービスのほぼすべてがREST APIを提供しています。


REST APIの基本概念

概念 説明
エンドポイント APIにアクセスするURL
HTTPメソッド GET(取得)・POST(送信)・PUT(更新)・DELETE(削除)
リクエスト クライアントからAPIへの要求
レスポンス APIからクライアントへの返答(主にJSON形式)
認証 APIキー・OAuth等でアクセスを制御

PythonでREST APIを叩く基本

requestsライブラリのインストール

pip install requests

GETリクエスト(データを取得する)

import requests

# 例:天気情報APIを叩く
url = "https://api.example.com/weather"
params = {"city": "Tokyo", "units": "metric"}
headers = {"Authorization": "Bearer YOUR_API_KEY"}

response = requests.get(url, params=params, headers=headers)

# ステータスコードの確認
print(f"ステータス: {response.status_code}")

# JSONデータを取得
data = response.json()
print(data)

POSTリクエスト(データを送信する)

import requests, json

url = "https://api.example.com/posts"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
payload = {
    "title": "テスト投稿",
    "body": "これはAPIから作成した投稿です",
    "userId": 1
}

response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.json())

よく使うHTTPステータスコード

コード 意味
200 OK(成功)
201 Created(作成成功)
400 Bad Request(リクエストエラー)
401 Unauthorized(認証失敗)
404 Not Found(リソースなし)
429 Too Many Requests(レート制限)
500 Internal Server Error(サーバーエラー)

エラーハンドリングの基本

import requests

try:
    response = requests.get("https://api.example.com/data", timeout=10)
    response.raise_for_status()  # 4xx/5xxの場合に例外を発生
    data = response.json()
except requests.exceptions.Timeout:
    print("タイムアウトしました")
except requests.exceptions.HTTPError as e:
    print(f"HTTPエラー: {e}")
except requests.exceptions.RequestException as e:
    print(f"通信エラー: {e}")

まとめ

REST APIの仕組みを理解し、Pythonのrequestsライブラリで扱えるようになると、外部サービスとの連携が格段に広がります。まずは無料のパブリックAPI(GitHub API・OpenWeather API等)で練習し、実際に動くスクリプトを作ってみましょう。