EMZETT.
Login

OpenAPI and Swagger: Documenting and testing APIs

In short: OpenAPI describes a REST interface machine-readably in YAML or JSON; from it arise documentation, test tools and even ready client code.

In more detail: Whoever offers an API has to say which endpoints exist, which parameters they expect and what they return. The OpenAPI specification (formerly Swagger) defines a standard format for it. Tools such as Swagger UI, Redoc and Postman read it.

In Depth

Example

openapi: 3.0.3
info:
  title: Task API
  version: 1.0.0
paths:
  /tasks:
    get:
      summary: Fetch all tasks
      responses:
        '200':
          description: List
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Task' }
components:
  schemas:
    Task:
      type: object
      required: [id, title]
      properties:
        id: { type: integer }
        title: { type: string }
        done: { type: boolean }

Benefits

  • Interactive documentation: in Swagger UI you can try requests directly.
  • Code generation: client libraries and server skeletons in many languages.
  • Validation of requests and responses.
  • Mock server for frontend development before the backend.
  • Contracts: frontend and backend agree on a specification (contract first).
  • Tests that check whether the API matches the description.

Two ways

Contract first: write the specification first, then implement. Code first: the specification is generated from annotations or types in the code (for example FastAPI, Spring, NestJS). Important is that description and code do not drift apart: check in the build that the specification is current.

Good practice

Describe error responses (400, 401, 404, 500) and their format, give examples, use reusable schemas, document authentication (bearer, API key, OAuth) and versioning. Do not publish internal endpoints or example data with real personal data.

See also: REST API design, API versioning, File formats (YAML, JSON etc.), README file