Back to all terms
ClientAPI
APIbasic

Response Envelope Pattern

Wrapping API responses in a consistent top-level structure with data, metadata, and error fields for predictable client parsing.

Also known as: API Response Wrapper, Response Wrapper Pattern

Description

The response envelope pattern wraps all API responses in a consistent top-level structure, making it predictable for clients to parse both successful and error responses. A typical envelope includes a data field for the payload, a meta field for pagination info or request metadata, and an errors field for error details. This consistency means clients can write a single response-handling layer rather than special-casing each endpoint.

For successful responses, the envelope might look like: { data: { ... }, meta: { request_id: '...', timestamp: '...' } }. For collection endpoints, the meta field includes pagination details: { data: [...], meta: { total_count: 150, has_more: true, next_cursor: '...' } }. For errors, the structure shifts: { error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: [...] } }. The key principle is that the top-level structure is always the same, and clients check for the presence of data versus error to determine the response type.

Some APIs (notably the JSON:API specification) take this further with standardized envelope structures. Others argue that envelopes add unnecessary nesting and that HTTP status codes combined with content negotiation provide sufficient context. In practice, a lightweight envelope with data, meta, and error fields strikes a good balance between consistency and simplicity, especially when multiple client teams consume the API.

Prompt Snippet

Wrap all responses in a standard envelope: success responses as { data: T, meta: { request_id: string, timestamp: string } } and error responses as { error: { code: string, message: string, details?: FieldError[] } }. For paginated collections use { data: T[], meta: { has_more: boolean, next_cursor: string | null, total_count?: number } }. Implement the envelope as Express middleware that intercepts res.json() calls. Include the X-Request-Id correlation header value in meta.request_id for cross-referencing with server logs.

Tags

response-formatenvelopeconsistencyclient-experience