Home > Back-end >  Is using Object class to represent all kind of Json payload a good idea
Is using Object class to represent all kind of Json payload a good idea

Time:12-16

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.

  1. Is it a good practice to use same json structure for error and success?
  2. Is there any way to improve swagger documentation, so that I can show what the response payload json will look like for a particular API response.

CodePudding user response:

  1. It is not a good practice to use the same json structure for error and success responses.
  2. Yes, if you have control over the Swagger definitions, you can specify different responses per response code.

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
          # ...

CodePudding user response:

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);
}
  • Related