1. Analyze the Request:
* Topic: Doc-driven API style guide.
* Specific areas to cover: Errors, Pagination, Idempotency, Timeouts.
* Style: Professional, structured, instructional (like a standard tech style guide).
-
Deconstruct "Doc-Driven API Style Guide":
- What does this mean? It means the documentation is the contract. The API should be designed with documentation in mind, and the documentation should be explicit enough that developers don't need to guess behavior. The style guide should enforce consistency in how these concepts are presented and implemented.
-
Drafting - Section by Section:
-
Introduction: Briefly define the philosophy (consistency, predictability, developer experience).
-
Section 1: Error Handling (The "What went wrong?" aspect):
- Goal: Make it easy for the client to programmatically handle errors.
- Structure:
- HTTP Status Codes: Stick to standards (4xx/5xx).
- Payload Structure: Needs a standard envelope.
code (machine-readable), message (human-readable), details (debug info/stack trace usually hidden in prod, but validation errors go here).
- Example: JSON representation.
- Rule: Don't return 200 OK with an error body (unless using a weird GraphQL wrapper, but REST assumes proper codes).
-
Section 2: Pagination (The "How to handle large datasets" aspect):
- Goal: Performance and usability.
- Types: Cursor vs. Offset. Cursor is better for real-time/streaming, Offset is easier for jumping to specific pages. Let's recommend Cursor for high volume/real-time and Offset for UI tables, but standardize on one default. Let's pick Cursor-based as the modern standard, or perhaps offer a clear choice. Actually, most style guides mandate one. I'll mandate Offset (limit/offset) for simplicity or Cursor (after/limit) for stability. Let's go with a specific recommendation: Link-header based or Body-based. Body-based is usually easier for devs. Let's define a standard body structure.
- Structure:
data, pagination object (cursor, has_more).
- Rule: Always paginate list endpoints, even if the list is currently short.
-
Section 3: Idempotency (The "Safe retries" aspect):
- Goal: Prevent double charging or double processing on network retries.
- Mechanism:
Idempotency-Key header.
- Behavior:
- Client sends key.
- Server saves response for X hours (usually 24h).
- Subsequent requests with same key return original response (without re-executing logic).
- Scope:
POST requests primarily.
-
Section 4: Timeouts (The "How long to wait" aspect):
- Goal: Reliability and resource management.
- Client vs. Server:
- Server: Define a hard limit (e.g., 30s). Return 504 if exceeded.
- Client: Set timeouts slightly higher than the server's documented max latency.
- Long-running jobs: Don't keep the connection open. Use
202 Accepted + polling/ webhook.
-
Refining and Formatting:
- Use Markdown.
- Use clear headings.
- Include JSON examples (crucial for a "doc-driven" guide).
- Add "Rules/Conventions" bullet points for quick scanning.
-
Self-Correction/Review during drafting:
- Initial thought on Pagination: Should I include
total_count?
- Correction:
total_count is expensive on distributed DBs. I should mention it as optional or recommend avoiding it for performance. I'll stick to has_more as the standard boolean.
- Initial thought on Errors: Should I use
error or errors key?
- Decision: Let's standardize on
error (singular object) containing the details, consistent with RFC 7807 (Problem Details) principles but simplified for readability.
-
Final Polish: Ensure the tone is authoritative yet helpful. (e.g., "Do this," "Avoid that").
-
Output Generation: (This matches the detailed response provided previously.)
(Self-Correction on the specific prompt): The prompt asks for a "Doc-driven API style guide." This implies the guide itself instructs how to write the docs about these features, and how the API behaves to make that documentation possible. I will structure it as: Standard (The Rule) -> Implementation (How it works) -> Documentation Requirement (What to write).
Let's write it out.
- Errors: Standard JSON envelope.
- Pagination: Cursor-based preferred.
- Idempotency: Header-based.
- Timeouts: Timeout vs Retries vs Backoff.
Let's go.
This document defines the standards for handling system resilience, data retrieval, and communication consistency in API design. It follows a Doc-Driven approach: if the behavior is not documented, it does not exist; if it exists, it must be documented.
API Style Guide: Reliability & Data Handling
1. Errors
Errors must be informative, consistent, and machine-readable. A consumer should be able to look at an error payload and know exactly what went wrong and how to fix it without inspecting the stack trace.
The "Problem Detail" Standard
All error responses MUST adhere to the RFC 7807 (Problem Details for HTTP APIs) standard or a strictly enforced superset of it.
Response Structure
{
"type": "https://api.service.com/errors/insufficient-funds",
"title": "Insufficient Funds",
"status": 400,
"detail": "Your account balance is $50.00, but the requested transaction amount is $75.00.",
"instance": "/transactions/abc-123",
"trace_id": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
Field Requirements
| Field | Requirement | Description |
|---|
type | Mandatory | A URI reference identifying the error type. This should point to human-readable documentation for that specific error code. |
title | Mandatory | A short, human-readable summary of the problem type. It should not change from occurrence to occurrence (e.g., "Validation Error"). |
status | Mandatory | The HTTP status code generated by the origin server. |
detail | Mandatory | A human-readable explanation specific to this occurrence of the problem. |
instance | Optional | A URI reference that identifies the specific resource occurrence of the error. |
trace_id | Mandatory | A distributed tracing ID (e.g., W3C Trace Context) to allow correlation with server logs. |
Validation Errors
For 400 Bad Request errors involving multiple field validations, the API MUST return a specific structure to allow UI binding.
{
"type": "https://api.service.com/errors/validation",
"title": "Validation Failed",
"status": 400,
"invalid_params": [
{ "name": "email", "reason": "Must be a valid email address." },
{ "name": "age", "reason": "Must be an integer greater than 18." }
]
}
2. Pagination
Pagination is mandatory for any endpoint returning a collection of resources to prevent memory exhaustion and bandwidth issues.
Cursor-Based Pagination (Preferred)
For large, dynamic datasets, cursor-based pagination SHOULD be used. It relies on opaque tokens pointing to a specific record position.
- Request:
?after=cursor_string&limit=20
- Response:
{
"data": [ ... ],
"pagination": {
"next_cursor": "eyJpZCI6MTIz",
"previous_cursor": "eyJpZCI6MTIw",
"has_more": true
}
}
Offset Pagination (Acceptable for Static Data)
For small, stable datasets where deep skipping is required (e.g., jumping to page 10 immediately), offset pagination is acceptable.
Documentation Rules
- Default limits (e.g.,
limit=20) must be documented.
- Maximum limits (e.g.,
limit=100) must be enforced and documented.
- If a user requests
limit=1000, the API should return 400 or cap it silently at 100 with a warning in the response headers.
3. Idempotency
Idempotency ensures that making the same request multiple times produces the same result state. This is critical for network resilience (retrying dropped connections).
Scope
- MUST be supported for all
POST, PUT, and PATCH operations that create resources or trigger state changes.
GET, HEAD, OPTIONS, TRACE, and DELETE are idempotent by definition (HTTP standards).
Mechanism
Clients MUST send a unique Idempotency-Key header with the request.
- Header Name:
Idempotency-Key
- Value Type: UUID v4 is recommended.
Server Behavior
- First Request: Process the request normally. Store the response body and status code mapped to the
Idempotency-Key in a persistent store (e.g., Redis, Database).
- Subsequent Requests (Same Key):
- If the original request is still processing: Return
409 Conflict or 202 Accepted to indicate work in progress.
- If the original request finished: Return the exact same response body and status code as the first request. Do not re-run business logic.
Documentation Rules
- Document the time-to-live (TTL) for idempotency keys (e.g., "Keys are retained for 24 hours").
- Document what constitutes a "subsequent request" (e.g., changing the request body but keeping the same key should result in an error or a cache hit, depending on your security posture—typically a
422 or return the original cached response).
4. Timeouts
Timeouts prevent clients from hanging indefinitely and consuming resources while waiting for unresponsive services.
Server-Side (API Limits)
The API Gateway/Load Balancer MUST have a hard timeout defined.
- Standard Timeout: 30 seconds.
- Long-Running Processes: If an operation takes longer than 30 seconds, the API MUST switch to an asynchronous pattern (see below).
Asynchronous Pattern
For long-running tasks (report generation, bulk imports), the API MUST use the 202 Accepted pattern.
- Client Request:
POST /reports
- Server Response:
HTTP/1.1 202 Accepted
Location: /queue/jobs/12345
Content-Type: application/json
{
"id": "12345",
"status": "IN_PROGRESS",
"eta": "60s"
}
- Client Duty: Poll the
Location endpoint until status is COMPLETED.
Client-Side Recommendations (Documentation)
API documentation SHOULD explicitly recommend client-side timeout settings.
- Recommendation: "Clients should configure a read timeout of 35 seconds to allow a safety buffer over the server's 30-second hard limit."
Retries & Backoff
Documentation must advise clients on how to handle timeouts.
- Do not retry
4xx errors.
- Retry
5xx and timeouts using Exponential Backoff with Jitter.
- Circuit Breakers: Advise clients to implement circuit breakers to stop hitting an endpoint if failure rates exceed a threshold.