OpenAPI (Swagger)

The OpenAPI specification is a language-agnostic definition format used to describe RESTful APIs. Nest provides a dedicated module which allows generating such a specification by leveraging decorators.

Installation

To begin using it, we first install the required dependencies.

  1. $ npm install --save @nestjs/swagger swagger-ui-express

If you use fastify, install fastify-swagger instead of swagger-ui-express:

  1. $ npm install --save @nestjs/swagger fastify-swagger

Bootstrap

Once the installation process is complete, open the main.ts file and initialize Swagger using the SwaggerModule class:

  1. import { NestFactory } from '@nestjs/core';
  2. import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
  3. import { AppModule } from './app.module';
  4. async function bootstrap() {
  5. const app = await NestFactory.create(AppModule);
  6. const options = new DocumentBuilder()
  7. .setTitle('Cats example')
  8. .setDescription('The cats API description')
  9. .setVersion('1.0')
  10. .addTag('cats')
  11. .build();
  12. const document = SwaggerModule.createDocument(app, options);
  13. SwaggerModule.setup('api', app, document);
  14. await app.listen(3000);
  15. }
  16. bootstrap();

The DocumentBuilder helps to structure a base document that conforms to the OpenAPI Specification. It provides several methods that allow setting such properties as title, description, version, etc. In order to create a full document (with all HTTP routes defined) we use the createDocument() method of the SwaggerModule class. This method takes two arguments, an application instance and a Swagger options object.

Once we create a document, we can call setup() method. It accepts:

  1. the path to mount the Swagger UI
  2. an application instance
  3. the document object instantiated above

Now you can run the following command to start the HTTP server:

  1. $ npm run start

While the application is running, open your browser and navigate to http://localhost:3000/api. You should see the Swagger UI.

OpenAPI (Swagger) - 图1

The SwaggerModule automatically reflects all of your endpoints. Also, in order to display the Swagger UI, @nestjs/swagger makes use of either swagger-ui-express or fastify-swagger depending on the platform.

Hint To generate and download a Swagger JSON file, navigate to http://localhost:3000/api-json in your browser (assuming that your Swagger documentation is available under http://localhost:3000/api).

Route parameters

The SwaggerModule searches for all @Body(), @Query(), and @Param() decorators in route handlers to generate the API document. It also creates corresponding model definitions by taking advantage of reflection. Consider the following code:

  1. @Post()
  2. async create(@Body() createCatDto: CreateCatDto) {
  3. this.catsService.create(createCatDto);
  4. }

Hint To explicitly set the body definition use the @ApiBody() decorator (@nestjs/swagger package).

Based on the CreateCatDto, the module definition will be created:

OpenAPI (Swagger) - 图2

As you can see, the definition is empty although the class has a few declared properties. In order to make the class properties visible to the SwaggerModule, we have to either annotate them with the @ApiProperty() decorator or use a CLI plugin (read more in the Plugin section) which will do it automatically:

  1. import { ApiProperty } from '@nestjs/swagger';
  2. export class CreateCatDto {
  3. @ApiProperty()
  4. name: string;
  5. @ApiProperty()
  6. age: number;
  7. @ApiProperty()
  8. breed: string;
  9. }

Hint Consider using the Swagger plugin (see Plugin section) which will automatically do it for you.

Let’s open the browser and verify the generated CreateCatDto model:

OpenAPI (Swagger) - 图3

In addition, the @ApiProperty() decorator allows setting various Schema Object properties:

  1. @ApiProperty({
  2. description: 'The age of a cat',
  3. minimum: 1,
  4. default: 1,
  5. })
  6. age: number;

Hint Instead of explicitly typing the @ApiProperty({ required: false }) you can use @ApiPropertyOptional() short-hand decorator.

In order to explicitly set the type of the property, use the type key:

  1. @ApiProperty({
  2. type: Number,
  3. })
  4. age: number;

Arrays

When the property is an array, we must manually indicate the array type as shown below:

  1. @ApiProperty({ type: [String] })
  2. names: string[];

Hint Consider using the Swagger plugin (see Plugin section) which will automatically detect arrays.

Either include the type as the first element of an array (as shown above) or set the isArray property to true.

Official enterprise support

  • OpenAPI (Swagger) - 图4 Providing technical guidance
  • OpenAPI (Swagger) - 图5 Performing in-depth code reviews
  • OpenAPI (Swagger) - 图6 Mentoring team members
  • OpenAPI (Swagger) - 图7 Advising best practices

Explore more

Circular dependencies

