Swagger/OpenAPI Guide
Basic to Advanced with Live Examples and Developer Tips
Introduction
Swagger/OpenAPI lets you define RESTful APIs in a machine-readable format, helping with documentation, testing, and SDK generation.
Setup & Installation
$ npm install swagger-ui-express swagger-jsdoc
const swaggerJsdoc = require('swagger-jsdoc');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
Basic YAML/JSON Examples
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: Get all users
responses:
'200':
description: List of users
"openapi": "3.0.3",
"info": { "title": "Sample API", "version": "1.0.0" },
"paths": {
"/users": { "get": {
"summary": "Get all users",
"responses": { "200": { "description": "List of users" } }
} } }
}
Intermediate Features
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
security:
- ApiKeyAuth: []
Advanced Techniques
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
Live Swagger UI
Pro Tips & Troubleshooting
- Use tags to organize endpoints.
- Provide examples for request/response bodies.
- Validate YAML/JSON before deployment.
- Enable deepLinking in Swagger UI for better navigation.
Swagger Across Cloud Platforms
Swagger/OpenAPI is platform-independent, but each cloud provider has its own way of integrating and deploying APIs:
| Platform | Hosting | Deployment | Authentication | Monitoring | SDK Generation |
|---|---|---|---|---|---|
| AWS | API Gateway, Lambda | aws apigateway import-rest-api --body file.json |
IAM roles, API keys, Cognito | CloudWatch | Auto SDKs via CLI/Console |
| GCP | Cloud Endpoints | gcloud endpoints services deploy openapi.yaml |
Service Accounts, API keys, OAuth2 | Stackdriver Logging | Auto SDKs via Endpoints |
| Azure | API Management (APIM) | az apim api import --resource-group RG --service-name APIName --path /api --specification-format OpenApi |
OAuth2, Managed Identity | Application Insights | SDKs via APIM portal |
Example: AWS Vendor Extension
/users:
get:
x-amazon-apigateway-integration:
uri: arn:aws:apigateway:region:lambda:path/2015-03-31/functions/arn:aws:lambda:region:account-id:function:myFunction/invocations
httpMethod: POST
type: aws_proxy
Real-World Examples
$ swagger-cli validate openapi.yaml
$ openapi-generator-cli generate -i openapi.yaml -g python -o ./python-client
swagger-cli or openapi-generator-cli to validate and generate SDKs automatically. It reduces runtime errors.
Testing & Debugging Tools
- Postman: Import OpenAPI spec for automated testing.
- Swagger Inspector: Test endpoints without writing any code.
- Stoplight Studio: Advanced visual OpenAPI editor.
- Redoc: Beautiful documentation generator.