Swagger: How to provide JSON response schema?

Created on 27 Nov 2017  路  7Comments  路  Source: nestjs/swagger

@ApiResponse({ status: 201, description: 'Creates new player object.' })

Only (I think) allows for the status and description (plus some other fields). How can I implicitly or explicitly (^^) force SwaggerModule to show the JSON that will be returned?

Most helpful comment

But that's the input? For POST I use @ApiModelProperty in the .dto files. I mean the output from the API. My API is connected via TypeORM to PostgreSQL.

  @Post()
  @UsePipes(new ValidationPipe())
  @ApiResponse({ status: 201, type: User, description: 'Creates new user object.' })
  async create (@Body() createUserDto: CreateUserDto): Promise<User> {
    const user = await this.userService.create(createUserDto)
    return this.userService.findOne(user.id)
  }

In Swagger UI I can see that CreateUserDto is used as a request body, that's great. Should I create a similar class for output? Or is it somehow possible to derive the output from the User (TypeORM) object?

All 7 comments

Hi @galkowskit,
Use type property. Pass there a class with properties annotated with @ApiModelProperty()

But that's the input? For POST I use @ApiModelProperty in the .dto files. I mean the output from the API. My API is connected via TypeORM to PostgreSQL.

  @Post()
  @UsePipes(new ValidationPipe())
  @ApiResponse({ status: 201, type: User, description: 'Creates new user object.' })
  async create (@Body() createUserDto: CreateUserDto): Promise<User> {
    const user = await this.userService.create(createUserDto)
    return this.userService.findOne(user.id)
  }

In Swagger UI I can see that CreateUserDto is used as a request body, that's great. Should I create a similar class for output? Or is it somehow possible to derive the output from the User (TypeORM) object?

You can use @ApiModelProperty() on the User properties as well.

You can use @ApiModelProperty() on the User properties as well.

@kamilmysliwiec This doesn't work, the response type from a controller method is not used for Swagger, only the parameters are.

You can verify this by running the Cats example with the @ApiModelProperty() set on the Cat class.

looks like type is not accepting arrays.
For example if the endpoint returns Post[] if you use @ApiResponse({status: 200, type: Post[], description: 'Returns Posts'}) ts will not compile for that you should use isArray

@ApiResponse({status: 200, type: Post, isArray: true, description: 'Returns Posts'})

The decorator is now @ApiResponseModelPropery(...) called, i guess!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings