Python requestsライブラリの使い方完全ガイド!HTTPリクエスト入門【2025年最新版】

PythonでWebAPIを使ったりWebスクレイピングをしたいけど、HTTPリクエストの送信方法が分からないと悩んでいませんか?Python requestsライブラリは、HTTPリクエストを簡単に送信できる最も人気の高いライブラリです。この記事では、requestsの基本的な使い方から実践的なテクニックまで、初心者にも分かりやすく解説します。

Python requestsとは?できることを解説

requestsは、PythonでHTTPリクエストを送信するためのライブラリです。Web APIとの通信、Webページの取得、ファイルのダウンロードなど、Web関連の処理を簡単に実装できます。

requestsでできること

  • Web API通信: REST APIからのデータ取得・送信
  • Webスクレイピング: HTMLページの取得・解析
  • ファイルダウンロード: 画像や文書の自動ダウンロード
  • 認証処理: Basic認証やOAuth認証
  • セッション管理: ログイン状態の維持

Python requestsのインストール方法

requestsライブラリは多くのPython環境に標準でインストールされていますが、念のため確認してインストールしましょう。

pip install requests

【基本編】requestsの使い方

1. 基本的なGETリクエスト

import requests

# Webページを取得
response = requests.get('https://httpbin.org/get')

print(response.status_code)  # 200
print(response.text)         # レスポンス内容
print(response.json())       # JSON形式で取得

2. パラメータ付きGETリクエスト

import requests

# URLパラメータを指定
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)

print(response.url)  # https://httpbin.org/get?key1=value1&key2=value2
print(response.json()['args'])  # パラメータの確認

3. POSTリクエストでデータ送信

import requests

# フォームデータを送信
data = {'username': 'testuser', 'password': 'testpass'}
response = requests.post('https://httpbin.org/post', data=data)

# JSONデータを送信
json_data = {'name': '田中太郎', 'age': 30}
response = requests.post('https://httpbin.org/post', json=json_data)

print(response.json()['json'])  # 送信したJSONデータ

【実践編】requestsの応用テクニック

1. ヘッダーの設定

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': 'application/json',
    'Authorization': 'Bearer your-token-here'
}

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

2. ファイルのダウンロード

import requests

def download_file(url, filename):
    response = requests.get(url, stream=True)
    
    with open(filename, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)
    
    print(f"ダウンロード完了: {filename}")

# 使用例
download_file('https://example.com/image.jpg', 'downloaded_image.jpg')

3. セッションの使用

import requests

# セッションを作成
session = requests.Session()
session.headers.update({'User-Agent': 'MyApp/1.0'})

# ログイン
login_data = {'username': 'user', 'password': 'pass'}
session.post('https://example.com/login', data=login_data)

# ログイン状態でAPI呼び出し
response = session.get('https://example.com/api/profile')
print(response.json())

4. タイムアウトとリトライ処理

import requests
import time

def robust_request(url, max_retries=3, timeout=10):
    for attempt in range(max_retries):
        try:
            response = requests.get(url, timeout=timeout)
            response.raise_for_status()  # HTTPエラーを例外として発生
            return response
        except requests.RequestException as e:
            if attempt == max_retries - 1:
                raise e
            time.sleep(2 ** attempt)  # エクスポネンシャルバックオフ

# 使用例
response = robust_request('https://api.example.com/data')

HTTPメソッド別requestsの使い方

メソッド用途使用例
GETデータ取得requests.get(url)
POSTデータ作成requests.post(url, data=data)
PUTデータ更新requests.put(url, data=data)
DELETEデータ削除requests.delete(url)
PATCH部分更新requests.patch(url, data=data)

REST API操作の実例

import requests

base_url = 'https://jsonplaceholder.typicode.com'

# GET: データ取得
response = requests.get(f'{base_url}/posts/1')
post = response.json()
print(f"取得: {post['title']}")

# POST: データ作成
new_post = {'title': '新しい投稿', 'body': '投稿内容', 'userId': 1}
response = requests.post(f'{base_url}/posts', json=new_post)
created_post = response.json()
print(f"作成: ID {created_post['id']}")

# PUT: データ更新
updated_post = {'id': 1, 'title': '更新された投稿', 'body': '更新内容', 'userId': 1}
response = requests.put(f'{base_url}/posts/1', json=updated_post)
print(f"更新: {response.status_code}")

# DELETE: データ削除
response = requests.delete(f'{base_url}/posts/1')
print(f"削除: {response.status_code}")

requestsでよく使うレスポンス属性

レスポンス情報の取得

import requests

response = requests.get('https://httpbin.org/get')

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

# ヘッダー情報
print(f"Content-Type: {response.headers['content-type']}")

# レスポンス内容
print(f"テキスト: {response.text[:100]}...")  # 最初の100文字
print(f"バイナリ: {len(response.content)} bytes")

