Documenting Your NestJS API with Swagger
Let's document our NestJS API using Swagger. Swagger is a powerful tool for automatically generating interactive API documentation, making it easier for developers to understand and consume your API.
Installing Swagger
First, install the necessary packages for Swagger:
npm install @nestjs/swagger swagger-ui-express
Configuring Swagger
Next, update the AppModule to enable Swagger:
import { Module } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
const options = new DocumentBuilder()
.setTitle('NestJS API')
.setDescription('The NestJS API documentation')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(this.app, options);
SwaggerModule.setup('api', this.app, document);
}
}
Generating Swagger Documentation
Now, run your NestJS application:
npm run start
You can access the Swagger UI by navigating to https://localhost:3000/api in your web browser. You should see the Swagger UI with documentation for your API endpoints.
Adding Swagger Annotations
You can use Swagger decorators to add metadata to your controllers and methods, which will be used to generate the Swagger documentation. For example:
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('cats')
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
In this example, the @ApiTags('cats') decorator specifies the tag for the CatsController class, and the documentation will include this tag to group related endpoints.
Swagger provides a powerful way to automatically generate interactive API documentation, making it easier for developers to understand and consume your API.