简体   繁体   中英

How to define different response models for different status codes in openApi / springfox-swagger2

Given the following REST method with springfox-swagger2 annotations:

@GetMapping(value = "/access", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "check access allowed")
@ApiResponses({
        @ApiResponse(code = 200, message = "okay, there you go", response = AccessResponse.class),
        @ApiResponse(code = 204, message = "I got nothing for you", response = Void.class)
})
public ResponseEntity<AccessResponse> access() {

    if (!isAccessEnabled()) {
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
    AccessResponse response = new AccessResponse("some data");
    return ResponseEntity.ok(response);
}

Notice that there are two states that this method can return:

  1. a response of type AccessResponse
  2. a http 204 - no content response

I want to generate a swagger api documentation that reflects the different response models (AccessResponse vs. Void). Inside the @ApiResponse Annotation I explicitly tell springfox-swagger2 to use different models for each state. Unfortunately the generated swagger api doc json refers only to the AccessResponse model for both http 200 and 204:

 "responses":{ "200":{ "description":"okay, there you go", "schema":{"$ref":"#/definitions/AccessResponse"} }, "204":{ "description":"I got nothing for you", "schema":{"$ref":"#/definitions/AccessResponse"} } } 

Am I missing something? Is there a way to tell swagger to render two different models for each HTTP/ok status code?

I've changed the return type of the method - removing the generic type:

public ResponseEntity access()

which results in a better (but not perfect) model description:

 "204":{ "description": "I got nothing for you", "schema":{"type":"object"} } 

Swagger UI renders this to

在此输入图像描述

I like that it displays the empty body now. However, the statusCode is a bit irritating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM