Decorators for Requests and Responses

To document your requests and responses you can use the following decorators:

  • @ApiProperty

  • @ApiPropertyOptional

By using these decorators on each of the class properties, you have to document each of them.

This is an example of what a documented request body looks like:

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

export class NotificationCategoryDto {
  @ApiProperty({
    name: 'name',
    type: String,
    required: true,
    example: 'Accounts',
  })
  name: string;
}
Swagger Interface.

If you want to document your API responses, you should also use decorators to make them visible in the Swagger interface.

Example:

import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';

export class NotificationCategory {
  @ApiProperty({
    name: 'id',
    type: String,
    example: 'b0a600fa-8860-42a6-8a6a-6521e90749b1',
  })
  @IsString()
  id?: string;

  @ApiProperty({
    name: 'name',
    type: String,
    example: 'Accounts',
  })
  @IsString()
  name?: string;
}

export class NotificationCategories {
  @ApiProperty({
    name: 'categories',
    type: NotificationCategory,
    isArray: true,
  })
  categories: NotificationCategory[];
}
Swagger Interface > Response example.

Correct:

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

export class NotificationCategoryDto {
  @ApiProperty({
    name: 'name',
    type: String,
    required: true,
    example: 'Accounts',
  })
  name: string;
}

Incorrect:

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

export interface NotificationCategoryDto {
  @ApiProperty({
    name: 'name',
    type: String,
    required: true,
    example: 'Accounts',
  })
  name: string;
}

Last updated

Was this helpful?