| name | openapi-swagger |
| description | Design, document, and generate APIs using OpenAPI/Swagger specifications. Create interactive API documentation, generate client SDKs, validate schemas, and build mock servers. Use when designing REST APIs, creating API documentation, generating client libraries, or validating API contracts. (project) |
OpenAPI/Swagger API Development
Expert guidance for API design, documentation, and SDK generation.
When to Use This Skill
- Designing REST API specifications
- Creating interactive API documentation
- Generating client SDKs
- Validating API schemas
- Building mock servers for development
- API contract testing
OpenAPI Specification Basics
Minimal OpenAPI 3.0 Spec
openapi: 3.0.3
info:
title: My API
description: API description
contact:
name: API Support
email: support@example.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
servers:
- url: https://api.example.com/v1
description: Production
- url: https://staging-api.example.com/v1
description: Staging
- url: http://localhost:3000/v1
description: Development
paths:
/health:
get:
summary: Health check
operationId: healthCheck
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: healthy
Path Operations
CRUD Operations
paths:
/users:
get:
summary: List users
operationId: listUsers
tags:
- Users
parameters:
- name: limit
in: query
schema:
type: integer
default: 20
maximum: 100
- name: offset
in: query
schema:
type: integer
default: 0
- name: sort
in: query
schema:
type: string
enum: [asc, desc]
default: asc
responses:
'200':
description: List of users
content:
application/json:
Components (Schemas)
Data Models
components:
schemas:
User:
type: object
required:
- id
- email
- createdAt
properties:
id:
type: string
format: uuid
readOnly: true
email:
type: string
format: email
name:
type: string
minLength: 1
maxLength: 100
role:
type: string
enum: [admin, user, guest]
default: user
isActive:
type: boolean
default: true
createdAt:
type: string
format: date-time
readOnly: true
updatedAt:
type:
[, , ]
Reusable Responses
components:
responses:
BadRequest:
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: BAD_REQUEST
message: Invalid request parameters
Unauthorized:
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: UNAUTHORIZED
message: Authentication required
Forbidden:
description: Forbidden
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: FORBIDDEN
message: Insufficient permissions
NotFound:
description: Resource not found
Security Schemes
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/authorize
tokenUrl: https://auth.example.com/token
scopes:
read:users: Read user information
write:users: Modify user information
admin: Full administrative access
BasicAuth:
type: http
scheme: basic
security:
- BearerAuth: []
paths:
/public:
get:
security: []
[]
[]
Advanced Features
File Uploads
paths:
/upload:
post:
summary: Upload file
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
file:
type: string
format: binary
description:
type: string
responses:
'200':
description: File uploaded
content:
application/json:
schema:
type: object
properties:
fileId:
type: string
url:
type: string
format: uri
Webhooks (OpenAPI 3.1)
webhooks:
userCreated:
post:
summary: User created webhook
requestBody:
content:
application/json:
schema:
type: object
properties:
event:
type: string
const: user.created
data:
$ref: '#/components/schemas/User'
responses:
'200':
description: Webhook processed
Polymorphism
components:
schemas:
Pet:
oneOf:
- $ref: '#/components/schemas/Dog'
- $ref: '#/components/schemas/Cat'
discriminator:
propertyName: petType
mapping:
dog: '#/components/schemas/Dog'
cat: '#/components/schemas/Cat'
Dog:
type: object
properties:
petType:
type: string
breed:
type: string
barkVolume:
type: integer
Cat:
type: object
properties:
petType:
type: string
breed:
type: string
meowPitch:
type: integer
Tools & CLI Commands
Swagger CLI
npm install -g @apidevtools/swagger-cli
swagger-cli validate api.yaml
swagger-cli bundle api.yaml -o bundled.yaml
swagger-cli bundle api.yaml -o api.json -t json
OpenAPI Generator
npm install -g @openapitools/openapi-generator-cli
openapi-generator-cli generate \
-i api.yaml \
-g typescript-axios \
-o ./generated/client
openapi-generator-cli generate \
-i api.yaml \
-g python \
-o ./generated/python-client
openapi-generator-cli generate \
-i api.yaml \
-g nodejs-express-server \
-o ./generated/server
openapi-generator-cli list
Spectral (Linting)
npm install -g @stoplight/spectral-cli
spectral lint api.yaml
extends: spectral:oas
rules:
operation-operationId: error
operation-tags: error
info-contact: warn
Prism (Mock Server)
npm install -g @stoplight/prism-cli
prism mock api.yaml
prism mock api.yaml --dynamic
prism proxy api.yaml https://api.example.com
Swagger UI / Redoc
Docker Swagger UI
services:
swagger-ui:
image: swaggerapi/swagger-ui
ports:
- "8080:8080"
environment:
- SWAGGER_JSON=/api/openapi.yaml
volumes:
- ./api.yaml:/api/openapi.yaml
Redoc
<!DOCTYPE html>
<html>
<head>
<title>API Documentation</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
<style>body { margin: 0; padding: 0; }</style>
</head>
<body>
<redoc spec-url='./api.yaml'></redoc>
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
</body>
</html>
npm install -g @redocly/cli
redocly build-docs api.yaml -o docs.html
redocly preview-docs api.yaml
Code Generation Examples
TypeScript Types
export interface User {
id: string;
email: string;
name?: string;
role: 'admin' | 'user' | 'guest';
isActive: boolean;
createdAt: string;
updatedAt: string;
}
export interface CreateUserRequest {
email: string;
name?: string;
password: string;
}
export interface ApiResponse<T> {
data: T;
pagination?: Pagination;
}
API Client Usage
import { UsersApi, Configuration } from './generated/client';
const config = new Configuration({
basePath: 'https://api.example.com/v1',
accessToken: 'your-jwt-token'
});
const usersApi = new UsersApi(config);
const users = await usersApi.listUsers({ limit: 10 });
const newUser = await usersApi.createUser({
createUserRequest: {
email: 'user@example.com',
name: 'John Doe',
password: 'securepassword'
}
});
const user = await usersApi.getUser({ userId: 'uuid-here' });
Best Practices
- Use semantic versioning for API versions
- Define reusable components (schemas, responses, parameters)
- Include examples for all schemas and responses
- Use operationId for code generation
- Tag operations for logical grouping
- Document all error responses
- Use $ref to avoid duplication
- Validate specs before publishing
- Version control your API specs
- Generate SDKs for consistent client implementations