Best practice to send response in spring boot

前端 未结 2 1774
执念已碎
执念已碎 2021-01-01 04:46

I\'m coding REST Api-s in spring boot. I want to make sure that my code is readable to front-end developers using swagger API development tool (Swagger). For example

2条回答
  •  佛祖请我去吃肉
    2021-01-01 05:43

    First of all you should follow the best practices of a RESTful API . Don't use verbs, instead use nouns as URL.So instead of @GetMapping("/getOne") , you can write it as @GetMapping("/branch/{id}") . You can refer this blog https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

    @2ndly , Don't return a generic type as ? , instead you can user the specific type , here as Branch and do central exception handling . The following code snippet can help you :

    @GetMapping("/branch/{id}")
    public ResponseEntity getBranch(@Pathvariable String id) {
    {
        Branch branch = branchService.getOne(id);
    
        if(branch == null) {
             throw new RecordNotFoundException("Invalid Branch id : " + id);
        }
        return new ResponseEntity(branch, HttpStatus.OK);
    }
    

    RecordNotFoundException.java

    @ResponseStatus(HttpStatus.NOT_FOUND)
    public class RecordNotFoundException extends RuntimeException
    {
        public RecordNotFoundException(String exception) {
            super(exception);
        }
    }
    

    CustomExceptionHandler.java

    @ControllerAdvice
    public class CustomExceptionHandler extends ResponseEntityExceptionHandler
    {
        @ExceptionHandler(Exception.class)
        public final ResponseEntity handleAllExceptions(Exception ex, WebRequest request) {
            List details = new ArrayList<>();
            details.add(ex.getLocalizedMessage());
            ErrorResponse error = new ErrorResponse("Server Error", details);
            return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    
        @ExceptionHandler(RecordNotFoundException.class)
        public final ResponseEntity handleRecordNotFoundException(RecordNotFoundException ex, WebRequest request) {
            List details = new ArrayList<>();
            details.add(ex.getLocalizedMessage());
            ErrorResponse error = new ErrorResponse("Record Not Found", details);
            return new ResponseEntity(error, HttpStatus.NOT_FOUND);
        }
    }
    
    
    

    ErrorResponse.java

    public class ErrorResponse
    {
        public ErrorResponse(String message, List details) {
            super();
            this.message = message;
            this.details = details;
        }
    
        private String message;
    
        private List details;
    
        //Getter and setters
    }
    

    The above class handles multiple exceptions including RecordNotFoundException and you can also customize for payload validations too.

    Test Cases :

    1) HTTP GET /branch/1 [VALID]
    
    HTTP Status : 200
    
    {
        "id": 1,
        "name": "Branch 1",
        ...
    }
    2) HTTP GET /branch/23 [INVALID]
    
    HTTP Status : 404
    
    {
        "message": "Record Not Found",
        "details": [
            "Invalid Branch id : 23"
        ]
    }
    

    提交回复
    热议问题