I am currently working in a code base where for every REST API response they use a java class like below
{
Object payload;
List<Error> errors;
String responseStatus;
}
The problem is, when we refer to the swagger documentation of the REST APIs it shows a json structure like below.
{
"payload":{},
"errors": [
{
"errMsg":"",
"errCode": ""
}
],
"responseStatus":""
}
So the response will have payload if response is success, error list in case of errors and response status set to success or failure respectively.
EDIT: I just want to mention that I cannot change the response payload to any thing else, as it is being used in more than 1000 APIs and is distributed into different services.
Is there any way to improve at least the swagger documentation, without changing the Response Object in java, because that ship has sailed a long time ago.
Here is an example from the Swagger documentation
paths:
/users/{id}:
get:
summary: Gets a user by ID.
response:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'401':
$ref: '#/components/responses/Unauthorized'
'404':
$ref: '#/components/responses/NotFound'
# Descriptions of common components
components:
responses:
NotFound:
description: The specified resource was not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Unauthorized:
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
schemas:
# Schema for error response body
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message
# Schema for the User response
User:
type: object
properties:
# Add properties for the User object
# ...
you can use ResponseEntity<? extends Response> return type in your methods. so that if response is success, both of them returned, as well as response is error.
public ResponseEntity<? extends ResponseDto> foo(RequestDto request){
if(success){
return new ResponseEntity<>(new SuccessResponse(Enum.SuccessResponse.getMessage,200,dto),HttpStatus.OK);
}
return new ResponseEntity<>(new ErrorResponse(Enum.ErrorResponse.getMessage,400),HttpStatus.BAD_REQUEST);
}