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.
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 OKfor a failed operation breaks generic HTTP handling and hides failures from caches and monitoring. - Returning an empty
500without 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
validation_failed provides a stable machine-readable condition.
Further reading
- API resource names, relationships, and collections covers resource modeling and collection design.
- API examples, schemas, and error documentation shows how to keep examples and schemas consistent.
- API contracts covers OpenAPI descriptions and compatibility checks.
- RFC 9457: Problem Details for HTTP APIs. Defines the media type and problem-detail members.
- RFC 9110: HTTP Semantics. Defines HTTP status code meanings, including 403 and 404.
- OpenAPI Specification. Describes response schemas, status codes, and examples in an API contract.
- OWASP API Security: Security Misconfiguration. Covers risks from verbose errors and unsafe defaults.
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.
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 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.