Search code examples
swaggernestjs

Explicit types in Request Body not showing up in Swagger (NestJS)


I am working with Swagger and NestJs. I have the following API endpoint in my controller.

@ApiTags('test')
@Controller('test')
export class TestController {
   @Put()
   async create(
       @Body('test') test: {
           name: string,
           age: number
       }): Promise<Foo> {
           return await this.testService.creat(test);
       }
   }
}

Unfortunately swagger doesn't pick up the inline type definition (or the body parameter in the first place). If I replace the inline definition with a class with @ApiProperty() annotations it works. However, I want to find a way without using Classes.

Is there a way or do I have to use classes here?

I also tried using the ApiBody() annotation, however that only adds a "Request Body required" field without the Type definition in swagger (see below)

swagger

Thanks in advance!


Solution

  • You have to specify the complete schema inside the @ApiBody() tag. However this will only increase your work of managing this along with the actual @Body() tag.

    @ApiTags('test')
    @ApiBody({
                schema: {
                    properties: {
                        'name': { type: 'string' },
                        'age': { type: 'number' }
                    }
                }
             })
    @Controller('test')
    export class TestController {
       @Put()
       async create(
           @Body('test') test: {
               name: string,
               age: number
           }): Promise<Foo> {
               return await this.testService.creat(test);
           }
       }
    }
    

    I would recommend using classes instead as suggested by Jay.