Writing in the front
It is well known that the standard HTTP interface consists of request mode, request parameters, request address, response data, and uniform exception interception. So this paper starts from these five aspects, standardize the interface, reduce the time of the front and back end joint adjustment! Standardize the backend interface based on the REST of the style, the REST of the instructions you can refer to this article: www.ruanyifeng.com/blog/2011/0…
Request way
The HTTP request mode represents the operation of resources. When defining an interface, you need to select an appropriate request mode based on the service. There are five common HTTP requests:
GET: queries one or more data from the server. 2. PUT: updates a full server resource. 3Copy the code
Request the address
The requested address is the URL, and we’ve already used HTTP requests to represent actions to manipulate resources, so we shouldn’t have any actions in the URL.
Imagine a scenario that designs an interface to manipulate a company’s departments and employees. Here is an example of a canonical URL:
Query examples
Query all departments GET /department 2. Query department information by department ID. GET /department/{id} 3. Query employees by department id and employee ID GET/Account /{id}/department/{id} 4. GET /department? currentPage=1&pageSize=10Copy the code
The new sample
1. Add department POST/Department 2. Add employee POST/AccountCopy the code
Update the sample
Update all information about the department except the primary key. PUT /department 2. Update the department name PUT /departmentCopy the code
Remove the sample
DELETE department DELETE /department/{id} 1. DELETE /account/{name}/department/{id}Copy the code
Request parameters
Additions and Updates
When the front end calls the new and update interface, it passes an object. Therefore, when the number of request parameters is equal to 1, it can directly receive this parameter. When the number of request parameters is greater than 1, it needs to create a DTO object to receive it. For the convenience of interface callers, we write detailed Swagger comments on objects and properties (what the class does, what the value does, formatting rules, examples).
For examples, see the following code, which saves space by eliminating getters and setters:
@APIModel (" Department object ") public Class DepartmentDto {@APIModelProperty (value =" department ID,example =" 1") private Integer ID; @apiModel (" Department object ") public Class DepartmentDto {@APIModelProperty (value =" department ID,example =" 1") private Integer ID; @apiModelProperty (value =" department name ",example =" department name ") private String name; }Copy the code
Query and Delete
Query and delete cannot create a new object to accept, so only define swagger annotations at the interface (what this value does, formatting rules, examples) and describe the interface’s role, return of error codes, return of success;
@apiOperation (value = "Query department information based on department ID ", Notes = "Query department information according to department ID ") @getMapping ("/{id}") @apiresponses (value = {@apiResponse (code = 200, message =" Query succeeded "), @ApiResponse(code = 500, Message = "systemError<br>" + "lengthError<br>")}) @apiimplICITParam (name = "id",value = "department ID ",example = "1") Public Result<DepartmentDto> getList(@pathVariable ("id") String ID){return result. success(" query successful ",new DepartmentDto()); }Copy the code
The response data
When the front and back ends are separated, we need to define a uniform return data format and also globally intercept exceptions.
Uniformly returns data objects
The returned object should contain the following fields: CODE: Http status code, Message: error code, and data: returned data.
- These three fields should be annotated with swagger;
- Privatize constructors and create static build methods for quick retrieval;
- You can override the toString method for logging purposes;
@apiModel ("HTTP ") public class Result<T> {@apiModelProperty ("HTTP ") private String code; @APIModelProperty (" Return error code ") private String message; @apiModelProperty (" return data ") private T data; private static final String success = HttpStatus.OK.value()+""; private static final String fail = HttpStatus.INTERNAL_SERVER_ERROR.value()+""; private Result(String code, String message, T t) { this.code = code; this.message = message; this.data = t; } public static Result success(String message,Object data){ return new Result(success,message,data); }}Copy the code
Global exception interception
Abnormal code
Create an enumeration of exception codes to facilitate storage management and return exceptions; The code contains no and code fields. Code is used to return to the front end. No can be generated by its own service rules and printed in logs for troubleshooting in the future.
public enum ExceptionEnum { SYSTEM_ERROR("010-1000000","systemError"); private final String no; private final String code; ExceptionEnum(String no, String code) { this.no = no; this.code = code; } public String getNo() { return no; } public String getCode() { return code; } @Override public String toString() { return this.code; }}Copy the code
Global exception class
Create a global exception code enumeration, use exception code to manage exceptions;
public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; private ExceptionEnum exceptionEnum; private Object data ; /** * Instantiates a new Iam base exception. */ public BusinessException() { } public BusinessException(ExceptionEnum exceptionEnum) { super(exceptionEnum.getCode()); this.exceptionEnum = exceptionEnum; }}Copy the code
Abnormal intercept
Global exception interception, return the error code returned by the service if it is a service exception; If it is an internal system error such as null pointer exception and so on, then throw system exception (such processing is to unify the return, convenient front-end processing, null pointer exception is just an example, if you really throw null pointer exception should think about why not empty!!)
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public Result exception(Exception e) { return Result.fail(ExceptionEnum.SYSTEM_ERROR.getCode()); } @ExceptionHandler(BusinessException.class) public Result exception(BusinessException e) { return Result.fail(e.getCode()); }}Copy the code
Example interface specifications
Examples of GET and DELETE interfaces
Add @APIOperation Description This method adds @APIResponses to describe successful and failed messages, status codes for Http requests add @APIIMPLICITParam to describe incoming parameters, format limits, and default values
@apiOperation (value = "Query department information based on department ID ", Notes = "Query department information according to department ID ") @getMapping ("/{id}") @apiresponses (value = {@apiResponse (code = 200, message =" Query succeeded "), @ApiResponse(code = 500, Message = "systemError<br>" + "lengthError<br>")}) @apiimplICITParam (name = "id",value = "department ID ",example = "1") Public Result<DepartmentDto> getList(@pathVariable ("id") String ID){return result. success(" query successful ",new DepartmentDto()); }Copy the code
Examples of POST, PUT, and PATCH interfaces
@apiOperation (value = "New department information ", notes =" new department information ") @postmapping ("/") @apiresponse (value = {@apiResponse (code = 200, Message = "added successfully "), @apiResponse (code = 500, Message = "systemError<br>" + "lengthError<br>")}) public Result add(@requestBody DepartmentDto dto) Result.success(" add success ",null); }Copy the code
The API documentation
According to the above code, the resulting Swagger document is shown as follows:
code
The sample code has been uploaded to www.fizzed.top/archives/ji…
Write in the last
Welcome everyone to pay attention to my public number [there is a base of the program ape], exchange Java, big data, the corresponding brain map will be put in the public number. Point attention, do not get lost!!
Blog: www.fizzed.top