Bal Vikash Sharma
Bal Vikash Sharma

Reputation: 95

How to pass Class of a type in swagger ApiOperation annotation response variable

In swagger I want to show the response which is a generic class. But it will not take the type of the class for the response.

@ApiOperation(value = "Get user name", response = ResponseWrapper.class)
// but I want to pass

@ApiOperation(value = "Get user name", response = ResponseWrapper<UserModel>.class)
// here I am getting error 
// how can I pass ResponseWrapper<UserModel>.class in the response variable

// In swagger response example body will be shown like :
/*
{
  "errors": [
    {
      "errorCode": "string",
      "message": "string"
    }
  ],
  "id": "string",
  "metadata": {},
  "response": {},
  "responsetime": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
  "version": "string"
}

But I want my response example body like this : 

{
  "errors": [
    {
      "errorCode": "string",
      "message": "string"
    }
  ],
  "id": "string",
  "metadata": {},
  "response": {
    "userName" : "string"
  },
  "responsetime": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
  "version": "string"
}
*/

The example code not having the ResponseWrapper of generic type but I want to pass Response wrapper of generic type.

Upvotes: 3

Views: 5550

Answers (2)

Bal Vikash Sharma
Bal Vikash Sharma

Reputation: 95

I have gone through the documentation. There is no way that we can pass generic "type" class to the parameter of @ApiOperation i.e. "response".

In my case I am returning ResponseEntity but with the help of advice I want I got the ResponseEntity and map it to the ResponseWrapper class.

But I need to show the user in Swagger UI that the response example is the ResponseWrapper object. So, I wanted to provide the ResponseWrapper class with its type in @ApiOperation "response" variable.

To do this I have to change the return type from ResponseEntity to ResponseWrapper. Otherwise there is no way. And type resolver will come into picture if your response is like ResponseWrapper>.

Upvotes: 0

Abaddon666
Abaddon666

Reputation: 1623

The only way to do this that I have found so far is to create an explicitly typed class implementing/extending your generic:

public class UserResponse extends ResponseWrapper<UserModel>{
}

This allows you to do

@ApiOperation(value = "Get user name", response = UserResponse .class)

Upvotes: 2

Related Questions