Swagger Documentation
Document your API with OpenAPI/Swagger.
Installation
bash
npm install swagger-ui-express swagger-jsdocnpm install -D @types/swagger-ui-express @types/swagger-jsdocConfiguration
typescript
// src/config/swagger.tsimport swaggerJsdoc from 'swagger-jsdoc'; const options = { definition: { openapi: '3.0.0', info: { title: 'E-commerce API', version: '1.0.0', description: 'Complete e-commerce API', }, servers: [ { url: 'http://localhost:3000', description: 'Development' }, ], components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, }, }, }, apis: ['./src/routes/*.ts', './src/schemas/*.ts'],}; export const swaggerSpec = swaggerJsdoc(options);Integration
typescript
// src/app.tsimport swaggerUi from 'swagger-ui-express';import { swaggerSpec } from './config/swagger'; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));Documenting Routes
typescript
/** * @openapi * /api/products: * get: * tags: [Products] * summary: List all products * parameters: * - in: query * name: page * schema: * type: integer * responses: * 200: * description: Products list */router.get('/', controller.list); /** * @openapi * /api/products: * post: * tags: [Products] * summary: Create product * security: * - bearerAuth: [] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/CreateProduct' * responses: * 201: * description: Product created */router.post('/', authenticate, controller.create);Documenting Schemas
typescript
/** * @openapi * components: * schemas: * Product: * type: object * properties: * id: * type: string * name: * type: string * price: * type: number */Access http://localhost:3000/api-docs for the interactive docs.
Summary
- ✅ Swagger UI integration
- ✅ OpenAPI 3.0 spec
- ✅ JSDoc documentation
Next lesson: API Security! 🚀