LearnFrenzy
Sign in Take a free test

Documentation and Testing · Lesson 26 of 30

OpenAPI and Swagger: Documenting REST APIs

4 min read Updated Nov 8, 2026 Saurabh Samir

An API without documentation is an API nobody can use. OpenAPI (formerly Swagger) is the standard, machine-readable way to describe a REST API: every path, parameter, request body, response, schema and security scheme in one YAML or JSON file. From that single file you get interactive docs, generated client libraries, mock servers, request validation and contract tests.

In this lesson

  • The structure of an OpenAPI document
  • A complete spec for an endpoint
  • Serving the spec and Swagger UI
  • Design-first vs code-first

The structure

openapi.yaml

  • openapi – the spec version (3.1.0)
  • info – title, version, description, contact
  • servers – base URLs (production, staging)
  • paths – each URL and its operations (get, post…)
  • components
    • schemas – reusable data models (Task, Problem)
    • securitySchemes – bearer JWT, API keys, OAuth 2.0
    • parameters, responses – reusable pieces
  • security – which scheme applies by default

A complete example

openapi: 3.1.0
info:
  title: Tasks API
  version: 1.2.0
  description: Manage tasks for LearnFrenzy study plans.
servers:
  - url: https://api.learnfrenzy.com/v1
paths:
  /tasks:
    get:
      summary: List tasks
      operationId: listTasks
      parameters:
        - name: done
          in: query
          schema: { type: boolean }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
      responses:
        '200':
          description: A page of tasks
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Task' } }
                  nextCursor: { type: [string, 'null'] }
    post:
      summary: Create a task
      operationId: createTask
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NewTask' }
      responses:
        '201':
          description: Created
          headers:
            Location: { schema: { type: string }, description: URL of the new task }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Task' }
        '422':
          description: Validation failed
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
components:
  schemas:
    NewTask:
      type: object
      required: [title]
      properties:
        title: { type: string, minLength: 3, maxLength: 120, example: Write API docs }
        dueDate: { type: string, format: date }
    Task:
      allOf:
        - $ref: '#/components/schemas/NewTask'
        - type: object
          required: [id, done]
          properties:
            id: { type: integer, example: 7 }
            done: { type: boolean }
    Problem:
      type: object
      properties:
        type: { type: string, format: uri }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
  securitySchemes:
    bearerAuth: { type: http, scheme: bearer, bearerFormat: JWT }
security:
  - bearerAuth: []
  • Schemas use JSON Schema (fully compatible in OpenAPI 3.1), so the same rules can validate requests.
  • $ref reuses definitions – one Task model used everywhere.
  • Document every response, including errors and headers like Location; that's what client developers need most.
  • operationId becomes the method name in generated clients (api.createTask()).

Serving the spec

// server.js
import express from 'express';

const app = express();

// In a real project: load openapi.yaml with a YAML parser, or generate the spec from your zod schemas.
const spec = {
  openapi: '3.1.0',
  info: { title: 'Tasks API', version: '1.2.0' },
  paths: { '/tasks': { get: { operationId: 'listTasks' }, post: { operationId: 'createTask' } } },
};

app.get('/openapi.json', (req, res) => res.json(spec));     // tools and Swagger UI read this URL

app.listen(process.env.PORT ?? 3000);

Real response

$ curl http://localhost:3000/openapi.json
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  "openapi": "3.1.0",
  "info": {
    "title": "Tasks API",
    "version": "1.2.0"
  },
  "paths": {
    "/tasks": {
      "get": {
        "operationId": "listTasks"
      },
      "post": {
        "operationId": "createTask"
      }
    }
  }
}

Point Swagger UI, Redoc or Scalar at that URL (Express has swagger-ui-express; frameworks like FastAPI, NestJS and Spring generate it for you) to get interactive docs where developers can try every endpoint. Postman and Insomnia import it as a collection; generators such as openapi-generator build typed clients in dozens of languages.

Design-first or code-first?

Design-firstCode-first
Processwrite and review the spec, then implement itwrite code, generate the spec from annotations or schemas
Strengthfrontend and backend work in parallel from the contract; API review happens earlydocs never drift from the code
ToolsStoplight, Swagger Editor, spec linting (Spectral), mock servers (Prism)zod-to-openapi, NestJS, FastAPI, springdoc

Keep the spec honest

Whichever way you work, run contract tests in CI that check real responses against the spec, and lint the spec (consistent naming, every operation has errors documented). Outdated docs are worse than none.

Practice

Try it yourself

  1. Add DELETE /tasks/{id} to the spec with a path parameter and 204 and 404 responses.

    Show solution
      /tasks/{id}:
        delete:
          summary: Delete a task
          operationId: deleteTask
          parameters:
            - name: id
              in: path
              required: true
              schema: { type: integer }
          responses:
            '204': { description: Deleted }
            '404':
              description: No task with this id
              content:
                application/problem+json:
                  schema: { $ref: '#/components/schemas/Problem' }

Quick check

What's the difference between OpenAPI and Swagger?

OpenAPI is the specification; Swagger is the original name and a family of tools (Swagger UI, Editor) for it.

What does $ref do?

References a reusable definition, such as a schema in components.

What can you generate from an OpenAPI file?

Interactive docs, client SDKs, server stubs, mock servers and tests.

Summary

  • OpenAPI describes paths, parameters, bodies, responses, schemas and security in one file.
  • Serve it for Swagger UI and tools; generate clients, mocks and tests from it.
  • Choose design-first or code-first, and verify the spec against reality in CI.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links