Unable to represent empty response body (HTTP 204)
See original GitHub issueDescription
In many of the APIs that I’m developing, we have cases where we reporting success does not require a response body (ex: deleting an entity, there is nothing to say if it works since the entity is gone.)
Unfortunately, it appears that swagger annotations cannot (currently) handle this.
Example:
Both this:
@ApiResponses({
@ApiResponse(code = 204, message = "identity deleted sucessfully",
response = void.class),
@ApiResponse(code = 404, message = "no such user or identity")
})
and this:
@ApiResponses({
@ApiResponse(code = 204, message = "identity deleted sucessfully"),
@ApiResponse(code = 404, message = "no such user or identity")
})
produce the following spec (irrelevant portions omitted):
"responses" : {
"204" : {
"description" : "identity deleted sucessfully",
"schema" : {
"type" : "object"
}
},
"404" : {
"description" : "no such user or identity"
}
}
It seems clear to me that this behavior is unarguably wrong, as void
has a very well-understood meaning of, well… nothing. As it stands, ReDoc, swagger-ui, et al. will display the 204 response as though it will produce JSON consisting of {}
(an empty object). This is incorrect.
Suggested resolution
When @ApiResponse#response
is Void.class
or void.class
, omit the schema
property in the resulting spec.
Additionally, consider adding special case handling to 204, since its meaning according to the HTTP spec strongly implies that there should be no response. (IIRC 404 already works like this unless you specify a response
property for it.)
Workaround
None. Document incorrect behavior and warn your API documentation’s users.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:14
- Comments:11 (4 by maintainers)
Top GitHub Comments
Found the workaround, As the default behavior of @ApiOperation is to return the return type of method, so for every status, the return type of method will be returned. If you want to send empty response then write
@ApiResponse(code = 204, message = "No User found for that Id",response = Object.class)
And in the SwaggerConfig write
So whenever an Object.class is returned swagger will automatically convert it into Void.class
I may be a bit late to the party, but the following workaround does the trick for me, in case anyone with the same issue is stumbling across this issue:
@ApiResponse(code = 204, message = "identity deleted sucessfully", response = Object.class)
For me the problem was, that the @ApiResponse inherited the response type from @ApiOperation. So I had to override it with something empty. “Void.class” would seem like the right choice, but this is the default value, thus leading to the inheritance from @ApiOperation.