Skip to content
On this page

Documentación de API REST

En esta sección veremos como documentar nuestra API REST con NestJS. Además te dejo el tutorial en video paso a paso:

Swagger ui

  • La especificación OpenAPI es un formato de definición independiente del idioma que se usa para describir las API RESTful.
  • Nest proporciona un módulo dedicado que permite generar dicha especificación aprovechando los decoradores.
  • Swagger ui es una herramienta que nos permite visualizar y probar nuestra API REST.
  • introduction
sh
yarn add @nestjs/swagger -SE

main.ts

ts
import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.setGlobalPrefix("api/v1");

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    })
  );

  const config = new DocumentBuilder()
    .setTitle("Cats example")
    .setDescription("The cats API description")
    .setVersion("1.0")
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("docs", app, document);

  await app.listen(parseInt(process.env.PORT) || 3001);
}
bootstrap();

Types and parameters (DTOs)

  • using-the-cli-plugin
  • Si bien la configuración se puede hacer manual, utilizaremos el CLI de NestJS para generar la documentación de los DTOs.

WARNING

Asegúrate de bajar el servidor y eliminar la carpeta dist.

nest-cli.json

json
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "plugins": ["@nestjs/swagger"]
  }
}

Operations

Tags

src\cats\cats.controller.ts

ts
import { ApiTags } from '@nestjs/swagger';

@ApiTags('cats')

Bearer authentication

ts
@ApiBearerAuth()
@Controller("cats")
export class CatsController {}

src\main.ts

ts
const config = new DocumentBuilder()
  .setTitle('Cats example')
  .setDescription('The cats API description')
  .setVersion('1.0')
  .addBearerAuth()
  .build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);

src\cats\cats.controller.ts

Responses

ts
@ApiBearerAuth()
@ApiUnauthorizedResponse({
  description: 'Unauthorized Bearer Auth',
})
@ApiTags('cats')
@Auth(Role.USER)
@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  @ApiCreatedResponse({
    description: 'The record has been successfully created.',
  })
  @ApiForbiddenResponse({ description: 'Forbidden.' })
  create(
    @Body() createCatDto: CreateCatDto,
    @ActiveUser() user: UserActiveInterface,
  ) {
    return this.catsService.create(createCatDto, user);
  }