OpenAPI#

OpenAPI (formerly Swagger) is a description language for HTTP APIs. The spec is a YAML or JSON document that describes endpoints, request and response schemas, authentication, errors, and examples.

The payoff: a single source of truth from which you generate clients, servers, mocks, tests, and human-readable docs.

The Spec File#

openapi: 3.1.0
info:
  title: Books API
  version: 1.0.0
servers:
  - url: https://api.example.com

paths:
  /books:
    get:
      summary: List books
      parameters:
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
      responses:
        '200':
          description: list of books
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Book' }

    post:
      summary: Create a book
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BookInput' }
      responses:
        '201':
          description: created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Book' }

components:
  schemas:
    Book:
      type: object
      required: [id, title, author]
      properties:
        id:     { type: string, format: uuid }
        title:  { type: string }
        author: { type: string }
        year:   { type: integer }
    BookInput:
      type: object
      required: [title, author]
      properties:
        title:  { type: string }
        author: { type: string }
        year:   { type: integer }

The Building Blocks#

A spec composes a small set of top-level objects: paths name URLs, components hold reusable schemas and parameters, security schemes describe authentication. The list below is the parts inventory; nearly every spec is some arrangement of these.

  • paths, the URL routes; each maps to operations (get / post / put / delete / patch).

  • components/schemas, reusable type definitions ($ref: '#/components/schemas/X').

  • components/parameters, reusable query / path / header parameters.

  • components/responses, reusable response definitions.

  • components/securitySchemes, auth schemes.

  • security, top-level required schemes per operation.

  • tags, group operations for docs.

Versions#

The OpenAPI specification has shipped three major versions worth knowing about. Swagger 2.0 still lingers in legacy APIs; 3.0 brought modern JSON Schema alignment; 3.1 is the recommended target in 2026, with full JSON Schema 2020-12 support and webhook descriptions.

  • Swagger 2.0 (2014), still common in legacy APIs.

  • OpenAPI 3.0 (2017), modern, JSON Schema-aligned, request bodies.

  • OpenAPI 3.1 (2021), full JSON Schema 2020-12 alignment; webhooks and $schema references; the recommended target.

Schemas (JSON Schema)#

OpenAPI’s type system is JSON Schema with minor historical divergences, closed entirely in 3.1. The constructs below cover most everyday API schemas: primitive types with formats, required-properties objects, length and pattern constraints, enums, and union types via oneOf / anyOf / allOf.

The core constructs.

  • type, string, number, integer, boolean, object, array, null.

  • format, e.g. date-time, email, uuid, uri.

  • required / properties / additionalProperties.

  • minimum / maximum / minLength / maxLength / pattern.

  • enum for closed sets.

  • oneOf / anyOf / allOf for unions / intersections.

  • discriminator to make polymorphism explicit.

Authentication#

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
    oauth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/authorize
          tokenUrl: https://auth.example.com/token
          scopes:
            read: read access
            write: write access

security:
  - bearerAuth: []

Tooling#

The ecosystem around an OpenAPI spec is broad. Editors and doc renderers, codegen for clients and servers, mock servers, linters, and middleware that validates requests and responses at runtime; one spec drives all of them. The list below is a tour of the standard choices.

Workflows#

Spec-first, write the spec, then implement to it. Generate the client and server scaffolding. The spec stays authoritative.

Code-first, annotate handlers in code; tools generate the spec. Common in Go (swag), Java (springdoc), TypeScript (zod-to-openapi), .NET (Swashbuckle). The risk: the spec drifts when developers forget to annotate.

Pick one and stick to it; switching is painful.

Extensions#

OpenAPI supports vendor extensions via x- prefixed fields:

paths:
  /books:
    get:
      x-rate-limit: 100/min
      x-internal: true

Used by API gateways (AWS API Gateway, Kong, Tyk), AsyncAPI bridges, codegen options.

Validation and Testing#

  • Request / response validation middleware, many frameworks (Fastify, NestJS, Express, FastAPI, ASP.NET) validate against the spec at runtime.

  • Contract tests, tools like Dredd or Schemathesis fuzz the spec against the running server to find inconsistencies.

  • Schema diff, tools detect breaking changes between spec versions.

AsyncAPI, the Adjacent Spec#

AsyncAPI is OpenAPI’s sibling for event-driven systems: Kafka topics, AMQP queues, MQTT channels, WebSockets. Same structure, different domain.

GraphQL Schema (SDL), a Cousin#

GraphQL ships its own description language (Schema Definition Language) that fills the same role for GraphQL APIs that OpenAPI fills for REST. For pure-REST shops, OpenAPI; for GraphQL, SDL.

When (Not) to Use OpenAPI#

  • Use for any HTTP API with multiple consumers, internal or external. The codegen alone pays back the spec maintenance.

  • Use when partners want predictable contracts.

  • Don’t use as the only documentation, humans need English; OpenAPI gives them tables.

  • Don’t use for tightly internal RPC, gRPC / Connect / tRPC offer better ergonomics for that case.

Pitfalls#

The traps that catch teams running OpenAPI in production. Spec-versus-implementation drift is the biggest; the spec claims one structure, the API does another. Massive single-file specs become unreviewable; mock-only workflows skip integration; and 3.0/3.1 differences trip up tooling.

  • Spec drift, the spec lies; the implementation does something else. Validate both directions.

  • Massive specs, bundle into multiple files via $ref.

  • Mock-first development without integration tests yields client / server divergence.

  • OpenAPI 3.0 vs. 3.1 differences in JSON Schema, 3.1 is stricter. Most tooling supports both; pin a version.