# JSON形式(APIレスポンス)
if response.headers.get('content-type', '').startswith('application/json'):
    print(f"JSON: {response.json()}")

# リクエスト情報
print(f"リクエストURL: {response.url}")
print(f"実行時間: {response.elapsed.total_seconds()}秒")

認証の実装方法

1. Basic認証

import requests
from requests.auth import HTTPBasicAuth

# 方法1: authパラメータ
response = requests.get('https://httpbin.org/basic-auth/user/pass', 
                       auth=HTTPBasicAuth('user', 'pass'))

# 方法2: タプルで指定
response = requests.get('https://httpbin.org/basic-auth/user/pass', 
                       auth=('user', 'pass'))

print(response.json())

2. Bearer Token認証

import requests

def api_request_with_token(url, token):
    headers = {'Authorization': f'Bearer {token}'}
    response = requests.get(url, headers=headers)
    return response.json()

# 使用例
token = 'your-api-token-here'
data = api_request_with_token('https://api.example.com/user', token)
print(data)

3. OAuth認証

import requests
from requests_oauthlib import OAuth1

# OAuth 1.0a
auth = OAuth1('client_key', 'client_secret', 'resource_owner_key', 'resource_owner_secret')
response = requests.get('https://api.twitter.com/1.1/account/verify_credentials.json', auth=auth)

エラーハンドリングとデバッグ

1. 例外処理の実装

import requests
from requests.exceptions import RequestException, Timeout, ConnectionError

def safe_api_call(url):
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()  # 4xx, 5xxエラーで例外発生
        return response.json()
    
    except Timeout:
        print("リクエストがタイムアウトしました")
    except ConnectionError:
        print("接続エラーが発生しました")
    except requests.HTTPError as e:
        print(f"HTTPエラー: {e.response.status_code}")
    except RequestException as e:
        print(f"リクエストエラー: {e}")
    
    return None

# 使用例
result = safe_api_call('https://api.example.com/data')

2. レスポンスのデバッグ

import requests

response = requests.get('https://httpbin.org/get')

# リクエスト情報の確認
print("=== リクエスト情報 ===")
print(f"Method: {response.request.method}")
print(f"URL: {response.request.url}")
print(f"Headers: {dict(response.request.headers)}")

# レスポンス情報の確認
print("\n=== レスポンス情報 ===")
print(f"Status: {response.status_code}")
print(f"Headers: {dict(response.headers)}")
print(f"Encoding: {response.encoding}")

requestsのパフォーマンス最適化

1. セッションプールの活用

import requests

# セッションでコネクションプールを再利用
session = requests.Session()

# アダプターでコネクションプール設定
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry_strategy = Retry(
    total=3,
    status_forcelist=[429, 500, 502, 503, 504],
    method_whitelist=["HEAD", "GET", "OPTIONS"]
)

adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=20, pool_maxsize=20)
session.mount("http://", adapter)
session.mount("https://", adapter)

# 複数リクエストで効率的
for i in range(10):
    response = session.get(f'https://httpbin.org/get?page={i}')
    print(f"Page {i}: {response.status_code}")

2. 並列処理での高速化

import requests
import concurrent.futures

def fetch_url(url):
    response = requests.get(url)
    return {'url': url, 'status': response.status_code, 'length': len(response.text)}

urls = [f'https://httpbin.org/delay/{i}' for i in range(1, 4)]

# 並列処理でリクエスト
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(fetch_url, urls))

for result in results:
    print(f"{result['url']}: {result['status']} ({result['length']} chars)")

実用的なrequests活用事例

1. Web API クライアントの作成

import requests

class APIClient:
    def __init__(self, base_url, api_key):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })
    
    def get(self, endpoint):
        url = f"{self.base_url}/{endpoint}"
        response = self.session.get(url)
        response.raise_for_status()
        return response.json()
    
    def post(self, endpoint, data):
        url = f"{self.base_url}/{endpoint}"
        response = self.session.post(url, json=data)
        response.raise_for_status()
        return response.json()

# 使用例
client = APIClient('https://api.example.com', 'your-api-key')
users = client.get('users')
new_user = client.post('users', {'name': '田中太郎', 'email': 'tanaka@example.com'})

2. Webhook受信サーバー

import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    data = request.json
    
    # 外部APIに転送
    response = requests.post('https://api.example.com/process', json=data)
    
    if response.status_code == 200:
        return jsonify({'status': 'success'}), 200
    else:
        return jsonify({'status': 'error'}), 500

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

3. データ収集パイプライン

import requests
import json
import time