When you have circular dependencies between classes, use a lazy function to provide the SwaggerModule with type information:

  1. @ApiProperty({ type: () => Node })
  2. node: Node;

Hint Consider using the Swagger plugin (see Plugin section) which will automatically detect circular dependencies.

Generics and interfaces

Since TypeScript does not store metadata about generics or interfaces, when you use them in your DTOs, SwaggerModule may not be able to properly generate model definitions at runtime. For instance, the following code won’t be correctly inspected by the Swagger module:

  1. createBulk(@Body() usersDto: CreateUserDto[])

In order to overcome this limitation, you can set the type explicitly:

  1. @ApiBody({ type: [CreateUserDto] })
  2. createBulk(@Body() usersDto: CreateUserDto[])

Mapped types

As you build out features like CRUD (Create/Read/Update/Delete) it’s often useful to construct variants on a base entity type. Nest provides several utility functions that perform type transformations to make this task more convenient.

When building input validation types (also called DTOs), it’s often useful to build create and update variations on the same type. For example, the create variant may require all fields, while the update variant may make all fields optional.

Nest provides the PartialType() utility function to make this task easier and minimize boilerplate.

The PartialType() function returns a type (class) with all the properties of the input type set to optional. For example, suppose we have a create type as follows:

  1. import { ApiProperty } from '@nestjs/swagger';
  2. export class CreateCatDto {
  3. @ApiProperty()
  4. name: string;
  5. @ApiProperty()
  6. age: number;
  7. @ApiProperty()
  8. breed: string;
  9. }

By default, all of these fields are required. To create a type with the same fields, but with each one optional, use PartialType() passing the class reference (CreateCatDto) as an argument:

  1. export class UpdateCatDto extends PartialType(CreateCatDto) {}

Hint The PartialType() function is imported from the @nestjs/swagger package.

The PickType() function constructs a new type (class) by picking a set of properties from an input type. For example, suppose we start with a type like:

  1. import { ApiProperty } from '@nestjs/swagger';
  2. export class CreateCatDto {
  3. @ApiProperty()
  4. name: string;
  5. @ApiProperty()
  6. age: number;
  7. @ApiProperty()
  8. breed: string;
  9. }

We can pick a set of properties from this class using the PickType() utility function:

  1. export class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}

Hint The PickType() function is imported from the @nestjs/swagger package.

The OmitType() function constructs a type by picking all properties from an input type and then removing a particular set of keys. For example, suppose we start with a type like:

  1. import { ApiProperty } from '@nestjs/swagger';
  2. export class CreateCatDto {
  3. @ApiProperty()
  4. name: string;
  5. @ApiProperty()
  6. age: number;
  7. @ApiProperty()
  8. breed: string;
  9. }

We can generate a derived type that has every property exceptname as shown below. In this construct, the second argument to OmitType is an array of property names.

  1. export class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}

Hint The OmitType() function is imported from the @nestjs/swagger package.

The IntersectionType() function combines two types into one new type (class). For example, suppose we start with two types like:

  1. import { ApiProperty } from '@nestjs/swagger';
  2. export class CreateCatDto {
  3. @ApiProperty()
  4. name: string;
  5. @ApiProperty()
  6. breed: string;
  7. }
  8. export class AdditionalCatInfo {
  9. @ApiProperty()
  10. color: string;
  11. }

We can generate a new type that combines all properties in both types.

  1. export class UpdateCatDto extends IntersectionType(CreateCatDto, AdditionalCatInfo) {}

Hint The IntersectionType() function is imported from the @nestjs/swagger package.

The type mapping utility functions are composable. For example, the following will produce a type (class) that has all of the properties of the CreateCatDto type except for name, and those properties will be set to optional:

  1. export class UpdateCatDto extends PartialType(
  2. OmitType(CreateCatDto, ['name'] as const),
  3. ) {}

Enums

To identify an enum, we must manually set the enum property on the @ApiProperty with an array of values.

  1. @ApiProperty({ enum: ['Admin', 'Moderator', 'User']})
  2. role: UserRole;

Alternatively, define an actual TypeScript enum as follows:

  1. export enum UserRole {
  2. Admin = 'Admin',
  3. Moderator = 'Moderator',
  4. User = 'User',
  5. }

You can then use the enum directly with the @Query() parameter decorator in combination with the @ApiQuery() decorator.

  1. @ApiQuery({ name: 'role', enum: UserRole })
  2. async filterByRole(@Query('role') role: UserRole = UserRole.User) {}

OpenAPI (Swagger) - 图8

