What Is OpenAPI?
The OpenAPI Specification (formerly Swagger) is a language-agnostic, machine-readable format for describing REST APIs. A single YAML or JSON file documents every endpoint, request/response schema, authentication method, and error code.
The *design-first* approach means you write the spec before writing code. This forces you to think through your API contract, enables parallel frontend/backend development, and gives you automatic documentation, mock servers, and client SDKs from day one.
Writing Your First Spec
openapi: '3.1.0'
info:
title: Orders API
version: '1.0.0'
description: Manage customer orders.
servers:
- url: https://api.example.com/v1
Paths and Operations
Each path defines one or more HTTP operations:
paths:
/orders:
get:
summary: List orders
operationId: listOrders
parameters:
- name: limit
in: query
schema: { type: integer, default: 20, maximum: 100 }
responses:
'200':
description: A list of orders
content:
application/json:
schema:
$ref: '#/components/schemas/OrderList'
'401':
$ref: '#/components/responses/Unauthorized'
post:
summary: Create an order
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OrderCreate'
responses:
'201':
description: Order created
Request/Response Schemas
Schemas use JSON Schema (OpenAPI 3.1 supports the full JSON Schema draft 2020-12):
components:
schemas:
Order:
type: object
required: [id, status, amount]
properties:
id:
type: string
example: 'ord_9182'
status:
type: string
enum: [pending, processing, completed, cancelled]
amount:
type: integer
description: Amount in cents
example: 4999
created_at:
type: string
format: date-time
Authentication Schemes
OpenAPI supports four security scheme types:
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
OAuth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://auth.example.com/oauth/authorize
tokenUrl: https://auth.example.com/oauth/token
scopes:
read:orders: Read orders
write:orders: Create and update orders
Apply security at the global level or per operation:
security:
- BearerAuth: []
Code Generation
From a single spec, you can generate:
- Server stubs — FastAPI, Express, Django REST Framework, Spring Boot
- Client SDKs — TypeScript, Python, Go, Java, Swift
- Documentation — Swagger UI, Redoc, Scalar
- Mock servers — Prism, WireMock
# Generate a TypeScript client
npx @openapitools/openapi-generator-cli generate \
-i openapi.yaml -g typescript-fetch -o ./src/api
# Run a mock server
npx @stoplight/prism-cli mock openapi.yaml
Validation and Testing
Validate your spec for correctness:
# Validate spec
npx @redocly/cli lint openapi.yaml
# Contract test — verify your implementation matches the spec
npx dredd openapi.yaml https://api.example.com
Integrate spec validation into CI so implementation drift is caught immediately. A spec that no longer matches the implementation is worse than no spec at all.