mcpField
H
httpx

httpx

github.com/slanycukr開発249 回インストール53 週間前に更新
リポジトリ

httpx について

HTTPX Skill は、同期・非同期 API を備えた Python HTTP クライアント HTTPX の利用ガイドです。クライアント設定、ストリーミング、認証、リクエスト処理のパターンを扱います。

主な機能

  1. 01同期・非同期 API
  2. 02HTTP/1.1 と HTTP/2 に対応
  3. 03コネクションプーリングとストリーミング
  4. 04標準およびカスタム認証
  5. 05タイムアウトとリダイレクト設定
  6. 06Cookie、プロキシ、TLS に対応

活用シーン

  1. 01同期または非同期の Python API クライアント構築
  2. 02大容量ファイルのストリーミング転送
  3. 03認証付きリクエストとタイムアウトの設定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/slanycukr/riot-api-project --skill httpx

インストール後、Claude Code で/httpxを入力して読み込まれたか確認します。

詳細

HTTPX スキル

HTTPX は、同期 API と非同期 API の両方を提供し、HTTP/1.1 と HTTP/2 をサポートする、機能が充実した Python 用 HTTP クライアントです。

クイックスタート

基本的な使い方
import httpx

# Simple GET request
response = httpx.get('https://api.example.com/data')
print(response.status_code)
print(response.json())

# POST request with JSON data
response = httpx.post('https://api.example.com/users', json={'name': 'Alice'})
非同期での使い方
import asyncio
import httpx

async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://api.example.com/data')
        return response.json()

result = asyncio.run(fetch_data())

よく使われるパターン

1. コネクションプーリングを使った非同期クライアント
import httpx

async def make_multiple_requests():
    async with httpx.AsyncClient() as client:
        # Reuse the same client for multiple requests
        tasks = [
            client.get('https://api.example.com/users/1'),
            client.get('https://api.example.com/users/2'),
            client.get('https://api.example.com/users/3')
        ]
        responses = await asyncio.gather(*tasks)
        return [r.json() for r in responses]
2. 認証
import httpx

# Basic Authentication
auth = httpx.BasicAuth(username='user', password='pass')
client = httpx.Client(auth=auth)

# Bearer Token Authentication
headers = {'Authorization': 'Bearer your-token-here'}
client = httpx.Client(headers=headers)

# Per-request authentication
response = client.get('https://api.example.com', auth=('user', 'pass'))
3. ストリーミングダウンロード
import httpx

# Stream large files without loading into memory
with httpx.stream('GET', 'https://example.com/large-file.zip') as response:
    with open('large-file.zip', 'wb') as f:
        for chunk in response.iter_bytes():
            f.write(chunk)

# Async streaming
async def download_large_file():
    async with httpx.AsyncClient() as client:
        async with client.stream('GET', 'https://example.com/large-file.zip') as response:
            with open('large-file.zip', 'wb') as f:
                async for chunk in response.aiter_bytes():
                    f.write(chunk)
4. ストリーミングアップロード
import httpx

# Upload large files with streaming
async def upload_large_file():
    def generate_data():
        # Yield chunks of data
        for i in range(100):
            yield f'chunk {i}\n'.encode()

    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://api.example.com/upload',
            content=generate_data()
        )
        return response
5. エラー処理とタイムアウト
import httpx

# Configure timeouts
client = httpx.Client(
    timeout=httpx.Timeout(10.0, connect=5.0, read=8.0)
)

try:
    response = client.get('https://api.example.com/slow')
    response.raise_for_status()  # Raise exception for 4XX/5XX responses
except httpx.TimeoutException:
    print("Request timed out")
except httpx.HTTPStatusError as e:
    print(f"HTTP error: {e.response.status_code}")
except httpx.RequestError as e:
    print(f"Request failed: {e}")
6. クライアントの設定
import httpx

# Client with shared configuration
client = httpx.Client(
    base_url='https://api.example.com',
    headers={'User-Agent': 'MyApp/1.0'},
    timeout=30.0,
    follow_redirects=True
)

# All requests will use base_url and headers
response = client.get('/users')  # Makes request to https://api.example.com/users
7. カスタム認証
import httpx

