HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
3 Topics
Chapter•150 Minutes

Validation, Schemas and API Contracts

Learn input validation, schema-driven APIs, contract boundaries, and defensive parsing.

Validate Every Trust Boundary

Input Validation

Everything received from an HTTP client should be treated as untrusted input. Validate path parameters, query parameters, headers, cookies, and request bodies.

Validation should check type, format, length, allowed values, ranges, relationships between fields, and business rules where appropriate.

Validation is not only a security feature. It protects the application from malformed data and makes API behavior predictable.

Schema Validation Concept
const userSchema = {
  name: { type: 'string', minLength: 1, maxLength: 100 },
  email: { type: 'email' },
  age: { type: 'integer', minimum: 18 }
};
💡 The schema defines constraints before application logic receives the input.

Request and Response Contracts

API Contracts

A contract describes what clients may send and what the server promises to return.

A mature API contract documents required fields, optional fields, nullable fields, formats, enum values, status codes, headers, authentication requirements, and error responses.

Schema validation tools can validate requests and responses automatically. This is particularly valuable in large teams where frontend and backend evolve independently.

Key Takeaways
  • Contracts define expectations between producers and consumers.
  • Request validation protects the server.
  • Response validation can detect accidental breaking changes.

OpenAPI as an Executable Contract

OpenAPI describes HTTP APIs using a machine-readable document. It can describe paths, operations, parameters, request bodies, responses, schemas, authentication schemes, and examples.

The specification can power documentation, client generation, server stubs, validation, testing, and API governance.

For teams, OpenAPI can become the central contract from which frontend clients and automated tests are generated.

OpenAPI Endpoint Fragment
paths:
  /users/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: User returned
        '404':
          description: User not found
💡 OpenAPI describes the endpoint contract independently from the server implementation.