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.

published: reading time: 8 min read author: Geek Workbench updated: November 4, 2026
Quick Summary

This guide follows an invoice request from JSON example through schema validation, success, and two error responses. It shows how to keep those fixtures consistent in CI and explain stable error codes without exposing internal details.

API Examples, Schemas, and Useful Error Documentation

Introduction

A schema tells a client which payload shapes an API accepts. Examples make those rules concrete, and error responses tell clients what to do when a request fails. Keep the three aligned: a request that passes validation should match the documented success path, and an invalid request should produce a documented error before it changes data.

The invoice below is the running example. Its values are synthetic. Use the API contracts guide to connect these examples to compatibility checks across consumers and providers.

Start with a valid request and response

The client asks to create an invoice with one line item:

{
  "customerId": "cus_demo_42",
  "currency": "USD",
  "lines": [{ "sku": "desk-lamp", "quantity": 2 }]
}

For this fixture, the test catalog prices desk-lamp at 6,499 cents. Two units produce the totalMinor value shown in the success response:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /invoices/inv_demo_202

{
  "id": "inv_demo_202",
  "status": "draft",
  "currency": "USD",
  "totalMinor": 12998
}

The request schema makes the accepted shape and constraints explicit. It rejects unknown fields, requires at least one line, and restricts each quantity to an integer in the documented range.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$defs": {
    "CreateInvoiceRequest": {
      "type": "object",
      "required": ["customerId", "currency", "lines"],
      "additionalProperties": false,
      "properties": {
        "customerId": { "type": "string", "minLength": 1 },
        "currency": { "type": "string", "enum": ["USD"] },
        "lines": {
          "type": "array",
          "minItems": 1,
          "items": {
            "type": "object",
            "required": ["sku", "quantity"],
            "additionalProperties": false,
            "properties": {
              "sku": { "type": "string", "minLength": 1 },
              "quantity": { "type": "integer", "minimum": 1, "maximum": 100 }
            }
          }
        }
      }
    },
    "Invoice": {
      "type": "object",
      "required": ["id", "status", "currency", "totalMinor"],
      "additionalProperties": false,
      "properties": {
        "id": { "type": "string", "minLength": 1 },
        "status": { "type": "string", "enum": ["draft"] },
        "currency": { "type": "string", "enum": ["USD"] },
        "totalMinor": { "type": "integer", "minimum": 0 }
      }
    },
    "ProblemDetails": {
      "type": "object",
      "required": ["type", "title", "status", "code", "requestId"],
      "properties": {
        "type": { "type": "string", "format": "uri" },
        "title": { "type": "string", "minLength": 1 },
        "status": { "type": "integer", "minimum": 400, "maximum": 599 },
        "detail": { "type": "string" },
        "instance": { "type": "string", "format": "uri-reference" },
        "code": { "type": "string", "minLength": 1 },
        "requestId": { "type": "string", "minLength": 1 }
      },
      "additionalProperties": true
    },
    "ValidationProblem": {
      "allOf": [
        { "$ref": "#/$defs/ProblemDetails" },
        {
          "type": "object",
          "required": ["errors"],
          "properties": {
            "errors": {
              "type": "array",
              "minItems": 1,
              "items": {
                "type": "object",
                "required": ["field", "code"],
                "properties": {
                  "field": { "type": "string" },
                  "code": { "type": "string" }
                },
                "additionalProperties": false
              }
            }
          }
        }
      ]
    }
  }
}

The schema document keeps the request, success response, and error profiles under $defs; CI should validate each fixture against the matching reference rather than treating the definitions as one interchangeable shape. Configure the validator to check format values if URI-format checking is part of your contract. Schema validation checks structure and constraints, not pricing, authorization, or database effects.

Add validation and operational failure fixtures

A quantity of zero fails CreateInvoiceRequest. In this API, validation happens before invoice creation, so the provider returns 422 Unprocessable Content and creates no invoice. RFC 9110 defines 422 for content the server understands but whose instructions it cannot process. The error body follows RFC 9457 Problem Details, with API-specific code, requestId, and errors extension members. For shared error-body conventions, see API requests, responses, and error shapes.

This is the invalid request fixture that the provider test submits:

{
  "customerId": "cus_demo_42",
  "currency": "USD",
  "lines": [{ "sku": "desk-lamp", "quantity": 0 }]
}
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.test/problems/invalid-request",
  "title": "Request validation failed",
  "status": 422,
  "code": "invalid_request",
  "requestId": "req_demo_7f3a",
  "errors": [{ "field": "lines[0].quantity", "code": "must_be_positive" }]
}

