Documentación con Swagger
Swagger genera documentación interactiva para tu API.
Instalación
bash
npm install swagger-ui-express swagger-jsdocnpm install -D @types/swagger-ui-express @types/swagger-jsdocConfiguración
typescript
// src/config/swagger.tsimport swaggerJsdoc from 'swagger-jsdoc';import swaggerUi from 'swagger-ui-express';import { Express } from 'express'; const options: swaggerJsdoc.Options = { definition: { openapi: '3.0.0', info: { title: 'E-commerce API', version: '1.0.0', description: 'API de e-commerce con Node.js y TypeScript', }, servers: [ { url: 'http://localhost:3000', description: 'Desarrollo' }, { url: 'https://api.ecommerce.com', description: 'Producción' }, ], components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', }, }, }, }, apis: ['./src/routes/*.ts', './src/schemas/*.ts'],}; const specs = swaggerJsdoc(options); export const setupSwagger = (app: Express) => { app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(specs));};Documentando Rutas
typescript
// src/routes/product.routes.ts /** * @swagger * components: * schemas: * Product: * type: object * properties: * id: * type: string * format: uuid * name: * type: string * slug: * type: string * price: * type: number * description: * type: string * category: * $ref: '#/components/schemas/Category' */ /** * @swagger * /api/products: * get: * summary: Lista todos los productos * tags: [Products] * parameters: * - in: query * name: page * schema: * type: integer * default: 1 * - in: query * name: limit * schema: * type: integer * default: 20 * - in: query * name: search * schema: * type: string * - in: query * name: categoryId * schema: * type: string * responses: * 200: * description: Lista de productos con paginación * content: * application/json: * schema: * type: object * properties: * data: * type: array * items: * $ref: '#/components/schemas/Product' * pagination: * type: object */ /** * @swagger * /api/products: * post: * summary: Crea un nuevo producto * tags: [Products] * security: * - bearerAuth: [] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - name * - price * - categoryId * properties: * name: * type: string * price: * type: number * description: * type: string * categoryId: * type: string * responses: * 201: * description: Producto creado * 401: * description: No autenticado * 403: * description: Sin permiso */router.post('/', authenticate, authorize('ADMIN'), controller.store);Setup en App
typescript
// src/app.tsimport { setupSwagger } from './config/swagger'; // ... otras configuraciones setupSwagger(app); // Acceder en: http://localhost:3000/api/docsDocumentación de Auth
typescript
/** * @swagger * /api/auth/login: * post: * summary: Iniciar sesión * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * email: * type: string * format: email * password: * type: string * responses: * 200: * description: Login exitoso * content: * application/json: * schema: * type: object * properties: * user: * $ref: '#/components/schemas/User' * token: * type: string * 401: * description: Credenciales inválidas */Resumen
- ✅ Swagger UI configurado
- ✅ Documentación con JSDoc
- ✅ Schemas reutilizables
- ✅ Autenticación documentada
Próxima clase: Seguridad de API! 🚀