Request body not showing in Nest.js + Swagger

Viewed 12670

My controller code is something like this.

@Controller('customer')
export class CustomerController{

    constructor(private readonly customerService: CustomerService){}

    @Post('lookup')
    async someMethod(@Body() body:any){

        console.log("BEGIN -- CustomerController.someMethod");

I am expecting to see in Swagger a place where I can input some text as a request body but instead I see this

enter image description here

5 Answers

Add @ApiProperty()

export class User{

 @ApiProperty()
  name:string
 
}

So it sounds like there's a few things going on here. The Swagger UI is a helper tool for sending in requests, but to do that it needs to know the shape of the request body. any is not good enough. If you're looking for a tool that allows you to send in anything, curl or postman are you best bets (at least for free).

Nest has a Swagger plugin that will read through your Typescript code and decorate your types and method accordingly, but you have to opt in to enable it. Otherwise, you need to use the decorators from the @nestjs/swagger package to tell Swagger what types are expected in and out of the methods.

So long as the type that corresponds to @Body() has swagger decorators or you enable the swagger plugin and have a valid class, the swagger UI should show up as expected, but with the above and using type any it won't do you any good.

My endpoint accepts unknown key/value data and I was having the same problem (I tried any, unknown, Record<string, any>, object, {}). Finally @Body() data: Map<string, any> worked for me.

try it like this:

@ApiBody({description: "body:any someMethod"})
@Post('lookup')
async someMethod(@Body() body:any){
console.log("BEGIN -- CustomerController.someMethod");
}

Swagger is unable to interpret your code. It is not an issue with your code. If your goal is to test your API for the UI team to use and not a comprehensive swagger documentation, then I found it easiest to just use Postman. Try hitting your API using Postman.

Related