With isArray set to true, the enum can be selected as a multi-select:

OpenAPI (Swagger) - 图9

Enums schema

By default, the enum property will add a raw definition of Enum on the parameter.

  1. - breed:
  2. type: 'string'
  3. enum:
  4. - Persian
  5. - Tabby
  6. - Siamese

The above specification works fine for most cases. However, if you are utilizing a tool that takes the specification as input and generates client-side code, you might run into a problem with the generated code containing duplicated enums. Consider the following code snippet:

  1. // generated client-side code
  2. export class CatDetail {
  3. breed: CatDetailEnum;
  4. }
  5. export class CatInformation {
  6. breed: CatInformationEnum;
  7. }
  8. export enum CatDetailEnum {
  9. Persian = 'Persian',
  10. Tabby = 'Tabby',
  11. Siamese = 'Siamese',
  12. }
  13. export enum CatInformationEnum {
  14. Persian = 'Persian',
  15. Tabby = 'Tabby',
  16. Siamese = 'Siamese',
  17. }

Hint The above snippet is generated using a tool called NSwag.

You can see that now you have two enums that are exactly the same. To address this issue, you can pass an enumName next to enum property in your decorator.

  1. export class CatDetail {
  2. @ApiProperty({ enum: CatBreed, enumName: 'CatBreed' })
  3. breed: CatBreed;
  4. }

The enumName property enables @nestjs/swagger to turn CatBreed into its own schema which in turns makes CatBreed enum reusable. The specification will look like the following:

  1. CatDetail:
  2. type: 'object'
  3. properties:
  4. ...
  5. - breed:
  6. schema:
  7. $ref: '#/components/schemas/CatBreed'
  8. CatBreed:
  9. type: string
  10. enum:
  11. - Persian
  12. - Tabby
  13. - Siamese

Hint Any decorator that takes enum as a property will also take enumName.

Raw definitions

In some specific scenarios (e.g. deeply nested arrays, matrices), you may want to describe your type by hand.

  1. @ApiProperty({
  2. type: 'array',
  3. items: {
  4. type: 'array',
  5. items: {
  6. type: 'number',
  7. },
  8. },
  9. })
  10. coords: number[][];

Likewise, in order to define your input/output content manually in controller classes, use the schema property:

  1. @ApiBody({
  2. schema: {
  3. type: 'array',
  4. items: {
  5. type: 'array',
  6. items: {
  7. type: 'number',
  8. },
  9. },
  10. },
  11. })
  12. async create(@Body() coords: number[][]) {}

Extra models

In order to define additional models that should be inspected by Swagger module, use the @ApiExtraModels() decorator:

  1. @ApiExtraModels(ExtraModel)
  2. export class CreateCatDto {}

Then, you can get the reference ($ref) to your model using getSchemaPath(ExtraModel):

  1. 'application/vnd.api+json': {
  2. schema: { $ref: getSchemaPath(ExtraModel) },
  3. },

oneOf, anyOf, allOf

In order to combine schemas, you can use oneOf, anyOf or allOf keywords (read more).

  1. @ApiProperty({
  2. oneOf: [
  3. { $ref: getSchemaPath(Cat) },
  4. { $ref: getSchemaPath(Dog) },
  5. ],
  6. })
  7. pet: Cat | Dog;

If you want to define a polymorphic array (i.e., an array whose members span multiple schemas), you should use a raw definition (see above) to define your type by hand.

  1. type Pet = Cat | Dog;
  2. @ApiProperty({
  3. type: 'array',
  4. items: {
  5. oneOf: [
  6. { $ref: getSchemaPath(Cat) },
  7. { $ref: getSchemaPath(Dog) },
  8. ],
  9. },
  10. })
  11. pets: Pet[];

HintgetSchemaPath() function is imported from @nestjs/swagger.

Both Cat and Dog must be defined as extra models using the @ApiExtraModels() decorator (at the class-level).

Multiple specifications

The SwaggerModule provides a way to support multiple specifications. In other words, you can serve different documentation, with different UIs, on different endpoints.

To support multiple specifications, your application must be written with a modular approach. The createDocument() method takes in a 3rd argument, extraOptions, which is an object with a the property include. The include property has a value which is an array of modules.

