API Request, Response, and Error Shapes Clients Can Trust

Design consistent API request and response envelopes, validation errors, and problem details so client developers can handle success and failure reliably.

published: reading time: 11 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

Use one response contract for the order API. The examples cover success, validation, permission, missing products, and server errors, followed by a client parser that handles malformed gateway responses. They also cover batch outcomes and safe logging.

API Request, Response, and Error Shapes Clients Can Trust

Introduction

Clients need to know what to send and how to distinguish a validation failure from a server problem. The order endpoint below shows the success body, expected failures, and a defensive client parser.

A practical error shape

Problem Details (application/problem+json) defines type, title, status, detail, and instance. An API can add documented extensions such as a stable code or field-level errors. When a problem body includes status, the server must use the same HTTP status code in the response line. RFC 9457 defines the format; it does not replace HTTP status semantics.

One endpoint, five outcomes

Use POST /v1/tenants/t_17/orders for each case below. The caller is authenticated, and a successful order request looks like this:

POST /v1/tenants/t_17/orders
Content-Type: application/json

{
  "productId": "prd_42",
  "quantity": 2,
  "shippingAddressId": "addr_81"
}

Order created

HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/tenants/t_17/orders/ord_91

{
  "id": "ord_91",
  "status": "pending",
  "productId": "prd_42",
  "quantity": 2
}

Field validation failed

For quantity: 0, return a 422 Problem Details response. Here, code and errors are API-defined extensions; pointer identifies the field in the submitted JSON.

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation",
  "title": "Request validation failed",
  "status": 422,
  "detail": "Correct the marked fields and try again.",
  "instance": "/problem-occurrences/req_validation",
  "code": "validation_failed",
  "errors": [
    {
      "pointer": "/quantity",
      "code": "must_be_positive",
      "detail": "Quantity must be greater than zero."
    }
  ]
}

Permission denied or product missing

In this contract, 403 means the caller may not create orders for the tenant. Check permission before looking up the product. 404 means the authorized request referenced a product with no current representation. These statuses are not interchangeable:

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/forbidden",
  "title": "Forbidden",
  "status": 403,
  "detail": "You cannot create orders for this tenant.",
  "instance": "/problem-occurrences/req_forbidden",
  "code": "permission_denied"
}
HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/not-found",
  "title": "Product not found",
  "status": 404,
  "detail": "The referenced product is unavailable.",
  "instance": "/problem-occurrences/req_missing",
  "code": "resource_not_found"
}

If resource existence is sensitive, an API may intentionally use the same 404 response for both an absent resource and a forbidden one. RFC 9110 permits that choice; document it as a deliberate concealment policy rather than treating 403 and 404 as synonyms.

Unexpected server failure

Return a generic 500 problem and a request identifier for support. Keep the exception in protected logs, not in the response:

HTTP/1.1 500 Internal Server Error
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/internal-error",
  "title": "Internal server error",
  "status": 500,
  "detail": "The order could not be created. Contact support with the request ID.",
  "instance": "/problem-occurrences/req_server",
  "code": "internal_error",
  "requestId": "req_server"
}

Do not return SQL, filesystem paths, stack traces, secrets, or unrestricted submitted values in any error body. Keep validation messages specific enough to fix the request without confirming sensitive account or resource existence.

The response bodies above follow the Problem Details shape in RFC 9457. HTTP semantics for 403 and 404 are defined separately.

Model the response path

sequenceDiagram
    participant Client
    participant API
    participant Validator
    participant Service
    Client->>API: Request with contract fields
    API->>Validator: Parse and validate
    alt Invalid input
        Validator-->>API: Field violations
        API-->>Client: 4xx problem response
    else Valid input
        Validator-->>API: Typed input
        API->>Service: Apply business operation
        Service-->>API: Result
        API-->>Client: 2xx representation
    end

This boundary helps keep HTTP concerns out of domain code. The validator produces a known input shape; the service returns a domain outcome; the API layer maps outcomes to status codes and response formats.

When to use and when not to use

Shared response contracts help when clients ship independently from the server. Field-level errors let form clients point to rejected inputs. For a small internal endpoint, a status code and content type may be enough; avoid a wrapper that adds no useful information. Do not return a success-shaped body for failure, because intermediaries and generic client libraries rely on HTTP status semantics.

Trade-offs between response patterns

Design Strength Cost
Problem Details Standard fields and clear media type Extensions still need documentation
Custom stable error code Straightforward client branching Requires governance and code catalog
Generic {data, error} envelope Uniform JSON shape Can obscure status semantics and add wrappers
Raw framework error Cheap during development Leaks details and changes across versions

Implementation snippet

Map known errors centrally, then keep unexpected failures generic:

function toProblem(error: unknown, requestId: string): Response {
  const instance = `/problem-occurrences/${requestId}`;
  const problem =
    error instanceof ValidationError
      ? {
          type: "https://api.example.com/problems/validation",
          title: "Request validation failed",
          status: 422,
          detail: "Correct the marked fields and try again.",
          code: "validation_failed",
          errors: error.fields,
        }
      : error instanceof ForbiddenError
        ? {
            type: "https://api.example.com/problems/forbidden",
            title: "Forbidden",
            status: 403,
            detail: "You cannot create orders for this tenant.",
            code: "permission_denied",
          }
        : error instanceof ProductNotFoundError
          ? {
              type: "https://api.example.com/problems/not-found",
              title: "Product not found",
              status: 404,
              detail: "The referenced product is unavailable.",
              code: "resource_not_found",
            }
          : {
              type: "https://api.example.com/problems/internal-error",
              title: "Internal server error",
              status: 500,
              detail:
                "The request could not be completed. Contact support with the request ID.",
              code: "internal_error",
              requestId,
            };

  return Response.json(
    { ...problem, instance },
    {
      status: problem.status,
      headers: { "Content-Type": "application/problem+json" },
    },
  );
}

