Pular para o conteúdoPedro Farbo
Lição 19 / 2535 min

Documentação com Swagger

Documentação com Swagger

API bem documentada facilita a integração por outros desenvolvedores.

Instalação

bash
npm install swagger-ui-express swagger-jsdocnpm install -D @types/swagger-ui-express @types/swagger-jsdoc

Configuração

typescript
// src/config/swagger.tsimport swaggerJsdoc from 'swagger-jsdoc'; const options: swaggerJsdoc.Options = {  definition: {    openapi: '3.0.0',    info: {      title: 'E-commerce API',      version: '1.0.0',      description: 'API completa para e-commerce',      contact: {        name: 'Suporte',        email: 'api@ecommerce.com',      },    },    servers: [      { url: 'http://localhost:3000', description: 'Development' },      { url: 'https://api.ecommerce.com', description: 'Production' },    ],    components: {      securitySchemes: {        bearerAuth: {          type: 'http',          scheme: 'bearer',          bearerFormat: 'JWT',        },      },    },    security: [{ bearerAuth: [] }],  },  apis: ['./src/routes/*.ts', './src/schemas/*.ts'],}; export const swaggerSpec = swaggerJsdoc(options);

Integração no App

typescript
// src/app.tsimport swaggerUi from 'swagger-ui-express';import { swaggerSpec } from './config/swagger'; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));app.get('/api-docs.json', (req, res) => {  res.json(swaggerSpec);});

Documentando Schemas

typescript
// src/schemas/product.schema.ts/** * @openapi * components: *   schemas: *     Product: *       type: object *       required: *         - name *         - price *       properties: *         id: *           type: string *           format: uuid *         name: *           type: string *           example: "iPhone 15" *         description: *           type: string *         price: *           type: number *           format: float *           example: 5999.99 *         stock: *           type: integer *           example: 100 *         createdAt: *           type: string *           format: date-time * *     CreateProduct: *       type: object *       required: *         - name *         - price *       properties: *         name: *           type: string *         description: *           type: string *         price: *           type: number *         stock: *           type: integer *         categoryId: *           type: string * *     PaginatedProducts: *       type: object *       properties: *         data: *           type: array *           items: *             $ref: '#/components/schemas/Product' *         pagination: *           type: object *           properties: *             page: *               type: integer *             limit: *               type: integer *             total: *               type: integer *             totalPages: *               type: integer */

Documentando Rotas

typescript
// src/routes/product.routes.ts/** * @openapi * /api/products: *   get: *     tags: *       - Products *     summary: Lista todos os produtos *     description: Retorna lista paginada de produtos *     parameters: *       - in: query *         name: page *         schema: *           type: integer *           default: 1 *         description: Número da página *       - in: query *         name: limit *         schema: *           type: integer *           default: 20 *         description: Itens por página *       - in: query *         name: category *         schema: *           type: string *         description: Filtrar por categoria *     responses: *       200: *         description: Lista de produtos *         content: *           application/json: *             schema: *               $ref: '#/components/schemas/PaginatedProducts' */router.get('/', productController.list); /** * @openapi * /api/products/{id}: *   get: *     tags: *       - Products *     summary: Busca produto por ID *     parameters: *       - in: path *         name: id *         required: true *         schema: *           type: string *         description: ID do produto *     responses: *       200: *         description: Produto encontrado *         content: *           application/json: *             schema: *               $ref: '#/components/schemas/Product' *       404: *         description: Produto não encontrado */router.get('/:id', productController.show); /** * @openapi * /api/products: *   post: *     tags: *       - Products *     summary: Cria novo produto *     security: *       - bearerAuth: [] *     requestBody: *       required: true *       content: *         application/json: *           schema: *             $ref: '#/components/schemas/CreateProduct' *     responses: *       201: *         description: Produto criado *       401: *         description: Não autenticado *       403: *         description: Sem permissão */router.post('/', authenticate, authorize('ADMIN'), productController.create);

Documentando Auth

typescript
// src/routes/auth.routes.ts/** * @openapi * /api/auth/login: *   post: *     tags: *       - Auth *     summary: Fazer login *     security: [] *     requestBody: *       required: true *       content: *         application/json: *           schema: *             type: object *             required: *               - email *               - password *             properties: *               email: *                 type: string *                 format: email *               password: *                 type: string *                 format: password *     responses: *       200: *         description: Login bem-sucedido *         content: *           application/json: *             schema: *               type: object *               properties: *                 user: *                   $ref: '#/components/schemas/User' *                 token: *                   type: string *       401: *         description: Credenciais inválidas */

Acessando a Documentação

Acesse http://localhost:3000/api-docs para ver a documentação interativa.

Resumo

  • ✅ Swagger UI para documentação visual
  • ✅ OpenAPI 3.0 spec
  • ✅ Documentação via JSDoc
  • ✅ Schemas reutilizáveis
  • ✅ Autenticação documentada

Próxima aula: Segurança da API! 🔒

Gostou do conteúdo? Sua contribuição ajuda a manter tudo online e gratuito!

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