You can setup multiple specifications support as shown below:

  1. import { NestFactory } from '@nestjs/core';
  2. import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
  3. import { AppModule } from './app.module';
  4. async function bootstrap() {
  5. const app = await NestFactory.create(AppModule);
  6. /**
  7. * createDocument(application, configurationOptions, extraOptions);
  8. *
  9. * createDocument method takes in an optional 3rd argument "extraOptions"
  10. * which is an object with "include" property where you can pass an Array
  11. * of Modules that you want to include in that Swagger Specification
  12. * E.g: CatsModule and DogsModule will have two separate Swagger Specifications which
  13. * will be exposed on two different SwaggerUI with two different endpoints.
  14. */
  15. const options = new DocumentBuilder()
  16. .setTitle('Cats example')
  17. .setDescription('The cats API description')
  18. .setVersion('1.0')
  19. .addTag('cats')
  20. .build();
  21. const catDocument = SwaggerModule.createDocument(app, options, {
  22. include: [CatsModule],
  23. });
  24. SwaggerModule.setup('api/cats', app, catDocument);
  25. const secondOptions = new DocumentBuilder()
  26. .setTitle('Dogs example')
  27. .setDescription('The dogs API description')
  28. .setVersion('1.0')
  29. .addTag('dogs')
  30. .build();
  31. const dogDocument = SwaggerModule.createDocument(app, secondOptions, {
  32. include: [DogsModule],
  33. });
  34. SwaggerModule.setup('api/dogs', app, dogDocument);
  35. await app.listen(3000);
  36. }
  37. bootstrap();

Now you can start your server with the following command:

  1. $ npm run start

Navigate to http://localhost:3000/api/cats to see the Swagger UI for cats:

OpenAPI (Swagger) - 图10

In turn, http://localhost:3000/api/dogs will expose the Swagger UI for dogs:

OpenAPI (Swagger) - 图11

Tags

To attach a controller to a specific tag, use the @ApiTags(...tags) decorator.

  1. @ApiTags('cats')
  2. @Controller('cats')
  3. export class CatsController {}

Headers

To define custom headers that are expected as part of the request, use @ApiHeader().

  1. @ApiHeader({
  2. name: 'X-MyHeader',
  3. description: 'Custom header',
  4. })
  5. @Controller('cats')
  6. export class CatsController {}

Responses

To define a custom HTTP response, we use @ApiResponse() decorator.

  1. @Post()
  2. @ApiResponse({ status: 201, description: 'The record has been successfully created.'})
  3. @ApiResponse({ status: 403, description: 'Forbidden.'})
  4. async create(@Body() createCatDto: CreateCatDto) {
  5. this.catsService.create(createCatDto);
  6. }

Nest provides a set of short-hand API response decorators that inherit from the @ApiResponse decorator:

  • @ApiOkResponse()
  • @ApiCreatedResponse()
  • @ApiAcceptedResponse()
  • @ApiNoContentResponse()
  • @ApiMovedPermanentlyResponse()
  • @ApiBadRequestResponse()
  • @ApiUnauthorizedResponse()
  • @ApiNotFoundResponse()
  • @ApiForbiddenResponse()
  • @ApiMethodNotAllowedResponse()
  • @ApiNotAcceptableResponse()
  • @ApiRequestTimeoutResponse()
  • @ApiConflictResponse()
  • @ApiTooManyRequestsResponse()
  • @ApiGoneResponse()
  • @ApiPayloadTooLargeResponse()
  • @ApiUnsupportedMediaTypeResponse()
  • @ApiUnprocessableEntityResponse()
  • @ApiInternalServerErrorResponse()
  • @ApiNotImplementedResponse()
  • @ApiBadGatewayResponse()
  • @ApiServiceUnavailableResponse()
  • @ApiGatewayTimeoutResponse()
  • @ApiDefaultResponse()
  1. @Post()
  2. @ApiCreatedResponse({ description: 'The record has been successfully created.'})
  3. @ApiForbiddenResponse({ description: 'Forbidden.'})
  4. async create(@Body() createCatDto: CreateCatDto) {
  5. this.catsService.create(createCatDto);
  6. }

To specify a return model for a request, we must create a class and annotate all properties with the @ApiProperty() decorator.

  1. export class Cat {
  2. @ApiProperty()
  3. id: number;
  4. @ApiProperty()
  5. name: string;
  6. @ApiProperty()
  7. age: number;
  8. @ApiProperty()
  9. breed: string;
  10. }

Then, Cat model must be used in combination with the type property of the response decorator.

  1. @ApiTags('cats')
  2. @Controller('cats')
  3. export class CatsController {
  4. @Post()
  5. @ApiCreatedResponse({
  6. description: 'The record has been successfully created.',
  7. type: Cat,
  8. })
  9. async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
  10. return this.catsService.create(createCatDto);
  11. }
  12. }