class CustomAuth(httpx.Auth):
    def __init__(self, api_key):
        self.api_key = api_key

    def auth_flow(self, request):
        request.headers['X-API-Key'] = self.api_key
        yield request

# Use custom auth
auth = CustomAuth('your-secret-api-key')
client = httpx.Client(auth=auth)
8. 進行状況の監視
import httpx
from tqdm import tqdm

def download_with_progress(url, filename):
    with httpx.stream('GET', url) as response:
        total = int(response.headers.get('content-length', 0))

        with tqdm(total=total, unit='B', unit_scale=True) as progress:
            with open(filename, 'wb') as f:
                for chunk in response.iter_bytes():
                    f.write(chunk)
                    progress.update(len(chunk))
9. リトライ処理
import httpx
import time

def make_request_with_retry(url, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = httpx.get(url, timeout=10.0)
            response.raise_for_status()
            return response
        except httpx.RequestError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponential backoff
10. WebSocket のサポート(httpx-ws を使用)
import httpx
from httpx_ws import connect_ws

async def websocket_example():
    async with httpx.AsyncClient() as client:
        async with connect_ws('wss://echo.websocket.org', client) as websocket:
            await websocket.send_text('Hello, WebSocket!')
            message = await websocket.receive_text()
            print(f"Received: {message}")

実用的なコードスニペット

API クライアントクラス
import httpx
from typing import Optional, Dict, Any

class APIClient:
    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url
        self.client = httpx.Client(
            base_url=base_url,
            headers={'Authorization': f'Bearer {api_key}'},
            timeout=30.0
        )

    def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
        response = self.client.get(endpoint, params=params)
        response.raise_for_status()
        return response.json()

    def post(self, endpoint: str, data: Dict[Any, Any]) -> Dict[Any, Any]:
        response = self.client.post(endpoint, json=data)
        response.raise_for_status()
        return response.json()

    def close(self):
        self.client.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

# Usage
with APIClient('https://api.example.com', 'your-api-key') as client:
    users = client.get('/users')
    new_user = client.post('/users', {'name': 'John', 'email': '[email protected]'})
非同期 API クライアント
import httpx
from typing import Optional, Dict, Any

class AsyncAPIClient:
    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={'Authorization': f'Bearer {api_key}'},
            timeout=30.0
        )

    async def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
        response = await self.client.get(endpoint, params=params)
        response.raise_for_status()
        return response.json()

    async def close(self):
        await self.client.aclose()

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

# Usage
async def main():
    async with AsyncAPIClient('https://api.example.com', 'your-api-key') as client:
        users = await client.get('/users')
        print(users)

要件

httpx>=0.24.0
# Optional dependencies for additional features:
# httpx-ws>=0.6.0  # WebSocket support
# tqdm>=4.65.0     # Progress bars
# anyio>=3.7.0     # Alternative async runtime
# trio>=0.22.0     # Alternative async runtime

主な機能

  • 同期 API と非同期 API:同期コードと非同期コードのどちらにも同じインターフェースを使用できます
  • HTTP/2 のサポート:多重化に対応した完全な HTTP/2 サポート
  • コネクションプーリング:効率的な接続管理
  • ストリーミング:すべてをメモリに読み込まずに、リクエストとレスポンスをストリーミングできます
  • 認証:Basic、Digest、Bearer トークン、およびカスタム認証を標準でサポート
  • タイムアウト:接続、読み取り、およびリクエスト全体のタイムアウトを設定できます
  • リダイレクト処理:リダイレクトの追跡を設定できます
  • Cookie の処理:Cookie を自動的に管理します
  • プロキシのサポート:HTTP および HTTPS プロキシをサポート
  • SSL/TLS:SSL/TLS の設定オプションを幅広く提供

インストール

pip install httpx

# For HTTP/2 support
pip install httpx[http2]

# For WebSocket support
pip install httpx-ws

このスキルは、最新の Python アプリケーション向けに包括的な HTTP クライアント機能を提供し、優れた非同期処理サポートと本番環境に対応した機能を備えています。

コメント