Saturday, April 4, 2020

Spring Boot API - Return Success Response

How To Return Success Response In Spring Boot API

In this post i am going to demonstrate that how we should return success responce in Spring boot rest API.
@RestController
@RequestMapping("/api/user")
@Api(value = "user", description = "Rest API to get user", tags = "User API")
public class UserController {

 @Autowired
 private UserService userService;

 @RequestMapping(value = "/users", method = RequestMethod.POST, produces = "application/json")
 @ApiOperation(value = "Getting all user list", response = APISuccessResponse.class)
 @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
   @ApiResponse(code = 401, message = "You are not authorized access the resource"),
   @ApiResponse(code = 404, message = "The resource not found") })
 public ResponseEntity<APISuccessResponse> getUsers() {
  APISuccessResponse responce = null;
  List<User> userList = null;
  try {
   userList = userService.getUsers();
   responce = new APISuccessResponse(HttpStatus.OK, "get Users List", userList);
  } catch (Exception e) {
   responce = new APISuccessResponse(HttpStatus.OK, "get Users List", userList);
  }
  return new ResponseEntity<>(responce, HttpStatus.OK);
 }

}
Output: API Response
{
  "status": "OK",
  "message": "get Users List",
  "responseStatus": "Success",
  "statusCode": 0,
  "responseCount": 2,
  "responceObject": [
    {
      "id": 1,
      "firstName": "Amit",
      "lastName": "Kumar",
      "email": "amit.kumar@abc.com",
      "mobile": "9999993690",
      "address": {
        "houseNo": "123",
        "state": "New Delhi",
        "city": "Delhi",
        "pinCode": "110068"
      }
    },
    {
      "id": 2,
      "firstName": "Test",
      "lastName": "Pathak",
      "email": "tset.123@abc.com",
      "mobile": "996633221155",
      "address": {
        "houseNo": "963",
        "state": "Maharast",
        "city": "Mumbai",
        "pinCode": "258963"
      }
    }
  ]
}
APISuccessResponse.java
package com.example.user.response;

import java.util.List;

import org.springframework.http.HttpStatus;

public class APISuccessResponse extends APIResponse {

 /*
  * Response object can be an array of object or single object
  */
 Object responceObject;

 public APISuccessResponse(HttpStatus status) {
  super(status);
  setResponseStatus("Success");
  setStatusCode(0);
 }

 public APISuccessResponse(HttpStatus status, String message, Object responceObject) {
  super(status, message);
  this.responceObject = responceObject;
  setResponseStatus("Success");
  setStatusCode(0);
  setResponseCount(responceObject instanceof List<?> ? ((List<?>) responceObject).size() : 1);
 }

 public APISuccessResponse(HttpStatus status, Object responceObject) {
  super(status);
  this.setResponceObject(responceObject);
 }

 public Object getResponceObject() {
  return responceObject;
 }

 public void setResponceObject(Object responceObject) {
  this.responceObject = responceObject;
 }

}

APIResponse.java
package com.example.user.response;

import org.springframework.http.HttpStatus;

public class APIResponse {

 /*
  * Http Status code of response
  */
 private HttpStatus status;

 /*
  * Responce Message
  */
 private String message;

 /*
  * Response Status string:Success or Failure
  */
 private String responseStatus;

 /*
  * Response Status code
  */
 private int statusCode;

 /*
  * Number of returned objects
  */
 private int responseCount;

 public APIResponse(HttpStatus status) {
  this.status = status;
 }

 public APIResponse(HttpStatus status, String message) {
  this(status);
  this.message = message;
 }

 /*
  * this is required while deserializing test response to create object
  */
 public APIResponse() {

 }

 public HttpStatus getStatus() {
  return status;
 }

 public void setStatus(HttpStatus status) {
  this.status = status;
 }

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }

 public String getResponseStatus() {
  return responseStatus;
 }

 public void setResponseStatus(String responseStatus) {
  this.responseStatus = responseStatus;
 }

 public int getStatusCode() {
  return statusCode;
 }

 public void setStatusCode(int statusCode) {
  this.statusCode = statusCode;
 }

 public int getResponseCount() {
  return responseCount;
 }

 public void setResponseCount(int responseCount) {
  this.responseCount = responseCount;
 }

}

APIErrorResponse.java
package com.example.user.response;

import java.time.LocalDateTime;
import org.springframework.http.HttpStatus;

public class APIErrorResponse extends APIResponse {

 private LocalDateTime timestamp;

 public APIErrorResponse(HttpStatus status, String message, int statusCode) {
  super(status, message);
  this.timestamp = LocalDateTime.now();
  setStatusCode(statusCode);
  setResponseStatus("error");
  setResponseCount(0);

 }

}

1 comment:

  1. Hi,
    Your content is very good.
    Is there any topics about Python , Haddop or sql?

    ReplyDelete