Saltar al contenidoPedro Farbo
Lección 19 / 2545 min

Documentación con Swagger

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-jsdoc

Configuració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/docs

Documentació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! 🚀

¿Te gustó el contenido? ¡Tu contribución ayuda a mantener todo online y gratuito!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e