How to specify a generic class type for a Swagger API response

I have about 40 APIs that have a similar basic response structure as follows:

{ "lastAccessed": "2015-30-08:14:21:45T", "createdOn": "2015-30-07:09:04:10T", "lastModified": "2015-30-08:14:21:45T", "isReadOnly": "false", "usersAllowed" : ["Tim", "Matt", "Christine"]; "noOfEntries": 1, "object": [ "ObjectA": { //here object A has its own model } ] } 

So, I have a base response class that accepts a generic type T as follows:

 public class Response<T> { @ApiModelProperty(value="Last time accessed") private String lastAccessed; @ApiModelProperty(value="Time when Created ") private String createdOn; private String lastModified; @ApiModelProperty(value="Created on") private boolean isReadOnly; @ApiModelProperty(value="Users that has access to the object.") private List<String> usersAllowed; private int noOfEntries; private T object; //getters and setters } 

So, for API A, which returns an Object of type with its own fields, I return a Response as an API response in the controller:

  public class A { @ApiModelProperty(value="Name") private String name; @ApiModelProperty(value="OID") private String id; //getters and setters } 

In the controller: Response data = new Response (); ResponseEntity response = new ResponseEntity <> (data, HttpStatus.OK);

Is there a way in swagger I can recursively specify the model of the response object? For example, I could write the annotation @ApiOperation (response = Response.class), but it would not have a model for A.

+5
source share
2 answers

I know this is an old post, but for someone else looking for the answer to this question:

This can be done for List , Set and Map objects, but any class of a class with common types will be ignored. If you use any of these three, you specify them in the responseContainer field and your display type in the response field.

 @ApiResponse(code = 200, responseContainer="List", respone=java.lang.String.class) 
+2
source

I use swagger 2 and after fixing this problem for me.

Remove the response property "from both @ApiResponse and @ApiOperation . Then swagger will automatically generate a response class for 200 OK from the method stubs (regardless of whether or not the generics are in the response class).

 @ApiOperation(value = "what your operation does") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success message") }) 
0
source

Source: https://habr.com/ru/post/1234940/


All Articles