Frontend Patterns

Pattern

API Schema

Define and enforce contracts for API request and response structures.

API Schema

Problem

Backend changes silently break frontend code because there’s no contract enforcement. Runtime errors appear in production when API fields are renamed, types change, or required fields become optional. Mock data and tests use different shapes than actual API responses, making bugs hard to catch until production deployment.

Solution

Define API contracts using schema languages like OpenAPI or JSON Schema that can validate responses at runtime and generate types at build time. This catches breaking changes immediately through failed validation and provides type safety across your entire data flow.

Example

This example shows how to define an API endpoint contract using OpenAPI specification, which documents expected request/response structures and enables validation and type generation.

# openapi.yaml - API contract definition
paths:
  /users/{id}:
    get:
      responses:
        200:
          content:
            application/json:
              # Define the response schema structure
              schema:
                type: object
                required: [id, email]  # These fields must be present
                properties:
                  id: { type: integer }    # User ID as a number
                  email: { type: string }  # Email address as a string

Benefits

  • Catches breaking API changes immediately through runtime validation failures.
  • Generates TypeScript types automatically from the source of truth.
  • Provides a single contract that frontend, backend, and tests share.
  • Enables automatic API documentation generation from the schema.
  • Reduces runtime errors caused by unexpected API response shapes.

Tradeoffs

  • Requires coordination between frontend and backend teams on schema updates.
  • Adds complexity with schema files that must be maintained alongside code.
  • Runtime validation adds overhead to every API request.
  • Learning curve for schema languages like OpenAPI or JSON Schema.
  • Can slow down rapid prototyping when contracts are strictly enforced.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.