Let’s open the browser and verify the generated Cat model:

OpenAPI (Swagger) - 图12

Global prefix

To ignore a global prefix for routes set through setGlobalPrefix(), use ignoreGlobalPrefix:

  1. const document = SwaggerModule.createDocument(app, options, {
  2. ignoreGlobalPrefix: true,
  3. });

Security

To define which security mechanisms should be used for a specific operation, use the @ApiSecurity() decorator.

  1. @ApiSecurity('basic')
  2. @Controller('cats')
  3. export class CatsController {}

Before you run your application, remember to add the security definition to your base document using DocumentBuilder:

  1. const options = new DocumentBuilder().addSecurity('basic', {
  2. type: 'http',
  3. scheme: 'basic',
  4. });

Some of the most popular authentication techniques are predefined (e.g. basic and bearer) and therefore you don’t have to define security mechanisms manually as shown above.

Learn the right way!

  • OpenAPI (Swagger) - 图13 60+ chapters
  • OpenAPI (Swagger) - 图14 4+ hours of videos
  • OpenAPI (Swagger) - 图15 Official certificate
  • OpenAPI (Swagger) - 图16 Deep-dive sessions

Explore official courses

Basic authentication

To enable basic authentication, use @ApiBasicAuth().

  1. @ApiBasicAuth()
  2. @Controller('cats')
  3. export class CatsController {}

Before you run your application, remember to add the security definition to your base document using DocumentBuilder:

  1. const options = new DocumentBuilder().addBasicAuth();

Bearer authentication

To enable bearer authentication, use @ApiBearerAuth().

  1. @ApiBearerAuth()
  2. @Controller('cats')
  3. export class CatsController {}

Before you run your application, remember to add the security definition to your base document using DocumentBuilder:

  1. const options = new DocumentBuilder().addBearerAuth();

OAuth2 authentication

To enable OAuth2, use @ApiOAuth2().

  1. @ApiOAuth2(['pets:write'])
  2. @Controller('cats')
  3. export class CatsController {}

Before you run your application, remember to add the security definition to your base document using DocumentBuilder:

  1. const options = new DocumentBuilder().addOAuth2();

Cookie authentication

To enable cookie authentication, use @ApiCookieAuth().

  1. @ApiCookieAuth()
  2. @Controller('cats')
  3. export class CatsController {}

Before you run your application, remember to add the security definition to your base document using DocumentBuilder:

  1. const options = new DocumentBuilder().addCookieAuth('optional-session-id');

File upload

You can enable file upload for a specific method with the @ApiBody decorator together with @ApiConsumes(). Here’s a full example using the File Upload technique:

  1. @UseInterceptors(FileInterceptor('file'))
  2. @ApiConsumes('multipart/form-data')
  3. @ApiBody({
  4. description: 'List of cats',
  5. type: FileUploadDto,
  6. })
  7. uploadFile(@UploadedFile() file) {}

Where FileUploadDto is defined as follows:

  1. class FileUploadDto {
  2. @ApiProperty({ type: 'string', format: 'binary' })
  3. file: any;
  4. }

Extensions

To add an Extension to a request use the @ApiExtension() decorator. The extension name must be prefixed with x-.

  1. @ApiExtension('x-foo', { hello: 'world' })

Decorators

All of the available OpenAPI decorators have an Api prefix to distinguish them from the core decorators. Below is a full list of the exported decorators along with a designation of the level at which the decorator may be applied.

@ApiOperation()Method
@ApiResponse()Method / Controller
@ApiProduces()Method / Controller
@ApiConsumes()Method / Controller
@ApiBearerAuth()Method / Controller
@ApiOAuth2()Method / Controller
@ApiBasicAuth()Method / Controller
@ApiSecurity()Method / Controller
@ApiExtraModels()Method / Controller
@ApiBody()Method
@ApiParam()Method
@ApiQuery()Method
@ApiHeader()Method / Controller
@ApiExcludeEndpoint()Method
@ApiTags()Method / Controller
@ApiProperty()Model
@ApiPropertyOptional()Model
@ApiHideProperty()Model
@ApiExtension()Method

Plugin

TypeScript’s metadata reflection system has several limitations which make it impossible to, for instance, determine what properties a class consists of or recognize whether a given property is optional or required. However, some of these constraints can be addressed at compilation time. Nest provides a plugin that enhances the TypeScript compilation process to reduce the amount of boilerplate code required.

Hint This plugin is opt-in. If you prefer, you can declare all decorators manually, or only specific decorators where you need them.

