How to Automatically Generate Swagger Docs in NestJS

Updated: January 1, 2024 By: Guest Contributor Post a comment

Introduction

Learn how to seamlessly integrate Swagger for auto-generating API documentation in NestJS, improving development efficiency and API usability.

Setting up NestJS

Before we jump into Swagger, make sure you have a NestJS project set up. Install the necessary packages via npm:

npm i -g @nestjs/cli
nestjs new project-name

After creating your project, navigate into its directory:

cd project-name

Installing Swagger Modules

Install the required Swagger packages for NestJS:

npm install @nestjs/swagger swagger-ui-express

Basic Configuration

To start, let’s configure Swagger for a simple API. Import SwaggerModule and DocumentBuilder in your main.ts:

import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

Next, you’ll want to create a Swagger document. Typically, you would do this in your main.ts as part of your bootstrap function:

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

  const config = new DocumentBuilder()
    .setTitle('Example API')
    .setDescription('The Example API description')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

Having done this, you can now access the Swagger UI by navigating to http://localhost:3000/api in your browser, which automatically generates documentation for your endpoints.

Annotating Controllers and Models

The next step is to use decorators provided by the @nestjs/swagger package to enrich your controllers and models with meta-information that Swagger uses to generate detailed documentation.

import { Controller, Get } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';

@Controller('cats')
export class CatsController {
  @Get()
  @ApiResponse({ status: 200, description: 'Get all cats.' })
  getAllCats() {
    // Your logic here
  }

  @Get(':id')
  @ApiResponse({ status: 200, description: 'Get a specific cat by id.' })
  getCatById() {
    // Your logic here
  }
}

Models can be detailed using Swagger’s decorators too:

import { ApiProperty } from '@nestjs/swagger';

export class Cat {
  @ApiProperty({ example: '1', description: 'The unique identifier of the cat.' })
  id: string;

  @ApiProperty({ example: 'Mittens', description: 'The name of the cat.' })
  name: string;
}

Advanced Configuration

For more complex APIs, there are additional options you can configure, like authentication, tags, and response models:

const config = new DocumentBuilder()
  .setTitle('Example API')
  .setDescription('The Example API description')
  .setVersion('1.0')
  .addTag('cats')
  .addBearerAuth()
  .build();

If you need to describe response objects for different scenarios, you can use the @ApiOkResponse decorator and specify the model:

@ApiOkResponse({ type: Cat, description: 'The cat has been successfully retrieved.' })

Automating the Process

Automating Swagger documentation is possible by combining decorators inside your NestJS application codebase. It minimizes effort and keeps your docs in sync with the actual API:

// Other necessary import statements
import { Crud, CrudController } from '@nestjsx/crud';
from '@nestjsx/crud-swagger';

@Crud({
  model: {
    type: Cat,
  },
  query: {
    // Your CRUD configuration here
  },
})
@Controller('cats')
export class CatsController implements CrudController {
  constructor(public service: CatsService) {}
}

Generating Docs for Existing Projects

To integrate Swagger into an existing NestJS project, ensure you follow the basic steps mentioned earlier, and then proceed to annotate existing controllers, services, and models with Swagger decorators.

Note: The level of effort involved largely depends on the size and complexity of your existing codebase.

Conclusion

With these steps, you can easily auto-generate comprehensive Swagger documentation for your NestJS APIs, enhancing development workflows and ensuring your API’s integrations are effortless. Remember, keeping documentation updated is key to a successful API strategy, and Swagger provides the tools to make this process as seamless as possible.