{}const=>[]async()letfn</>var
開発Python

Python での API の操作: requests ライブラリの完全ガイド

リクエストライブラリを使用してPythonでAPIを操作する方法を学びます。 この記事では、GET および POST リクエストの実例、エラー処理、ヘッダーと認証の操作、ファイルのダウンロードについて説明します。開発者向けの基本から高度なテクニックまでの完全ガイド。

К

Kodik

著者

2分で読める

なぜリクエストなのか?

Pythonには、HTTPを操作するための組み込みの urllibモジュールが含まれていますが、その構文は煩雑で直感的ではありません。リクエストライブラリは、エレガントで直感的なインターフェースを提供することでこの問題を解決します。そのスローガンが「人間のためのHTTP」であるのも不思議ではありません。

🔥 10万人以上の学生が参加中

理論を読むのに疲れた?
コーディングの時間だ!

Kodik — 実践でプログラミングを学ぶアプリ。AIメンター、インタラクティブなレッスン、実際のプロジェクト。

🤖 AI 24時間
🎓 修了証
💰 無料
🚀 始める
今日参加

インストール

リクエストの設定は非常に簡単です。

pip install requests

操作の基本:GETリクエスト

最も一般的なタイプのリクエスト、GETから始めましょう。GitHubユーザーに関するデータを取得する必要があるとします。

import requests

response = requests.get('https://api.github.com/users/octocat')

# 回答のステータスを確認しています
print(response.status_code)  # 200

# JSONを取得する
data = response.json()
print(data['name'])  # The Octocat
print(data['public_repos'])  # 公開リポジトリの数

response オブジェクトには、ステータスコード、ヘッダー、応答本文など、サーバー応答に関するすべての情報が含まれています。

クエリのパラメータ

多くの場合、APIではURLにパラメータを渡す必要があります。リクエストライブラリを使用すると、これをエレガントに行うことができます。

# GitHub でリポジトリを検索する
params = {
    'q': 'python requests',
    'sort': 'stars',
    'order': 'desc'
}

response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()

for repo in repos['items'][:5]:
    print(f"{repo['name']}: {repo['stargazers_count']} stars")

ライブラリは、特殊文字をエスケープして、パラメータを使用して正しいURLを自動的に生成します。

POSTリクエストとデータの送信

POSTリクエストは、リソースを作成したり、フォームを送信したりするために使用されます。JSONを送信する例を考えてみましょう。

# 新しいリソースの作成
data = {
    'title': 'I'm studying requests',
    'body': 'This is a very convenient library!',
    'userId': 1
}

response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)

if response.status_code == 201:
    print('Resource created!')
    print(response.json())

json パラメータに注意してください。requests は自動的にJSONで辞書をシリアル化し、正しいヘッダー Content-Typeを設定します。

見出しの操作

多くのAPIは、ヘッダーを介した認証を必要とします。方法は次のとおりです。

headers = {
    'Authorization': 'Bearer YOUR_TOKEN_HERE',
    'User-Agent': 'MyApp/1.0'
}

response = requests.get('https://api.example.com/data', headers=headers)

一部のAPIはAPIキーを使用します。

headers = {'X-API-Key': 'your_api_key'}
response = requests.get('https://api.example.com/protected', headers=headers)

エラー処理

適切なエラー処理なしに、API を使用したプロフェッショナルな作業は不可能です。

try:
    response = requests.get('https://api.example.com/data', timeout=5)
    response.raise_for_status()  # 4 xxおよび5 xxコードの例外をスローします
    
    data = response.json()
    
except requests.exceptions.HTTPError as http_err:
    print(f'HTTP error: {http_err}')
except requests.exceptions.ConnectionError:
    print('Connection error')
except requests.exceptions.Timeout:
    print('Timeout')
except requests.exceptions.RequestException as err:
    print(f'An error occurred: {err}')

raise_for_status() メソッドは、サーバーがエラーコードを返した場合に自動的に例外をスローします。

複数のリクエストのためのセッション

1 つの API に対して複数のリクエストを行う必要がある場合は、セッションを使用します。セッションはクッキーと接続を保存するため、作業が大幅に高速化されます。

session = requests.Session()
session.headers.update({'Authorization': 'Bearer TOKEN'})

# セッション内のすべてのリクエストは共通のヘッダーを使用します
response1 = session.get('https://api.example.com/users')
response2 = session.get('https://api.example.com/posts')
response3 = session.post('https://api.example.com/comments', json={'text': 'Hello'})

session.close()

コンテキストマネージャーを使用することをお勧めします。

with requests.Session() as session:
    session.headers.update({'Authorization': 'Bearer TOKEN'})
    response = session.get('https://api.example.com/data')

ファイルの操作

API を介したファイルのアップロードも簡単です。

# ファイルを読み込んでいます
files = {'file': open('document.pdf', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)

# ファイルのダウンロード
response = requests.get('https://example.com/image.jpg', stream=True)
with open('image.jpg', 'wb') as file:
    for chunk in response.iter_content(chunk_size=8192):
        file.write(chunk)

stream = Trueパラメータを使用すると、大きなファイルをメモリに完全にロードすることなく、バッチでロードできます。

実例:気象APIの操作

完全な天気予報アプリを作成しましょう。

import requests

def get_weather(city, api_key):
    """Gets the current weather for the specified city"""
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    
    params = {
        'q': city,
        'appid': api_key,
        'units': 'metric',
        'lang': 'ru'
    }
    
    try:
        response = requests.get(base_url, params=params, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        
        weather_info = {
            'city': data['name'],
            'temperature': data['main']['temp'],
            'feels': data['main']['feels_like'],
            'description': data['weather'][0]['description'],
            'Humidity': data['main']['humidity'],
            'Wind': data['wind']['speed']
        }
        
        return weather_info
        
    except requests.exceptions.RequestException as e:
        print(f"Error retrieving data: {e}")
        return None

# 使用
weather = get_weather('Moscow', 'YOUR_API_KEY')
if weather:
    print(f"Weather in the city {weather['city']}:"
    print(f"Temperature: {weather['temperature']}°C")
    print(f"Feels like: {weather['ощущается']}°C"  print(f"Description: {weather['description']}"]}")

高度なオプション

アダプターを使用した再試行メカニズム:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

session = requests.Session()
retry = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

response = session.get('https://api.example.com/data')

認証の操作:

# Basic Auth
response = requests.get('https://api.example.com/data', 
                       auth=('username', 'password'))

# OAuth 2.0は通常ヘッダーを介して
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get('https://api.example.com/data', headers=headers)

結論

リクエストライブラリは、PythonのAPIを楽しくします。シンプルで直感的な構文、強力な機能、優れたドキュメントにより、PythonのHTTPリクエストのデファクトスタンダードとなっています。リクエストを習得することで、プロジェクトに数千の異なるサービスを統合し、本当に強力なアプリケーションを作成することができます。

アプリケーション コディック Python、JavaScript、API、その他多くの構造化コースを提供します。インタラクティブなレッスン、実践的なタスク、ステップバイステップの学習は、あなたが開発者になるのに役立ちます。

私たちの Telegramチャンネル経験豊富な開発者のサポート、役立つ資料、プログラミングに関する質問への回答が見つかります。志を同じくする人々のコミュニティと一緒に、快適なペースで学びましょう!

🎯先延ばしをやめよう

記事は気に入った?
実践の時間だ!

Kodikでは読むだけでなく、すぐにコードを書く。理論 + 実践 = 本当のスキル。

即座に実践
🧠AIがコードを説明
🏆修了証

登録不要 • カード不要