0
0

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初心者向け: APIを叩いて情報を受信する基本(GET編)

0
Posted at

Python初心者向け: APIを叩いて情報を受信する基本(GET編)

はじめに

「APIを叩く」と聞くと難しそうですが、まずは 受信(GET) だけに絞ると理解しやすいです。
この記事では、Pythonの requests を使って以下を順番に学びます。

  • APIにGETリクエストを送る
  • JSONレスポンスを読む
  • 必要な項目だけ取り出す
  • エラー時に落ちないようにする
  • クエリパラメータ(params)を使う
  • 1件のデータが持つ項目を全部確認する

動作環境

  • Python 3.x
  • requests ライブラリ

インストール(必要なら):

pip install requests

1. まずは1件取得してみる

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url, timeout=10)

print("status:", response.status_code)
print("content-type:", response.headers.get("content-type"))
print("body:", response.text)

確認ポイント

  • status: 200 なら成功
  • content-type が application/json ならJSONが返っている
  • body にJSON文字列が見える

2. JSONとして扱って必要な値を取り出す

response.text は文字列なので、通常は response.json() で辞書に変換して扱います。

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url, timeout=10)
response.raise_for_status()

data = response.json()
print("id:", data["id"])
print("title:", data["title"])

3. エラーハンドリング(超重要)

API通信では失敗も普通に起きます。
try/except で安全に処理できるようにしておくのが実務では必須です。

import requests

def fetch_post(post_id: int) -> None:
    url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"

    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        data = response.json()
        print("id:", data["id"])
        print("title:", data["title"])

    except requests.exceptions.HTTPError as e:
        status = e.response.status_code if e.response is not None else "unknown"
        body = e.response.text if e.response is not None else "no response body"
        print("HTTP Error:", e)
        print("status code:", status)
        print("error message:", body)

    except requests.exceptions.Timeout:
        print("タイムアウトしました")

    except requests.exceptions.RequestException as e:
        print("通信エラーが発生しました:", e)

fetch_post(1)       # 成功
fetch_post(999999)  # 404の確認用

4. クエリパラメータを使って一覧取得する

URLを文字列連結せず、params= を使うのが基本です。

import requests

def fetch_posts_by_user(user_id: int, limit: int = 3) -> None:
    url = "https://jsonplaceholder.typicode.com/posts"
    params = {
        "userId": user_id,
        "_limit": limit
    }

    response = requests.get(url, params=params, timeout=10)
    response.raise_for_status()
    posts = response.json()

    print(f"user_id={user_id} / 取得件数={len(posts)}")
    for post in posts:
        print(f"id={post['id']}, title={post['title']}")

fetch_posts_by_user(1, limit=5)

5. 「このidが持つ項目を全部見たい」とき

レスポンス辞書をループすれば、キーと値を全部確認できます。

import requests

post_id = 1
url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"

response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()

print(f"post_id={post_id} の全項目:")
for key, value in data.items():
    print(f"{key}: {value}")

キー名だけ見たいなら:

print(list(data.keys()))

6. パラメータはどう調べる?

基本は次の順です。

  1. 公式APIドキュメントを見る
  2. OpenAPI/Swaggerがあれば読む
  3. 実際に params を変えて結果の差分を確認する
  4. レスポンスヘッダー(Link, X-Total-Count など)も見る

まとめ

初心者がまず押さえるべきはこの3つです。

  • requests.get(..., timeout=10) で取得する
  • response.json() でデータを扱う
  • try/except + raise_for_status() で失敗に備える

受信(GET)をしっかり固めると、その後のPOST/PUT/DELETEも理解しやすくなります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?