REST API – API Documentation with OpenAPI and Swagger

Every API needs a manual. Without one, developers who use your API spend hours guessing what endpoints exist, what data to send, and what to expect back. OpenAPI and Swagger solve this problem by giving you a standard way to describe and publish that manual automatically.

What Is API Documentation?

API documentation is a written description of every part of your API — its endpoints, request formats, response formats, error codes, and authentication rules. Good documentation lets a developer start using your API without asking you a single question.

Think of it like a restaurant menu. The menu lists every dish (endpoint), its ingredients (request parameters), its price (required headers or tokens), and what you get on the plate (response). Without the menu, customers cannot order confidently.

The Problem with Writing Docs Manually

Many teams write API docs in Word files or wikis. This creates a painful cycle:

  • Developer changes an endpoint.
  • Forgets to update the Word file.
  • Other developers read old docs and write broken code.

Manual docs go stale fast. The API changes but the document stays the same.

What Is OpenAPI?

OpenAPI is a specification — a set of rules for describing a REST API in a structured file. You write one YAML or JSON file that describes your entire API. Tools then read that file to generate documentation, test pages, client libraries, and server stubs automatically.

Think of OpenAPI as a blueprint for a building. The blueprint is one authoritative document. Architects, plumbers, and electricians all read the same blueprint. Nobody works from a photocopy that might be outdated.

OpenAPI File — Simple Mental Model

┌─────────────────────────────────────────────┐
│            openapi.yaml                     │
│                                             │
│  info:                                      │
│    title: "Student API"                     │
│    version: "1.0"                           │
│                                             │
│  paths:                                     │
│    /students:          ← URL endpoint       │
│      get:              ← HTTP method        │
│        summary: "Get all students"          │
│        responses:                           │
│          200:          ← success code       │
│            description: "List of students"  │
└─────────────────────────────────────────────┘

That single file is the source of truth for your entire API.

What Is Swagger?

Swagger started as the original name of the OpenAPI Specification. In 2016, the project was donated to the Linux Foundation and renamed "OpenAPI." The Swagger name now refers to a set of tools built around the OpenAPI Specification.

The most popular Swagger tools are:

  • Swagger Editor — A browser-based editor where you write your OpenAPI file and see a live preview of your documentation.
  • Swagger UI — A web interface that turns your OpenAPI file into a beautiful, interactive documentation page. Developers can read the docs and test API calls right from the browser.
  • Swagger Codegen — A tool that reads your OpenAPI file and generates client SDKs (in Python, Java, JavaScript, and more) automatically.

OpenAPI vs Swagger — Quick Comparison

┌──────────────────┬─────────────────────────────────────┐
│   Term           │   What It Means                     │
├──────────────────┼─────────────────────────────────────┤
│ OpenAPI          │ The specification (the standard)    │
│ Swagger UI       │ Tool to display OpenAPI as HTML     │
│ Swagger Editor   │ Tool to write OpenAPI files         │
│ Swagger Codegen  │ Tool to generate code from OpenAPI  │
└──────────────────┴─────────────────────────────────────┘

Anatomy of an OpenAPI File

An OpenAPI file has five main sections. Each section describes a different aspect of your API.

Section 1 — Info

This section describes the API itself: its name, version, and a short description.

openapi: "3.0.3"
info:
  title: "Library API"
  description: "Manage books and members"
  version: "2.1.0"

Section 2 — Servers

This section lists the base URLs where your API lives — development, staging, and production.

servers:
  - url: "https://api.library.com/v2"
    description: "Production"
  - url: "https://dev.library.com/v2"
    description: "Development"

Section 3 — Paths

This is the biggest section. It lists every endpoint, every HTTP method, every parameter, and every possible response.

paths:
  /books/{id}:
    get:
      summary: "Get a book by ID"
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: "Book found"
        "404":
          description: "Book not found"

Section 4 — Components

This section holds reusable pieces — data schemas, error formats, and security definitions — so you define them once and reference them many times.

components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: integer
        title:
          type: string
        author:
          type: string

Section 5 — Security

This section describes how clients authenticate with your API — API keys, OAuth tokens, or HTTP Basic auth.

security:
  - ApiKeyAuth: []

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

How Swagger UI Works — Step by Step

Here is what happens when you deploy Swagger UI for your API:

Developer visits docs URL
        │
        ▼
Swagger UI loads your openapi.yaml file
        │
        ▼
Renders an HTML page with all endpoints listed
        │
        ▼
Developer clicks "Try it out" on any endpoint
        │
        ▼
Fills in parameters directly in the browser
        │
        ▼
Swagger UI sends a real HTTP request to your API
        │
        ▼
Displays the actual response below the form

Developers test your API without writing a single line of code or opening a terminal.

Writing Your First OpenAPI File

Below is a complete, minimal OpenAPI file for a simple "Todo" API. Study each part carefully.

openapi: "3.0.3"

info:
  title: "Todo API"
  version: "1.0.0"
  description: "A simple API to manage your daily tasks"

servers:
  - url: "https://api.todos.com/v1"

paths:

  /todos:
    get:
      summary: "List all todos"
      responses:
        "200":
          description: "An array of todos"
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Todo"

    post:
      summary: "Create a new todo"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/NewTodo"
      responses:
        "201":
          description: "Todo created"

  /todos/{id}:
    delete:
      summary: "Delete a todo"
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "204":
          description: "Todo deleted"
        "404":
          description: "Todo not found"