A separate fixture covers a temporary service failure. RFC 9110 defines 503 for temporary overload or maintenance and allows Retry-After to suggest when the client should try again. This example uses delay-seconds; an HTTP date is also permitted by the Retry-After definition. The value here is an example delay, not a default. A 503 does not make replaying a POST safe; use the API’s idempotency mechanism or check the operation result before retrying an invoice creation.

HTTP/1.1 503 Service Unavailable
Content-Type: application/problem+json
Retry-After: 30

{
  "type": "https://api.example.test/problems/temporarily-unavailable",
  "title": "Invoice service temporarily unavailable",
  "status": 503,
  "code": "temporarily_unavailable",
  "requestId": "req_demo_8b21"
}

Problem Details uses standard members such as type, title, status, detail, and instance. This API profile requires type, title, and status, then adds stable code and diagnostic requestId extensions; the validation profile also requires errors. RFC 9457 says the body’s status, when present, is advisory and the origin server must send that same status in the HTTP response. It also says clients should ignore extension members they do not recognize. For more response conventions, see API requests, responses, and error shapes.

Validate every fixture in CI

Keep the JSON examples as fixtures beside the schema or API contract. Run structural validation for each fixture and add provider tests for behavior a schema cannot prove.

Fixture Schema check Provider behavior to assert
Valid create request Passes CreateInvoiceRequest Returns 201, a Location, and an Invoice body; total matches the test catalog
Created response Passes Invoice status is draft; totalMinor is the expected amount
Request with quantity: 0 Fails CreateInvoiceRequest as expected Returns 422 with ValidationProblem; creates no invoice
Validation response Passes ValidationProblem; body status matches HTTP 422 Field path and stable code identify the quantity constraint
Temporary failure response Passes ProblemDetails; body status matches HTTP 503 Includes Retry-After only when the service can give a useful wait time; no private diagnostics leak

A passing fixture check does not prove every endpoint behavior. Keep integration coverage for authorization, state changes, and dependencies, and test that the schema and examples change with the implementation. The API contracts guide shows how to add consumer/provider compatibility verification to CI.

Document field and error behavior

For each field, state its type, whether it is required, its range or format, and its meaning. Clarify omitted versus null, empty versus absent, and whether unknown properties are rejected or ignored. Match the schema to runtime validation rather than to an idealized contract.

For updates, say what omission and null mean. A PATCH API might interpret omission as “leave unchanged” and null as “clear this value”; that is a service contract choice, not a universal rule. A type declaration alone does not explain it.

Use HTTP status codes for the broad result and stable codes for application-specific branching. Keep human-readable title and detail text useful to a person, but do not ask clients to parse prose. Validation details can identify a field and reason without echoing the submitted value. Never include stack traces, SQL fragments, internal hostnames, or secrets in a problem response.

Do not retry an unchanged invalid request. For temporary failures, follow a documented Retry-After value and the API’s retry rules. A client creating an invoice should use an idempotency key if it may have to replay a request whose outcome is unknown.

Quick recap checklist

  • Validate each example against the schema for its direction and status.
  • Check that HTTP status and Problem Details status agree.
  • Test validation failures before side effects occur.
  • Keep operational errors safe, stable, and clear about retry behavior.
  • Keep examples synthetic and update them when runtime behavior changes.

Interview questions

1. Why validate examples against a schema in CI?
It catches drift between documented fixtures and their declared shape. Provider tests still need to verify runtime behavior such as totals and side effects.
2. What does HTTP 422 mean in this example?
The server understood the request content and its syntax, but could not process the instruction because the quantity violates the API's rule. The test also asserts that no invoice was created.
3. Why does a 503 response not automatically make a POST safe to retry?
The client still needs to know whether the operation took effect. Use an idempotency key or query the operation result before replaying an invoice creation.
4. Which Problem Details fields should clients parse?
Use the documented stable code or extension fields for machine decisions. Treat human-readable text as explanatory, and ignore unrecognized extensions as RFC 9457 specifies.

Further reading

Conclusion

A useful API doc lets a reader trace one payload through its schema, expected response, and CI checks. Keep those fixtures aligned with runtime behavior, and give clients stable error signals they can act on without learning private implementation details.

Category

Related Posts

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.

#api-design #http #error-handling

GraphQL Federation: Subgraphs, Routing, and Trade-offs

Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.

#graphql #federation #microservices

Functions, Modules, and Error Handling

Learn to shape backend functions and modules, handle failures clearly, and build services that are easier to test, operate, and change.

#backend #typescript #code-organization