Home > OS >  How to define the response body object, in a NestJs-generated Swagger document?
How to define the response body object, in a NestJs-generated Swagger document?

Time:01-29

I'm Using NestJs and its Swagger plugin to auto-generate documentation of my API.

Problem is, I cant figure out how to make the response schema appear in the documentation. In my GET routes, all i get is "Code 200", with no data structure.

I have a typical setup, where a controller method uses a corresponding service method, which in turn uses a TypeOrm repository. For example:

@Get()
 findAll() {    
   return this.usersService.findAll();
}

I tried using the @ApiResponse decorator, but didn't really see any way to make it serve this purpose. Also, creating a user.dto.ts and making it the return type of the controller route didn't do any good.

Eventually, this is what i get in the Swagger:

swagger

How can i define the response body schema?

CodePudding user response:

You can use the type and isArray properties in conjunction with the ApiResponse family of decorators. For example:

@ApiOkResponse({
    description: 'The user records',
    type: User,
    isArray: true
})
@Get()
 findAll() {    
   return this.usersService.findAll();
}

Additionally, consider using the Swagger CLI plugin to help you have these decorators applied automatically during build time instead of you having to keep everything in sync manually.

  •  Tags:  
  • Related