components:
  schemas:
    Todo:
      type: object
      properties:
        id:
          type: integer
        title:
          type: string
        done:
          type: boolean

    NewTodo:
      type: object
      required:
        - title
      properties:
        title:
          type: string

Data Types in OpenAPI Schemas

OpenAPI supports a fixed set of data types for describing request and response fields.

┌────────────────┬──────────────┬──────────────────────────┐
│  OpenAPI Type  │  Format      │  Example Value           │
├────────────────┼──────────────┼──────────────────────────┤
│ integer        │ int32/int64  │ 42                       │
│ number         │ float/double │ 3.14                     │
│ string         │ —            │ "hello"                  │
│ string         │ date         │ "2024-06-01"             │
│ string         │ date-time    │ "2024-06-01T10:00:00Z"   │
│ boolean        │ —            │ true / false             │
│ array          │ —            │ [1, 2, 3]                │
│ object         │ —            │ { "key": "value" }       │
└────────────────┴──────────────┴──────────────────────────┘

Describing Request Bodies

When a client sends data to your API (POST or PUT), you describe that data inside requestBody.

POST /orders

Request body expected by API:
┌───────────────────────────────────┐
│  {                                │
│    "product_id": 101,             │  ← integer, required
│    "quantity": 3,                 │  ← integer, required
│    "note": "Gift wrap please"     │  ← string, optional
│  }                                │
└───────────────────────────────────┘

OpenAPI description:
requestBody:
  required: true
  content:
    application/json:
      schema:
        type: object
        required:
          - product_id
          - quantity
        properties:
          product_id:
            type: integer
          quantity:
            type: integer
          note:
            type: string

Describing Response Bodies

Every status code your API can return needs a responses entry. This helps developers understand both success and error cases.

API Response Map for GET /orders/{id}

   Status 200 ──→ Returns Order object
   Status 401 ──→ "Unauthorized — missing API key"
   Status 403 ──→ "Forbidden — no permission"
   Status 404 ──→ "Order not found"
   Status 500 ──→ "Server error"

Each mapped in OpenAPI:
responses:
  "200":
    description: "Order found"
    content:
      application/json:
        schema:
          $ref: "#/components/schemas/Order"
  "404":
    description: "Order not found"
    content:
      application/json:
        schema:
          $ref: "#/components/schemas/Error"

Adding Examples to Your Docs

OpenAPI lets you embed example request and response payloads directly in your documentation. Developers see exactly what real data looks like.

/products/{id}:
  get:
    responses:
      "200":
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Product"
            example:
              id: 55
              name: "Wireless Keyboard"
              price: 1299
              in_stock: true

That example block appears in Swagger UI and instantly shows developers the shape of your real data.

Documenting Authentication

API Key Authentication

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header         ← key goes in request header
      name: X-API-Key    ← header name

security:
  - ApiKeyAuth: []       ← applies to ALL endpoints

Bearer Token (JWT) Authentication

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - BearerAuth: []

Override Security for a Specific Endpoint

paths:
  /public/status:
    get:
      summary: "Health check — no auth needed"
      security: []     ← empty array removes auth requirement

Versioning Your OpenAPI File

When your API changes, update the version field in info and keep old versions of your YAML file archived. Serve them at versioned URLs so old client apps still find their matching documentation.

Version strategy for documentation files:

docs/
├── v1/
│   └── openapi.yaml      ← stable, no changes
├── v2/
│   └── openapi.yaml      ← current active version
└── v3/
    └── openapi.yaml      ← beta / next version

Tools That Read OpenAPI Files

Your openapi.yaml
        │
        ├──→ Swagger UI        → Interactive HTML docs
        │
        ├──→ Redoc             → Beautiful static docs
        │
        ├──→ Postman           → Import and auto-create test collection
        │
        ├──→ OpenAPI Generator → Generate SDK in 40+ languages
        │
        └──→ Prism             → Mock server (no real backend needed)

Hosting Your Swagger UI

You can serve Swagger UI in three common ways:

Option 1 — Embed in Your API Server

Most frameworks have a plugin that auto-generates and serves Swagger UI at a path like /docs or /api-docs. Examples: Springdoc for Java Spring Boot, FastAPI for Python, NestJS Swagger for Node.js.

Option 2 — Static File Hosting

Download the Swagger UI HTML bundle, add your openapi.yaml file next to it, and host both as static files on any web server or CDN.

Option 3 — SwaggerHub

SwaggerHub is a hosted platform by SmartBear where teams collaborate on OpenAPI files, manage versions, and publish docs without any server setup.

Common Mistakes in API Documentation

❌ MISTAKE                      ✅ CORRECT APPROACH
────────────────────────────────────────────────────
Skip optional fields            Document all fields,
in schema                       mark as required/optional

No examples in docs             Add at least one example
                                per response type

Document only happy path        Document all error codes
                                (401, 403, 404, 422, 500)

One giant openapi.yaml          Split into multiple files,
file (thousands of lines)       reference with $ref

Never update the docs           Treat docs as code —
after API changes               update them in same PR

Key Points

  • OpenAPI is the standard specification format for describing REST APIs in YAML or JSON.
  • Swagger is a set of tools — Editor, UI, and Codegen — built around the OpenAPI Specification.
  • An OpenAPI file has five main sections: info, servers, paths, components, and security.
  • Swagger UI turns your OpenAPI file into an interactive HTML page where developers can test calls live.
  • Always document every response code — not just 200. Developers need to know how your API fails.
  • Add example values to every schema so developers see real-looking data, not abstract field names.
  • Treat your OpenAPI file like source code — version it, review it in PRs, and never let it go stale.

Leave a Comment