Home > front end >  Is GenericResponse best practice for rest API?
Is GenericResponse best practice for rest API?

Time:05-20

We are designing new rest api and I am conflict which one of the below solution is the best practice/approach for rest API response(the rest APIs are implemented using spring boot) and what is the pros and cons for each one of them ?

Solution Tow is about returning data object without any using any envelope ex ResponseEntity<MyClass>

Solution Tow is about having GenericResponse ex:

public class GenericResponse {

private int code;

private APiError error;

private Object data;}

CodePudding user response:

In my opinion, if the client needs to show appropriate error message based on backend processing then "Generic response" format with error and data object is helpful. Otherwise only data response with proper status code (200/400/404/403) will help to keep the code simple.

CodePudding user response:

I would suggest using a GenericResponse Model. One of the Pros of using is definitely better maintainability.

Following approach is What I like more and I feel it's more standard

     public abstract class BaseResponse {
      private String ResponseCode;
     //Contains common fields Ex. Tracking fields like correlationId, RequestId
     }

     public class ErrorResponse extends BaseResponse {
     //Error Fields
    }

    public class Response extends ErrorResponse {
    //Response 
    }

In future, if you're need of adding a new Response for endpoint, you can just extend the ErrorResponse(Common error response structure).

  • Related