OpenAPI & Swagger Guide
Document your REST API with the industry-standard OpenAPI Specification
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 Is the Difference?
| Term | What It Is |
|---|---|
| OpenAPI Specification (OAS) | The open standard for describing REST APIs. Maintained by the OpenAPI Initiative. |
| Swagger | The original name (pre-2016). Now refers to the toolset: Swagger UI, Swagger Editor, Swagger Codegen. |
| OpenAPI 3.1 | Current version (2021). Full JSON Schema alignment, webhook support. |
| OpenAPI 3.0 | Most 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. This is 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
/users/{id}?page=2&limit=10X-API-KeyResponse Codes
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
OpenAPI 3.1 vs 3.0: Key Differences
OpenAPI 3.1 (released February 2021) is the current standard. If you start a new API, use 3.1. This is what changed and why it matters.
| 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) |
| Tooling support | Universal | Good and growing (Redoc, Scalar, Spectral all support 3.1) |
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 # Non-standard extension
# OpenAPI 3.1 โ uses standard JSON Schema type array
components:
schemas:
User:
properties:
middle_name:
type: [string, null] # Standard JSON SchemaWebhook definition in 3.1
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 successfullyOpenAPI 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?
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 does not support 3.1 yet. Avoid OpenAPI 2.0 (Swagger 2) for new projects.
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).
Related Guides
๐ REST API Design Guide
Complete guide to URL design, versioning, and API architecture.
๐ Authentication
OAuth 2.0, JWT, and API key patterns for securing your API.
๐งช API Testing
Test your documented API with Postman, Jest, and contract tests.
๐ก๏ธ Security
OWASP Top 10 and security best practices for REST APIs.