The Swagger plugin will automatically:

  • annotate all DTO properties with @ApiProperty unless @ApiHideProperty is used
  • set the required property depending on the question mark (e.g. name?: string will set required: false)
  • set the type or enum property depending on the type (supports arrays as well)
  • set the default property based on the assigned default value
  • set several validation rules based on class-validator decorators (if classValidatorShim set to true)
  • add a response decorator to every endpoint with a proper status and type (response model)

Please, note that your filenames must have one of the following suffixes: ['.dto.ts', '.entity.ts'] (e.g., create-user.dto.ts) in order to be analysed by the plugin.

Previously, if you wanted to provide an interactive experience with the Swagger UI, you had to duplicate a lot of code to let the package knows how your models/components should be declared in the specification. For example, you could define a simple CreateUserDto class as follows:

  1. export class CreateUserDto {
  2. @ApiProperty()
  3. email: string;
  4. @ApiProperty()
  5. password: string;
  6. @ApiProperty({ enum: RoleEnum, default: [], isArray: true })
  7. roles: RoleEnum[] = [];
  8. @ApiProperty({ required: false, default: true })
  9. isEnabled?: boolean = true;
  10. }

While it’s not a big deal with medium-sized projects, it becomes pretty verbose & clunky once you have a large set of classes.

Now, with the Swagger plugin enabled, the above class definition can be declared simply:

  1. export class CreateUserDto {
  2. email: string;
  3. password: string;
  4. roles: RoleEnum[] = [];
  5. isEnabled?: boolean = true;
  6. }

The plugin adds appropriate decorators on the fly based on the Abstract Syntax Tree. Hence, you no longer have to struggle with @ApiProperty decorators scattered throughout the entire project.

Hint The plugin will automatically generate any missing swagger properties, but if you need to override them, you simply set them explicitly via @ApiProperty().

In order to enable the plugin, simply open nest-cli.json (if you use Nest CLI) and add the following plugins configuration:

  1. {
  2. "collection": "@nestjs/schematics",
  3. "sourceRoot": "src",
  4. "compilerOptions": {
  5. "plugins": ["@nestjs/swagger/plugin"]
  6. }
  7. }

You can use the options property to customize the behavior of the plugin.

  1. "plugins": [
  2. {
  3. "name": "@nestjs/swagger/plugin",
  4. "options": {
  5. "classValidatorShim": false
  6. }
  7. }
  8. ]

The options property has to fulfill the following interface:

  1. export interface PluginOptions {
  2. dtoFileNameSuffix?: string[];
  3. controllerFileNameSuffix?: string[];
  4. classValidatorShim?: boolean;
  5. }
OptionDefaultDescription
dtoFileNameSuffix[‘.dto.ts’, ‘.entity.ts’]DTO (Data Transfer Object) files suffix
controllerFileNameSuffix.controller.tsController files suffix
classValidatorShimtrueIf set to true, the module will reuse class-validator validation decorators (e.g. @Max(10) will add max: 10 to schema definition)

If you don’t use the CLI but instead have a custom webpack configuration, you can use this plugin in combination with ts-loader:

  1. getCustomTransformers: (program: any) => ({
  2. before: [require('@nestjs/swagger/plugin').before({}, program)]
  3. }),

Migration to 4.0

If you’re currently using @nestjs/swagger@3.*, note the following breaking/API changes in version 4.0.

The following decorators have been changed/renamed:

  • @ApiModelProperty is now @ApiProperty
  • @ApiModelPropertyOptional is now @ApiPropertyOptional
  • @ApiResponseModelProperty is now @ApiResponseProperty
  • @ApiImplicitQuery is now @ApiQuery
  • @ApiImplicitParam is now @ApiParam
  • @ApiImplicitBody is now @ApiBody
  • @ApiImplicitHeader is now @ApiHeader
  • @ApiOperation({ title: 'test' }) is now @ApiOperation({ summary: 'test' })
  • @ApiUseTags is now @ApiTags

DocumentBuilder breaking changes (updated method signatures):

  • addTag
  • addBearerAuth
  • addOAuth2
  • setContactEmail is now setContact
  • setHost has been removed
  • setSchemes has been removed (use the addServer instead, e.g., addServer('http://'))

The following methods have been added:

  • addServer
  • addApiKey
  • addBasicAuth
  • addSecurity
  • addSecurityRequirements

Hoodies, T-shirts, and accessories!

Support our future development by shopping in the official store!

See more

Example

A working example is available here.