OpenAPI & Swagger Guide

Document your REST API with the industry-standard OpenAPI Specification

Last updated:

What is OpenAPI?

OpenAPI (formerly Swagger) is the industry-standard specification for describing REST APIs in a machine-readable format. It lets you define your entire API โ€” endpoints, parameters, request bodies, responses, authentication โ€” in a single YAML or JSON file.

๐Ÿ“„

Single Source of Truth

Your OpenAPI spec is the authoritative definition of your API contract. Teams, tools, and clients all work from the same document.

๐Ÿ–ฅ๏ธ

Interactive Documentation

Tools like Swagger UI and Redoc auto-generate beautiful, interactive documentation from your spec โ€” developers can try API calls right from the browser.

โš™๏ธ

Code Generation

Generate client SDKs in 40+ languages, server stubs, and mock servers directly from your OpenAPI spec.

๐Ÿงช

Automated Testing

Tools like Dredd, Schemathesis, and Spectral validate your API implementation against the spec automatically.

OpenAPI vs Swagger: What's the Difference?

TermWhat It Is
OpenAPI Specification (OAS)The open standard for describing REST APIs. Maintained by the OpenAPI Initiative.
SwaggerThe original name (pre-2016). Now refers to the toolset: Swagger UI, Swagger Editor, Swagger Codegen.
OpenAPI 3.1Current version (2021). Full JSON Schema alignment, webhook support.
OpenAPI 3.0Most widely adopted version. Still excellent choice for new projects.
OpenAPI 2.0 (Swagger 2)Legacy. Still used in older APIs but migrate if possible.

OpenAPI Spec Structure

An OpenAPI document has several top-level sections. Here's the anatomy of an OpenAPI 3.1 spec in YAML:

Minimal OpenAPI 3.1 Spec

openapi: 3.1.0
info:
  title: Users API
  version: 1.0.0
  description: Manage user accounts
  contact:
    name: API Support
    email: api@example.com

servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging

paths:
  /users:
    get:
      summary: List all users
      operationId: listUsers
      tags: [Users]
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
        '401':
          $ref: '#/components/responses/Unauthorized'

    post:
      summary: Create a user
      operationId: createUser
      tags: [Users]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          example: 123
        name:
          type: string
          example: Jane Doe
        email:
          type: string
          format: email
          example: jane@example.com
        created_at:
          type: string
          format: date-time

    CreateUserRequest:
      type: object
      required: [name, email, password]
      properties:
        name:
          type: string
          minLength: 1
        email:
          type: string
          format: email
        password:
          type: string
          minLength: 8

    UserList:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/User'
        pagination:
          $ref: '#/components/schemas/Pagination'

    Pagination:
      type: object
      properties:
        total:
          type: integer
        page:
          type: integer
        limit:
          type: integer

  responses:
    Unauthorized:
      description: Authentication required
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
                example: Unauthorized

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

security:
  - BearerAuth: []

Defining Endpoints

Each endpoint in your API is defined under paths. Here are the key components:

Path Parameters

in: pathRequired variable in the URL path, e.g. /users/{id}
in: queryOptional URL query parameter, e.g. ?page=2&limit=10
in: headerCustom request header, e.g. X-API-Key
in: cookieCookie-based parameter

Response Codes

200Successful GET, PUT, PATCH
201Successful POST (resource created)
204Successful DELETE (no body)
400Validation error
401Unauthenticated
404Resource not found

Authentication in OpenAPI

Bearer Token (JWT)

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

# Apply globally
security:
  - BearerAuth: []

# Or per-endpoint
paths:
  /users:
    get:
      security:
        - BearerAuth: []

API Key

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

security:
  - ApiKeyAuth: []

OAuth 2.0

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/oauth/authorize
          tokenUrl: https://auth.example.com/oauth/token
          scopes:
            read:users: Read user profiles
            write:users: Create and update users

Tools: Swagger UI, Redoc & More

๐Ÿ”ต Swagger UI

The most popular OpenAPI visualiser. Renders interactive docs where developers can make real API calls. Self-hostable via Docker or npm.

docker run -p 8080:8080 \
  -e SWAGGER_JSON=/api/openapi.yaml \
  -v $(pwd):/api \
  swaggerapi/swagger-ui

๐Ÿ“˜ Redoc

Clean, responsive three-panel documentation. Excellent for public API docs. Supports OpenAPI 3.0 and 3.1.

<!-- Single HTML file docs -->
<redoc spec-url="openapi.yaml"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"></script>

โœ๏ธ Swagger Editor

Browser-based YAML/JSON editor with real-time validation and preview. Available at editor.swagger.io.

๐Ÿ” Spectral

Linter for OpenAPI specs. Enforces style rules, catches mistakes, and validates your spec before deployment.

npx @stoplight/spectral-cli lint openapi.yaml

Generate Docs from Code

Instead of writing the spec by hand, most frameworks let you auto-generate it from code annotations.

Node.js + Express (swagger-jsdoc)

npm install swagger-jsdoc swagger-ui-express

// app.js
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const options = {
  definition: {
    openapi: '3.1.0',
    info: { title: 'Users API', version: '1.0.0' },
  },
  apis: ['./routes/*.js'],
};

const spec = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(spec));

// routes/users.js
/**
 * @openapi
 * /users:
 *   get:
 *     summary: List all users
 *     responses:
 *       200:
 *         description: OK
 */
router.get('/users', listUsers);

Python + FastAPI (built-in)

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Users API", version="1.0.0")

class User(BaseModel):
    id: int
    name: str
    email: str

@app.get("/users", response_model=list[User])
async def list_users():
    """List all users"""
    return []

# Docs auto-available at:
# /docs  โ†’ Swagger UI
# /redoc โ†’ Redoc

Frequently Asked Questions

What is the difference between OpenAPI and Swagger?

Swagger was the original name for the specification. In 2016 it was renamed OpenAPI. Today, OpenAPI is the specification standard, and Swagger refers to the tooling ecosystem (Swagger UI, Swagger Editor, Swagger Codegen).

Which OpenAPI version should I use?

Use OpenAPI 3.1 for new projects โ€” it has full JSON Schema alignment and webhook support. OpenAPI 3.0 is fine if your tooling doesn't support 3.1 yet. Avoid OpenAPI 2.0 (Swagger 2) for new projects.

Do I need OpenAPI for my REST API?

It's not required, but strongly recommended. You get free interactive documentation, client SDK generation, automated contract testing, and a shared API contract for frontend/backend teams โ€” all from one YAML file.

Can I generate an OpenAPI spec from existing code?

Yes โ€” use springdoc-openapi (Java/Spring), FastAPI's built-in support (Python), swagger-jsdoc (Node.js/Express), or drf-spectacular (Django REST Framework).