OpenAPI Cheat Sheet
Quick reference for OpenAPI 3.1 specification syntax, components, security schemes, and best practices. Design APIs faster with this comprehensive reference.
OpenAPI Document Structure
| openapi: "3.1.0" | OpenAPI version (must be 3.1.0 for latest) |
| info | Metadata: title, description, version, contact, license |
| servers | Array of base URLs with variables |
| paths | Endpoint definitions with operations |
| components | Reusable schemas, parameters, responses, security schemes |
| security | Global authentication requirements |
| tags | Operation grouping for documentation |
| externalDocs | Link to additional documentation |
Info Object
| title | API name (required) |
| version | API version string (required) |
| description | API description (supports CommonMark markdown) |
| termsOfService | URL to terms of service |
| contact | { name, url, email } — Contact information |
| license | { name, url } — License information |
info:
title: PetStore API
version: 2.0.0
description: A sample API for managing a pet store
termsOfService: https://petstore.example.com/terms
contact:
name: API Support
email: [email protected]
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
Paths & Operations
| Method | Description |
|---|---|
| get | Retrieve a resource or list of resources |
| post | Create a new resource |
| put | Replace an entire resource |
| patch | Partial update to a resource |
| delete | Remove a resource |
| head | Metadata only (no body) |
| options | Describe API capabilities |
| trace | Diagnostic loop-back |
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
schema:
type: integer
responses:
'200':
description: A list of pets
post:
summary: Create a pet
operationId: createPet
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PetCreate'
responses:
'201':
description: Pet created
Components
| schemas | Reusable JSON Schemas for request/response bodies |
| parameters | Reusable path/query/header/cookie parameters |
| responses | Reusable response definitions |
| requestBodies | Reusable request body definitions |
| headers | Reusable header definitions |
| securitySchemes | Authentication scheme definitions |
| links | Operation links (HATEOAS) |
| callbacks | Webhook callback definitions |
components:
schemas:
Pet:
type: object
required:
- name
- status
properties:
id:
type: integer
format: int64
readOnly: true
name:
type: string
minLength: 1
maxLength: 100
status:
type: string
enum: [available, pending, sold]
category:
$ref: '#/components/schemas/Category'
tags:
type: array
items:
$ref: '#/components/schemas/Tag'
PetCreate:
type: object
required:
- name
properties:
name:
type: string
status:
type: string
default: available
Security Schemes
| http (basic) | HTTP Basic Authentication |
| http (bearer) | Bearer token (JWT, OAuth 2.0) |
| apiKey | API key in header/query/cookie |
| oauth2 | OAuth 2.0 flows (authorizationCode, implicit, password, clientCredentials) |
| openIdConnect | OpenID Connect Discovery |
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://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: Read access
write: Write access
# Global security requirement
security:
- BearerAuth: []
- ApiKeyAuth: []
# Or per-operation
paths:
/admin:
get:
security:
- OAuth2: [read, write]
Parameters
| in: path | URL path segment (required: true) |
| in: query | URL query string parameter |
| in: header | HTTP header |
| in: cookie | Cookie value |
parameters:
- name: userId
in: path
required: true
description: Unique user identifier
schema:
type: integer
minimum: 1
example: 12345
- name: include
in: query
required: false
description: Related resources to include
schema:
type: array
items:
type: string
enum: [posts, comments, profile]
style: form
explode: true
- name: X-Request-ID
in: header
required: true
schema:
type: string
format: uuid
- name: sessionId
in: cookie
required: true
schema:
type: string
Status Codes & Responses
| Code | Meaning |
|---|---|
| 200 OK | Successful GET, PUT, PATCH |
| 201 Created | Resource created (POST) |
| 204 No Content | Success with no body (DELETE) |
| 304 Not Modified | Cache validation (ETag/If-Modified-Since) |
| 400 Bad Request | Invalid syntax, validation error |
| 401 Unauthorized | Missing or invalid authentication |
| 403 Forbidden | Authenticated but no permission |
| 404 Not Found | Resource does not exist |
| 409 Conflict | Resource conflict (duplicate, version mismatch) |
| 422 Unprocessable Entity | Validation errors (semantic) |
| 429 Too Many Requests | Rate limit exceeded |
| 500 Internal Server Error | Server-side error |
responses:
'200':
description: Successful response
headers:
X-RateLimit-Limit:
schema:
type: integer
X-RateLimit-Remaining:
schema:
type: integer
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
example:
id: 123
name: Fluffy
status: available
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: VALIDATION_ERROR
message: Invalid input
details:
- field: name
message: Name is required
'404':
description: Resource not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
default:
description: Unexpected error
Common Patterns
| Pagination | cursor, limit, offset, page, page_size |
| Sorting | sort=field,-other_field (prefix - for desc) |
| Filtering | filter[field]=value, filter[operator]=gte |
| Field Selection | fields=id,name,email (sparse fieldsets) |
| Includes | include=posts,comments (related resources) |
| Idempotency | X-Idempotency-Key header for POST/PUT |
| ETag / Caching | ETag header + If-None-Match request header |
| Async Operations | 202 Accepted + Location header for status polling |
# Pagination patterns
/query?limit=20&offset=40 # Offset-based
/query?cursor=abc123&limit=20 # Cursor-based (recommended)
/query?page=3&page_size=20 # Page-based
# Sorting
/query?sort=created_at,-name # Ascending created, descending name
# Filtering (JSON:API style)
/query?filter[status]=published
/query?filter[created_at][gte]=2024-01-01
# Sparse fieldsets
/query?fields=user=id,name,email
# Includes
/query/posts?include=author,comments
# Conditional requests
If-None-Match: "abc123"
If-Match: "abc123" # For optimistic locking
# Async operations
POST /jobs
→ 202 Accepted
Location: /jobs/123/status
Retry-After: 5
Common Media Types
| application/json | Standard JSON (most common) |
| application/xml | XML format |
| multipart/form-data | File uploads |
| application/x-www-form-urlencoded | Form submissions |
| text/plain | Plain text |
| application/pdf | PDF documents |
| image/png, image/jpeg | Image files |
| application/vnd.api+json | JSON:API format |
Common Gotchas
| Path parameters required | Parameters with in: path must have required: true |
| operationId uniqueness | operationId must be unique across all operations (used for codegen) |
| Default response | Use default response to catch unspecified errors |
| readOnly/writeOnly | Use readOnly: true for IDs, writeOnly: true for passwords |
| nullable values | OpenAPI 3.1: use type: [..., "null"] (JSON Schema 2020-12) |
| Circular references | Use $ref for self-referencing schemas (parent/child relationships) |
| Deprecated fields | Use deprecated: true to mark fields for removal |
| Example placement | Use examples (plural) for multiple, example (singular) for one |
Essential Tools
| Spectral | Linting and validation (stoplight.io/spectral) |
| Swagger Editor | Real-time editing and preview (editor.swagger.io) |
| openapi-generator | Generate SDKs, servers, docs from spec |
| Redoc | Beautiful documentation generation |
| Stoplight Studio | Visual OpenAPI designer (GUI) |
| Postman | Import OpenAPI for testing collections |
Related Guide
Learn API-first design and OpenAPI best practices in depth.
Read OpenAPI Best Practices →