← Back to Home / Coding Prompts

Python API Integration Template

Build robust API client integrations.

Act as a senior software engineer specializing in third-party API integrations for SaaS products, having built 50+ API clients that handle authentication, rate limiting, error handling, pagination, and data synchronization reliably at scale. Generate a complete Python API client template for a specific API type (REST, GraphQL, SOAP, WebSocket), including authentication handling, request retry logic, response parsing, error management, and testing patterns. Begin with client class structure including __init__ method (base URL, API credentials, timeout defaults 30 seconds, session configuration, headers setup), session management (requests.Session for connection pooling, HTTPAdapter with pool connections 50, pool maxsize 100, retry strategy, SSL verification option), configuration validation (required parameters check, environment variable loading .env, config dictionary merge, missing key error raising), and async version option (aiohttp.ClientSession, async context manager, semaphore for concurrency). Implement authentication methods including API key (headers: {"X-API-Key": key}, query parameter: "?api_key=key", Bearer token: "Authorization: Bearer token"), OAuth2 (client credentials grant: POST /token with client_id/secret, password grant: username/password, refresh token handling: token refresh before expiry, token storage and reuse), JWT (token acquisition, expiration check, automatic refresh, signature verification), Basic Auth (requests.auth.HTTPBasicAuth, base64 encoding, HTTPS requirement warning), and session cookies (Session object persistence, CSRF token extraction, cookie expiry handling). Create request handling with retry logic including tenacity library decorator (@retry), retry conditions (status codes 429, 500, 502, 503, 504, timeout exceptions, connection errors), wait strategies (exponential backoff 1s, 2s, 4s, 8s, 16s, max 60s, jitter added 0-1s random), stop conditions (max attempts 3-5, timeout 30 seconds, certain status codes 400/401/403/404 no retry), and idempotency consideration (GET, PUT, DELETE safe to retry, POST requires idempotency key). Add pagination handling for paginated responses including page-based (?page=2&per_page=50), cursor-based (?after=cursor_token, has next page check), offset-limit (?offset=100&limit=50), JSON response parsing (extract data array, next page URL/params, total count if available), generator function (yield items one page at a time, memory efficient), and automatic pagination (collect all pages, max pages limit configurable, progress callback). Implement rate limiting management including headers response parsing (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset), retry-after header parsing and sleep, token bucket algorithm for request pacing, queue with delayed processing, semaphore for concurrent limits, and burst vs sustained limit differentiation. Create error handling including custom exception hierarchy (APIError base, AuthenticationError, RateLimitError, NotFoundError, ValidationError, ServerError), response status code mapping (400 ValidationError, 401 AuthenticationError, 403 PermissionError, 404 NotFoundError, 429 RateLimitError, 500-504 ServerError), response body parsing for error messages (standard field "error"/"message"/"detail"), logging strategy (request ID, endpoint, parameters, error details), and user-facing vs debug error messages separation. Add data validation using Pydantic models (response schema validation, type coercion, field aliases for naming differences, default values for optional fields), serialization (model_dump() for requests, model_validate for responses), and nested model handling for complex responses. Include testing strategy with mock responses (pytest fixtures, responses library, VCR.py for recording cassettes), edge case testing (rate limit exceeded, pagination end, malformed responses, timeout), and integration test sandbox environment. Provide documentation standards with docstrings (Google format, usage examples, parameter descriptions, return schemas, exception raises), README with quick start, authentication setup, endpoints overview, and rate limit guidelines.