Skip to content

Response Envelopes

HTTP is already an envelope. When to add another one, and how to keep it minimal.

An HTTP response is already an envelope: the status code indicates success or failure, headers carry metadata (content type, cache directives, rate limit state, request IDs), and the body is the payload. Wrapping every response body in { "data": ..., "meta": ... } is a second envelope layered on top of the first.

That’s not inherently wrong, but it should be a deliberate choice rather than a default habit.

The case against

A plain response for a single resource:

HTTP/1.1 200 OK
Content-Type: application/json
X-Request-ID: 7d3f9c2a-1b4e-4c8d-9e6f-2a5b8c1d4e7f

{
  "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "email_address": "alice@example.com",
  "created_at": "2024-01-15T10:30:00.000Z"
}

This is unambiguous. 200 means success. The body is the user. Clients deserialize directly into their model object. SDK generators produce clean types. The shape is obvious to anyone reading the documentation.

Adding a wrapper changes nothing structurally useful:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "data": {
    "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "email_address": "alice@example.com",
    "created_at": "2024-01-15T10:30:00.000Z"
  },
  "meta": {
    "request_id": "7d3f9c2a-1b4e-4c8d-9e6f-2a5b8c1d4e7f",
    "api_version": "1.0"
  }
}

The information in meta is already available: request_id from the X-Request-ID response header, api_version from the URL. Duplicating it in the body means clients have two sources of truth that can diverge.

When an envelope is worth it

Pagination metadata. A collection response needs to carry a cursor alongside the items. There’s no standard HTTP mechanism for this, so the body is the right place:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "data": [ ... ],
  "pagination": {
    "next_cursor": "eyJpZCI6IjEyMyJ9",
    "has_next_page": true,
    "limit": 20
  }
}

This is a real need. data and pagination serve different consumers (the item list vs. the client’s paging logic) and separating them in the body is genuinely useful.

Consistent error shape. When building an SDK that needs to parse errors the same way regardless of status code or endpoint, a stable top-level error key helps:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "email_address is not a valid email",
    "details": [
      {
        "code": "INVALID_FORMAT",
        "pointer": "/email_address",
        "message": "Must be a valid email address"
      }
    ]
  }
}

The error key at the top level is a useful convention for clients. It’s always present on non-2xx responses, never present on 2xx responses, and can be handled in a single place in the SDK.

The minimal envelope

If you add an envelope, keep it to what carries its weight:

Key When to include
data Always on success (singles and collections)
pagination Collections only, when the list is paginated
error Always on non-2xx; never on 2xx
type Pagination struct {
    NextCursor  *string `json:"next_cursor"`
    HasNextPage bool    `json:"has_next_page"`
    Limit       int     `json:"limit"`
}

type ErrorDetail struct {
    Code    string `json:"code"`
    Pointer string `json:"pointer"`
    Message string `json:"message"`
}

type APIError struct {
    Code    string        `json:"code"`
    Message string        `json:"message"`
    Details []ErrorDetail `json:"details,omitempty"`
}

type Success[T any] struct {
    Data       T           `json:"data"`
    Pagination *Pagination `json:"pagination,omitempty"`
}

type Failure struct {
    Error APIError `json:"error"`
}
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Envelope<T> {
    Success {
        data: T,
        #[serde(skip_serializing_if = "Option::is_none")]
        pagination: Option<Pagination>,
    },
    Error {
        error: ApiError,
    },
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Pagination {
    pub next_cursor: Option<String>,
    pub has_next_page: bool,
    pub limit: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ApiError {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub details: Vec<ErrorDetail>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorDetail {
    pub code: String,
    pub pointer: String,
    pub message: String,
}
interface Pagination {
  next_cursor: string | null;
  has_next_page: boolean;
  limit: number;
}

interface ErrorDetail {
  code: string;
  pointer: string;
  message: string;
}

interface ApiError {
  code: string;
  message: string;
  details?: ErrorDetail[];
}

type SuccessEnvelope<T> = {
  data: T;
  pagination?: Pagination;
};

type ErrorEnvelope = {
  error: ApiError;
};

type Envelope<T> = SuccessEnvelope<T> | ErrorEnvelope;

Don’t add meta for things that already have a home in HTTP headers. A request_id field in the body that mirrors X-Request-ID in the header is redundant; pick one and commit to it. Headers are the right place: they’re available in access logs and reverse proxy traces without parsing the body.

Never mix data and error

A response is either a success or a failure. Never include both data and error in the same response body:

# Wrong: ambiguous state
{
  "data": { ... },
  "error": null
}

# Right: success
HTTP/1.1 200 OK
{ "data": { ... } }

# Right: failure
HTTP/1.1 400 Bad Request
{ "error": { ... } }

An "error": null field on a success response is noise that trains clients to null-check a field that is never populated on the happy path. Absence is the signal.

Type to search…

↑↓ navigate↵ selectEsc close