Okay, the user wants a doc-driven API style guide covering four specific areas: errors, pagination, idempotency, and timeouts. This is a structured request, so I need to deliver a comprehensive yet practical guide.
First, I should clarify what "doc-driven" means here—probably an approach where the API documentation itself defines the contract, not just describes it. The user likely wants this to be a living reference for their team, so examples and consistency matter.
Breaking it down: errors need clear standards for status codes and error payloads; pagination requires cursor-based design; idempotency is crucial for safe retries; timeouts must be explicit to prevent hangs. I’ll structure each section with principles, requirements, and examples to make it actionable.
I’ll avoid over-explaining basics but ensure the examples are concrete (like JSON error structures). The tone should be authoritative but not rigid—this is a style guide, not a spec. Maybe add a "when to deviate" note for flexibility.
The user didn’t specify a tech stack, so I’ll keep it generic (REST/JSON) but note where HTTP specifics apply. They might be an architect or lead dev standardizing APIs across teams, so clarity and enforceability are key. I’ll emphasize consistency and client safety upfront.
Doc-Driven API Style Guide: Core Principles
Documentation is the contract. The implementation must match the documented behavior exactly.
1. Errors
Principle
Errors must be machine-parseable, consistent, and actionable. Clients should never need to parse human-readable messages to determine error type.
Requirements
A. HTTP Status Codes
Use standard HTTP status codes semantically:
| Code | Meaning | Use Case |
|---|
200 | OK | Successful request |
201 | Created | Resource created successfully |
204 | No Content | Successful request with no body (DELETE, some PUTs) |
400 | Bad Request | Invalid input, validation errors, malformed JSON |
401 | Unauthorized | Missing/invalid authentication credentials |
403 | Forbidden | Authenticated but lacks permission |
404 | Not Found | Resource doesn't exist (idempotent, safe to retry) |
409 | Conflict | Resource state conflict (e.g., duplicate key, optimistic lock failure) |
422 | Unprocessable Entity | Valid request but business logic prevents fulfillment |
429 | Too Many Requests | Rate limiting |
500 | Internal Server Error | Unexpected server error |
501 | Not Implemented | Endpoint exists but feature not ready |
503 | Service Unavailable | Server down for maintenance/overload |
Never use 200 OK for errors. 5xx errors should be logged server-side with request context for debugging.
B. Error Response Body
Always return JSON with a consistent structure:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "One or more validation errors occurred",
"details": [
{
"field": "email",
"issue": "INVALID_FORMAT",
"message": "Must be a valid email address"
}
],
"request_id": "req_abc123def456",
"timestamp": "2024-01-15T10:30:00Z"
}
}
Field Requirements:
code (required): Machine-readable error code. Format: UPPER_SNAKE_CASE. Must be stable across versions.
message (required): Human-readable description (for logs, debugging). Should not be exposed directly to end-users in production (localize at client).
details (optional): Array of field-specific errors for 400/422 responses.
request_id (required): Unique ID for this request (correlate with server logs).
timestamp (required): ISO 8601 UTC timestamp.
C. Error Code Registry
Maintain a canonical list of all error codes in documentation:
| Code | HTTP Status | Description | Retryable? | User Action |
|---|
INVALID_TOKEN | 401 | Expired or malformed JWT | No | Re-authenticate |
RATE_LIMIT_EXCEEDED | 429 | Too many requests | Yes (after Retry-After) | Slow down requests |
RESOURCE_NOT_FOUND | 404 | Specified ID doesn't exist | Yes | Check ID, create if needed |
CONCURRENT_MODIFICATION | 409 | Optimistic lock failure | Yes | Refresh data, retry |
QUOTA_EXCEEDED | 403 | Account limit reached | No | Contact support/upgrade |
2. Pagination
Principle
Use cursor-based pagination (not offset-based) for scalability, consistency, and avoidance of missing/duplicate records during concurrent modifications.
Requirements
A. Request
Accept these query parameters:
| Parameter | Type | Required | Description |
|---|
cursor | string | No | Opaque cursor from previous response (base64 encoded) |
limit | integer | No | Max items to return (default: 50, max: 200) |
order | string | No | Sort order: asc or desc (default: asc) |
Example Request:
GET /api/v1/orders?cursor=eyJpZCI6MTIzfQ==&limit=25&order=desc
B. Response
Always include pagination metadata in response body:
{
"data": [
{ "id": "order_123", "total": 99.99 }
],
"pagination": {
"next_cursor": "eyJpZCI6MTI0fQ==",
"has_more": true,
"limit": 25,
"estimated_total": 1247
}
}
Field Requirements:
next_cursor (required if has_more: true): Opaque string—clients must treat as black box.
has_more (required): Boolean indicating more pages exist.
limit (required): Echo back the effective limit used.
estimated_total (optional but recommended): Total count estimate (may be approximate for large datasets).
C. Cursor Rules
- Cursors must be opaque and time-bound (expire after reasonable period).
- Must encode enough server-side state to resume pagination (e.g.,
id, created_at).
- Never expose raw database offsets or internal IDs directly.
- Changing
order between requests invalidates previous cursors (return 400 with INVALID_CURSOR error).
3. Idempotency
Principle
Non-GET/HEAD requests must support idempotency to safely handle network retries and duplicate requests.
Requirements
A. Idempotency Key
- Clients must provide
Idempotency-Key: <uuid> header on all POST, PUT, PATCH, DELETE requests.
- Keys are scoped to user + endpoint combination (not global).
- Keys should be v4 UUIDs or similar (e.g.,
key_abc123).
Example:
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
B. Server Behavior
- First request with new key: Process normally, store result & status with the key (TTL: 24h).
- Duplicate request with same key (within TTL): Return exact same response (status code + body) as first request.
- Include header:
Idempotency-Replayed: true
- Key expired/not found: Treat as new request.
- Different HTTP method for same key: Return
409 CONFLICT with IDEMPOTENCY_KEY_METHOD_MISMATCH error.
C. Implementation Notes
- Store
(user_id, path, idempotency_key) → (status_code, response_body, timestamp) mapping.
- Response storage must be exact byte-for-byte copy of original response.
- For long-running operations (async), return
202 Accepted on first call, then use same key on status check to get consistent result.
4. Timeouts
Principle
All API operations must have clear, enforced timeout boundaries to prevent resource exhaustion.
Requirements
A. Client-Side Timeouts
Document recommended client timeout values:
| Operation Type | Recommended Timeout | Rationale |
|---|
| Simple CRUD (GET/POST) | 10 seconds | User-facing interactive requests |
| Bulk operations | 60 seconds | Long-running but bounded |
| Webhook delivery | 5 seconds | Third-party webhook receivers |
| File upload/download | 120 seconds | Network-bound operations |
B. Server-Side Enforcement
- Hard timeout per request:
30 seconds absolute maximum for any synchronous operation.
- Return
504 Gateway Timeout if operation exceeds hard timeout.
- For operations >30s, must be designed as async:
- Accept request → return
202 Accepted with Location: /operations/{id}
- Client polls operation endpoint until
completed/failed.
C. Response Timeout Headers
Include timing information in response headers:
X-Process-Time-MS: 245
X-Timeout-Policy: standard
X-Process-Time-MS: Time spent processing request (excludes network).
X-Timeout-Policy: Identifies timeout tier used (e.g., standard, bulk, upload).
D. Client Guidelines
Clients must:
- Implement circuit breakers for
5xx/429 responses.
- Use exponential backoff with jitter for retries.
- Respect
Retry-After header on 429 responses.
- Set connection-level timeouts < server hard timeout (e.g., client timeout 25s, server 30s).
Implementation Checklist
For each API endpoint, verify:
When to Deviate
Document why you deviate from this guide:
- Legacy API with established contract
- Third-party integration constraints
- Domain-specific requirements (e.g., WebSocket streams)
Always document the deviation rationale in the API spec.
Last updated: 2024-01-15
This guide applies to all REST/JSON APIs in the organization. GraphQL implementations have separate guidelines.