OpenAPI & Swagger for REST API Documentation

The OpenAPI Specification (OAS) defines how to describe HTTP APIs. Swagger UI uses that description to display interactive REST API documentation.

Last updated:

What is OpenAPI?

An OpenAPI document describes endpoints, parameters, request bodies, responses, and authentication in YAML or JSON. Swagger Editor lets you edit and preview that document.

๐Ÿ“„

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 Is the Difference?

TermWhat It Is
OpenAPI Specification (OAS)The OpenAPI Initiative maintains this open standard for HTTP APIs.
SwaggerThe name of the original specification. Swagger also names tools such as Swagger UI, Swagger Editor, and Swagger Codegen.
OpenAPI 3.2.1The latest specification release. The OpenAPI Initiative published OpenAPI 3.2.1 on .
OpenAPI 3.1This release series added JSON Schema 2020-12 compatibility and a top-level field for webhooks. The Users API example uses 3.1.0.
OpenAPI 3.0An earlier release series with a different Schema Object.
Swagger 2.0 (OpenAPI 2.0)The legacy Swagger 2.0 specification.

OpenAPI 3.1.0 YAML Example for Swagger

This Users API document declares the specification version in openapi and the API version in info.version.

  1. Copy the YAML below into Swagger Editor 5.
  2. In the preview, expand GET /users.
  3. Expand the schema for the 200 response to see the fields in UserList.

The example uses placeholder server URLs. The preview displays documentation without a live API.

Users API

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

The paths section defines the endpoints in your API. The HTTP methods guide explains when to use GET, POST, PUT, PATCH, and DELETE.

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

Swagger UI displays interactive documentation from an OpenAPI document. Swagger UI 5.32.0 lists support for OpenAPI 3.1.0 and 3.2.0.

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

Swagger Editor 5 supports OpenAPI 3.1.0. It validates YAML and JSON and displays a preview in the browser.

๐Ÿ” 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, OpenAPI 3.1.0)

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

OpenAPI 3.1 vs 3.0: Key Differences

OpenAPI 3.1 added support for JSON Schema 2020-12 and top-level webhooks. This comparison explains the differences between the 3.0 and 3.1 release series.

Feature OpenAPI 3.0 OpenAPI 3.1
JSON Schema alignment Subset of JSON Schema (diverges on several keywords) โœ… Full JSON Schema 2020-12 compatibility
Nullable fields nullable: true (non-standard) type: [string, "null"] (standard)
Webhooks Not supported natively โœ… webhooks top-level field
exclusive min/max exclusiveMinimum: true (boolean) exclusiveMinimum: 5 (number โ€” more intuitive)
$schema keyword Not supported โœ… Supported โ€” declares JSON Schema dialect
License identifier URL only โœ… SPDX identifier (e.g. MIT, Apache-2.0)

Nullable in 3.0 vs 3.1

# OpenAPI 3.0 โ€” nullable uses a custom keyword
components:
  schemas:
    User:
      properties:
        middle_name:
          type: string
          nullable: true
# OpenAPI 3.1 โ€” uses standard JSON Schema type array
components:
  schemas:
    User:
      properties:
        middle_name:
          type: [string, "null"]  # Standard JSON Schema

Webhook definition in OpenAPI 3.1.0

openapi: 3.1.0
info:
  title: My API
  version: 1.0.0
webhooks:
  orderCreated:
    post:
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Order'
      responses:
        '200':
          description: Webhook received successfully
components:
  schemas:
    Order:
      type: object
      properties:
        id:
          type: integer
      required: [id]

OpenAPI Tooling Ecosystem

Beyond Swagger UI and Redoc, a rich ecosystem of tools can validate, lint, generate code from, and publish your OpenAPI spec.

โšก Scalar

Modern, beautiful API documentation UI. Open source, fast, and supports OpenAPI 3.1. A popular Redoc alternative with a cleaner design.

npx @scalar/api-reference --input openapi.yaml

๐Ÿ—๏ธ openapi-generator

Generate client SDKs and server stubs in 50+ languages from your spec. Java, Python, TypeScript, Go, Kotlin, Rust, and more.

npx @openapitools/openapi-generator-cli generate \
  -i openapi.yaml \
  -g typescript-axios \
  -o ./src/client

๐Ÿ” Spectral

Linter for OpenAPI specs. Catches common mistakes, enforces style rules, and integrates with CI to prevent bad specs from shipping.

npx @stoplight/spectral-cli lint openapi.yaml --ruleset spectral:oas

๐Ÿงช Prism

Mock server that reads your OpenAPI spec and returns realistic example responses. Great for frontend development before the API is ready.

npx @stoplight/prism-cli mock openapi.yaml

See our API Documentation guide for more on docs tooling, and API Testing for how to use your OpenAPI spec in automated tests. API Versioning covers how to manage breaking changes across spec versions.

Frequently Asked Questions

What is the difference between OpenAPI and Swagger?

The OpenAPI Specification (OAS) defines how to describe HTTP APIs. Swagger was the name of the original specification. Today, Swagger also names tools such as Swagger UI and Swagger Editor.

What is the latest OpenAPI version, and which version should I use?

OpenAPI 3.2.1 is the latest specification release. The OpenAPI Initiative published it on September 10, 2026. Use a version that your editor, validator, documentation tool, and code generator support.

Do I need OpenAPI for my REST API?

It is 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).