1. Understand the Goal: The user wants a "doc-driven API style guide" focusing on four specific areas: errors, pagination, timeouts, and idempotency. "Doc-driven" implies that the design should prioritize the documentation aspect—clear, human-readable, and consistent—likely following a standard like OpenAPI or a similar specification-first approach, but specifically focusing on the content of the guide itself.
-
Target Audience: API Developers, Technical Writers, and Architects who need a set of rules to ensure consistency across their API ecosystem.
-
Structure of the Style Guide: A style guide needs to be authoritative yet practical. I should structure it logically:
- Introduction/Philosophy: Briefly explain the "doc-driven" approach.
- Core Sections:
- Errors (Handling failures)
- Pagination (Handling large lists)
- Timeouts (Handling latency)
- Idempotency (Handling retries/safety)
- Format: Use clear headings, "Do/Don't" examples, and code snippets (JSON) to make it actionable.
-
Drafting Content - Section by Section:
-
Refining and Formatting:
- Use Markdown.
- Use bolding for emphasis.
- Use code blocks for JSON examples.
- Add a "Why?" or "Rationale" for each section to explain the "doc-driven" aspect (e.g., "Why this error format? Because it generates auto-docs easily").
-
Self-Correction/Review during drafting:
- Initial thought: Maybe include authentication?
- Correction: No, the prompt specifically asked for errors, pagination, timeouts, and idempotency. Stick to the scope.
- Check: Is "doc-driven" interpreted correctly? It usually means "Design First." I need to emphasize that these rules should be encoded in the API specification (OpenAPI) before code.
-
Final Polish:
- Ensure the tone is professional and prescriptive.
- Make sure the JSON examples are valid JSON.
- Check links/references to RFCs (like 7807 or 7231).
-
Output Generation: (This aligns with the provided good response). I will organize it into a template format that a team could actually copy-paste into their internal Wiki or Git repo.
- Structure:
- General Principles.
- Errors (RFC 7807).
- Pagination (Cursor-based).
- Timeouts (Async Pattern).
- Idempotency (Key pattern).
- Summary table.
-
(Self-Correction on Timeouts): Just saying "set a timeout" is too vague. The style guide must address how the API communicates timeouts. The 202 Accepted pattern is the "Style Guide" way to solve long timeouts.
-
(Self-Correction on Pagination): I need to specify the response envelope. { data: [...], pagination: {...} } is a standard doc-driven pattern.
-
Final output generation starts.
This is a design specification for a Doc-Driven API Style Guide. In a doc-driven approach, the documentation is not an afterthought; it is the contract that drives client implementation and server behavior.
This guide mandates specific patterns for four critical architectural pillars: Errors, Pagination, Timeouts, and Idempotency.
API Style Guide: The Stability Pillars
1. Philosophy: The "Doc-First" Contract
All implementation must adhere to the OpenAPI (Swagger) specification defined before code is written. The patterns below are non-negotiable defaults to ensure stability, debuggability, and developer experience (DX).
2. Errors: Structured & Verbose
Errors must be machine-readable so clients can programmatically handle them, and human-readable so developers can fix them.
The Standard: RFC 7807 (Problem Details)
We use the application/problem+json content type. This standardizes error payloads so they are predictable across every endpoint.
Payload Structure
{
"type": "https://api.service.com/errors/insufficient-funds",
"title": "Transaction Failed",
"status": 400,
"detail": "Your account balance is $50.00, but the transaction amount is $75.00.",
"instance": "tr-12345-abcde",
"trace_id": "a1b2c3d4e5f6"
}
Field Specifications
type (string, URI): A unique identifier for the error type. This should link to a documentation page describing the error and how to resolve it.
title (string): A short, human-readable summary of the problem. It should not change from occurrence to occurrence (e.g., "Insufficient Funds").
status (number): The HTTP status code generated by the origin server.
detail (string): A human-readable explanation specific to this occurrence of the problem (e.g., include IDs or limits).
instance (string): A specific ID for this exact request/error event (useful for server logs).
trace_id (string): A distributed tracing ID (e.g., Jaeger/Zipkin) to bridge the gap between API logs and infrastructure logs.
Validation Errors (422 Unprocessable Entity)
When input validation fails, use the errors array to pinpoint specific fields:
{
"type": "https://api.service.com/errors/validation",
"title": "Validation Failed",
"status": 422,
"errors": [
{
"field": "email",
"message": "Must be a valid email address"
},
{
"field": "age",
"message": "Must be greater than 18"
}
]
}
3. Pagination: Cursor-Based vs. Offset
To prevent "drift" when data changes during pagination and to handle large datasets efficiently, we prefer Cursor-Based Pagination for public APIs.
The Envelope Pattern
All list endpoints must return a wrapper object (envelope), never a naked array.
Response Structure:
{
"data": [
{ "id": "obj_1", "name": "Item One" },
{ "id": "obj_2", "name": "Item Two" }
],
"pagination": {
"next_cursor": "eyJpZCI6Im9ial8yIn0=",
"previous_cursor": null,
"has_more": true
}
}
Query Parameters
limit: (int) Number of items per page. Default: 20. Max: 100.
cursor: (string) An opaque token provided by the previous next_cursor or previous_cursor. Clients must treat this as an opaque string and not attempt to decode it.
Rationale
- Stability: If an item is inserted while a user is paging, offset pagination (
?page=2) causes the user to see a duplicate of the last item on page 1. Cursors avoid this.
- Performance:
OFFSET 10000 in SQL is slow. WHERE id > last_seen_id is fast (index seek).
4. Timeouts: The Async Contract
APIs must distinguish between "processing" and "done." In a doc-driven approach, we set explicit SLAs for response times.
The 29-Second Rule
Client-facing gateways should timeout after 29 seconds to stay under the typical 30-second load balancer timeout. However, your API logic should finish much faster.
Handling Long-Running Processes: 202 Accepted
If an operation takes longer than 2 seconds (e.g., generating a PDF report, importing a CSV), do not keep the connection open.
- Request:
POST /reports
- Response:
Client Retry-After
When returning 429 Too Many Requests or 503 Service Unavailable, the API must include the Retry-After header.
- Example:
Retry-After: 120 (Wait 120 seconds).
5. Idempotency: Safe Retries
Networks fail. If a client times out reading a response, they will retry the request. The API must ensure that the same request executed twice does not result in two charges or two database entries.
The Idempotency-Key Header
Required for all POST, PATCH, and DELETE requests that change state.
The Rule:
The client generates a unique key (UUID). The server stores the request payload and the response for 24 hours.
- Request 1: Client sends
POST /charges with header Idempotency-Key: key_123.
- Action: Server processes the charge. Server saves
key_123 -> Response.
- Response:
201 Created.
- Request 2 (Retry): Client times out. Sends
POST /charges again with header Idempotency-Key: key_123.
- Action: Server sees
key_123. It checks if the previous request is still processing.
- If processing: Return
409 Conflict (request in flight).
- If finished: Return the cached
201 Created response immediately.
Documentation Requirement
The API docs must explicitly state the lifecycle of idempotency keys (e.g., "Keys are retained for 24 hours").
Error Handling
If the client reuses an Idempotency-Key with a different request body:
- Response:
422 Unprocessable Entity
- Body: "Idempotency key already used for a different request."
Summary Checklist for Design Docs
When writing the API specification (OpenAPI/Swagger) for a new endpoint, the developer must fill out this checklist:
| Feature | Requirement | Implemented? |
|---|
| Errors | Does it use RFC 7807 (application/problem+json)? | [ ] |
| Pagination | Does it return an object envelope ({ data: [], pagination: {} })? | [ ] |
| Timeouts | If runtime > 2s, does it return 202 Accepted with a Location header? | [ ] |
| Idempotency | Does POST support the Idempotency-Key header? | [ ] |