The production handler should log the internal exception with the request ID, while returning only safe details to the caller.

Parse the response defensively

Gateways can return HTML or malformed JSON before this handler runs. The client should fall back to the HTTP status and keep success bodies untrusted until they pass the response schema.

interface ProblemDetails {
  type: string;
  status: number;
  code?: string;
}

function isProblemDetails(value: unknown): value is ProblemDetails {
  if (typeof value !== "object" || value === null) return false;
  const candidate = value as Record<string, unknown>;
  return (
    typeof candidate.type === "string" &&
    typeof candidate.status === "number" &&
    (candidate.code === undefined || typeof candidate.code === "string")
  );
}

async function readApiResponse(response: Response): Promise<unknown> {
  const mediaType = (response.headers.get("content-type") ?? "").toLowerCase();
  const body: unknown = mediaType.includes("json")
    ? await response.json().catch(() => null)
    : null;

  if (!response.ok) {
    const problem =
      isProblemDetails(body) && body.status === response.status ? body : null;
    throw new Error(problem?.code ?? `http_${response.status}`);
  }

  return body;
}

Use stable codes for branching, not detail. Validate a successful body against the order schema before passing it to application code. For fixture and schema examples, see API examples, schemas, and error documentation.

Production failure scenarios and mitigations

A frontend depends on an error message string and breaks after copy editing. Give clients stable codes and treat detail as display text. A gateway replaces a JSON error with an HTML timeout page; document gateway behavior and let clients handle invalid response bodies defensively. A batch endpoint returns 200 when individual items failed, but provides no per-item status; define partial success explicitly with per-item outcomes or make the whole request atomic. A deployment changes field names without a migration window; use additive changes and contract checks.

Observability checklist

  • Track status, stable error code, route template, request ID, and latency.
  • Measure validation failures by field code without recording submitted private values.
  • Separate expected client errors from unexpected server errors in alerts.
  • Monitor response content type and body size, including gateway-generated errors.

Security and privacy notes

Error bodies are public output. Redact credentials and personal data, sanitize reflected input, and avoid stack traces. If resource existence is sensitive, follow the API’s documented concealment policy. Apply the same care to logs: restrict access, define retention, and avoid storing full request bodies when they may contain personal or regulated data. Encode user-supplied text for its display context so an error message cannot become an injection path.

Common pitfalls

  • Returning a different error schema from each route forces clients to maintain endpoint-specific parsers.
  • Changing or reusing error codes makes client handling unreliable; treat documented codes as part of the API contract.
  • Using 200 OK for a failed operation breaks generic HTTP handling and hides failures from caches and monitoring.
  • Returning an empty 500 without a request identifier leaves operators with no useful way to find the protected server-side exception.
  • Logging complete request bodies can expose credentials and personal data. Log safe fields and a correlation ID instead.

Quick recap checklist

  • Document request fields, success payloads, and error payloads together.
  • Return meaningful HTTP status codes and stable machine-readable error codes.
  • Keep public error details safe while recording useful diagnostics in protected logs.
  • Include a request identifier that connects a client response to server-side traces or logs.

Interview questions

1. Why should clients branch on an error code instead of the detail string?
Human-readable text can be edited or localized. A documented code such as validation_failed provides a stable machine-readable condition.
2. What does a Problem Details response add to a plain error message?
It gives errors a standard media type and fields for the problem type, title, HTTP status, instance, and detail. An API can add documented extensions for cases such as field-level errors.
3. How can an API return useful diagnostics without leaking internals?
Return a safe error code and request identifier, log the full exception in a protected system, and use that identifier to correlate the two during debugging.
4. How should a batch API communicate partial success?
Document whether the operation is atomic. If items can succeed independently, return a clear outcome for each item so clients can identify which ones failed; do not imply that the entire batch succeeded with a bare 200 response.
5. What information belongs in a field-level validation error?
Include a stable field identifier and machine-readable reason, with a safe message that helps the caller correct the input. Do not include submitted secrets or unrestricted attacker-controlled values.
6. Why should an API client handle a non-JSON error body?
A proxy, gateway, or web server may return HTML or plain text for failures before the API handler runs. Clients should preserve the HTTP status and handle an unparseable body without crashing.
7. Why should the HTTP status and status field in a Problem Details body agree?
Clients and intermediaries use the HTTP status line, while some application code also reads the body. A mismatch creates conflicting signals and makes retries, monitoring, and support harder to reason about.
8. Why can returning different login errors reveal account information?
If the response distinguishes an unknown account from a wrong password, an attacker can test which accounts exist. Use consistent public error behavior where enumeration would create a risk.
9. When should a generic response envelope be used?
Use a wrapper when it provides shared metadata or another documented capability clients need. Avoid adding one solely for visual uniformity if it obscures HTTP status semantics or forces every client to unwrap unused data.

Further reading

Conclusion

Give clients one documented shape for success and problems. Keep the public body small, use status codes consistently, and leave diagnostic details in protected logs.

Category

Related Posts

API Resource Names, Relationships, and Collections

Model API URLs around stable resources and relationships, with clear collection behavior that clients can navigate without learning server internals.

#api-design #rest #resource-modeling

HTTP Methods, Status Codes, and Headers in API Design

Choose HTTP methods that match the operation, return status codes clients can act on, and use headers for metadata, caching, and safe retries.

#api-design #http #rest

API Examples, Schemas, and Useful Error Documentation

Write API examples, schemas, and error docs that help developers send valid requests, handle failures, and understand exactly what a response means.

#api-documentation #schemas #error-handling