class DataCollector:
    def __init__(self, api_endpoint, output_file):
        self.api_endpoint = api_endpoint
        self.output_file = output_file
        self.session = requests.Session()
    
    def collect_data(self, pages=5):
        all_data = []
        
        for page in range(1, pages + 1):
            try:
                response = self.session.get(f"{self.api_endpoint}?page={page}")
                response.raise_for_status()
                
                data = response.json()
                all_data.extend(data.get('results', []))
                
                print(f"Page {page} collected: {len(data.get('results', []))} items")
                time.sleep(1)  # レート制限対応
                
            except requests.RequestException as e:
                print(f"Error on page {page}: {e}")
                continue
        
        # データ保存
        with open(self.output_file, 'w', encoding='utf-8') as f:
            json.dump(all_data, f, ensure_ascii=False, indent=2)
        
        print(f"Total collected: {len(all_data)} items")
        return all_data

# 使用例
collector = DataCollector('https://api.example.com/data', 'collected_data.json')
data = collector.collect_data(pages=10)

requestsとcookieの操作

Cookieの取得と送信

import requests

# Cookieを取得
response = requests.get('https://httpbin.org/cookies/set/test/value')
cookies = response.cookies

print(f"取得したCookie: {cookies}")

# Cookieを送信
response = requests.get('https://httpbin.org/cookies', cookies=cookies)
print(response.json())

# セッションでCookie自動管理
session = requests.Session()
session.get('https://httpbin.org/cookies/set/session/12345')
response = session.get('https://httpbin.org/cookies')
print("セッションCookie:", response.json())

SSL証明書とプロキシの設定

SSL証明書の設定

import requests

# SSL証明書の検証を無効化(非推奨)
response = requests.get('https://example.com', verify=False)

# カスタム証明書を指定
response = requests.get('https://example.com', verify='/path/to/cert.pem')

# クライアント証明書を使用
response = requests.get('https://example.com', cert=('/path/to/client.cert', '/path/to/client.key'))

プロキシの設定

import requests

proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

response = requests.get('https://httpbin.org/ip', proxies=proxies)
print(response.json())

# 認証付きプロキシ
proxies = {
    'http': 'http://user:pass@proxy.example.com:8080',
    'https': 'https://user:pass@proxy.example.com:8080'
}

requestsのベストプラクティス

1. 設定の外部化

import requests
import os
from dataclasses import dataclass

@dataclass
class APIConfig:
    base_url: str
    api_key: str
    timeout: int = 30
    max_retries: int = 3

def load_config():
    return APIConfig(
        base_url=os.getenv('API_BASE_URL', 'https://api.example.com'),
        api_key=os.getenv('API_KEY'),
        timeout=int(os.getenv('API_TIMEOUT', '30')),
        max_retries=int(os.getenv('API_MAX_RETRIES', '3'))
    )

config = load_config()

2. ログ記録の実装

import requests
import logging

# ログ設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def logged_request(method, url, **kwargs):
    logger.info(f"Sending {method} request to {url}")
    
    try:
        response = requests.request(method, url, **kwargs)
        logger.info(f"Response: {response.status_code}")
        return response
    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        raise

# 使用例
response = logged_request('GET', 'https://api.example.com/data')

3. レート制限の実装

import requests
import time
from functools import wraps

def rate_limit(calls_per_second=1):
    min_interval = 1.0 / calls_per_second
    last_called = [0.0]
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            elapsed = time.time() - last_called[0]
            left_to_wait = min_interval - elapsed
            if left_to_wait > 0:
                time.sleep(left_to_wait)
            ret = func(*args, **kwargs)
            last_called[0] = time.time()
            return ret
        return wrapper
    return decorator

@rate_limit(calls_per_second=0.5)  # 2秒に1回
def api_call(url):
    return requests.get(url)

# 使用例
for i in range(5):
    response = api_call(f'https://httpbin.org/delay/1')
    print(f"Call {i+1}: {response.status_code}")

まとめ:requestsでHTTP通信をマスターしよう

Python requestsライブラリは、HTTP通信において最も重要で使いやすいツールです。この記事で紹介した基本的な使い方から高度なテクニックまでを活用すれば、Web APIとの通信やWebスクレイピングを効率的に実装できます。

重要なポイント

  • 適切なエラーハンドリングでロバストなコードを書く
  • セッションを活用してパフォーマンスを向上させる
  • タイムアウトとリトライでネットワークエラーに対処する
  • レート制限でサーバーへの負荷を抑制する

まずは基本的なGET/POSTリクエストから始めて、徐々に認証やセッション管理などの高度な機能を取り入れてみてください。requestsをマスターすれば、PythonでのWeb開発やデータ収集の可能性が大幅に広がります。


この記事がお役に立ちましたら、ぜひシェアしてください。Python requestsやHTTP通信に関するご質問がございましたら、お気軽にコメントでお知らせください。

■「らくらくPython塾」が切り開く「呪文コーディング」とは?

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座