SoFunction
Updated on 2025-03-02

Detailed introduction to Java backend API interface development specifications

In the field of software development, especiallyJavaIn back-end development, the design and development of API interfaces are the bridge connecting front-end and back-end services. The quality and specification directly affect the system's maintainability, scalability and user experience. An excellent oneAPI interface designCertain specifications should be followed to ensure the consistency, security and ease of use of the interface. This article will introduce the development specifications of the Java back-end API interface in detail from the aspects of naming specifications, receiving parameter specifications, parameter verification, receiving method specifications, exception class processing, unified return format, idempotence, etc., and explain them through actual code examples.

1. Naming Specifications

1.1 Interface Naming

  • RESTful style:followRESTful Principle,useHTTP MethodsGETPOSTPUTDELETEetc.) to indicate the operation of the resource. The interface URL should intuitively reflect resources and their operations, such as/usersGet the user list,/users/{id}Gets the user with the specified ID.
  • Verb + noun:existURLTry to avoid using verbs, butHTTP MethodsIndicates operation. However, in specific scenarios, such as complex queries,URLAdd verb descriptive query parameters, such as/users/search
  • Hump ​​naming: The interface name and resource name are named lowercase camel (lowerCamelCase),likegetUserById

1.2 Variable Naming

  • Attribute naming:JavaThe attribute names are named in lowercase camel, such asuserIduserName
  • Constant naming: all capitals, separated by underscores, such asMAX_USERS

2. Receive parameter specifications

2.1 Body

forPOSTPUTIf you want to modify the server status, it is recommended to use it.JSON formatAs the request body.
The fields in the request body should correspond to the database table or business object attributes to ensure data consistency.

{  
  "userId": 1,  
  "userName": "JohnDoe",  
  "email": "johndoe@"  
}

2.2 Query Parameters

forGETRequest, use query parameters to pass non-sensitive information, such as paging parameters, sorting conditions, etc.
Query parameter names also use lowercase camel nomenclature, such aspage=1&size=10

3. Parameter verification

Front-end verification is combined with back-end verification: Although the front-end should perform basic verification, the back-end must implement comprehensive verification logic to prevent malicious requests.
Use the verification framework:Hibernate Validator, simplify the verification logic through annotation.

public class UserDTO {  
    @NotNull(message = "User ID cannot be empty")  
    private Long userId;  
  
    @NotBlank(message = "Username cannot be empty")  
    @Size(min = 3, max = 20, message = "The username must be between 3 and 20 characters")  
    private String userName;  
  
    // Other fields and verification annotations...}

4. Standardization of reception methods

Select the reception method according to the content type:application/jsonType of data, use@RequestBody annotationReceive the request body; forapplication/x-www-form-urlencodedormultipart/form-data, it may need to be resolved manually or used@RequestParametc.

Unified use annotations: use as much as possibleSpring MVCThe notes provided (e.g.@PathVariable@RequestParam@RequestBody) to simplify code and enhance readability.

V. Exception class handling

Custom exception class: define a series of custom exception classes according to project requirements, such asBusinessExceptionSystemExceptionetc. to distinguish between business exceptions and system exceptions.
Global exception handling: Use@ControllerAdviceor@RestControllerAdviceThe annotated class captures and handles exceptions globally and returns the format uniformly.

@RestControllerAdvice  
public class GlobalExceptionHandler {  
  
    @ExceptionHandler(value = )  
    public ResponseEntity<Object> handleBusinessException(BusinessException ex) {  
        // Construct the return body, including error codes, error messages, etc.        Map<String, Object> body = new HashMap<>();  
        ("code", ());  
        ("message", ());  
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);  
    }  
  
    // Other exception handling methods...}

6. Definition of unified return format

The unified return format usually contains the following key parts:

  • Status Code (Code): Indicates the result status of the request processing, such as success, failure, unauthorized, etc. The status code can be an HTTP status code or a custom service status code. Custom status codes can describe the error types of business logic more precisely.
  • Message: A text description corresponding to the status code, used to provide the caller with more context information about the request result.
  • Data: The specific data returned when the request is successful. If the request fails, this section may be empty, null, or contains some error message.
  • Timestamp (optional): Record the time of response generation, which helps the client to perform cache control or logging.
  • Other metadata (optional): such as paging information (current page number, number of pages, total number of records, etc.),Request IDetc. Decide whether it is necessary to include it according to specific needs.

ExampleThe following is a unified return formatJSONExample:

{  
  "code": 200, // Custom or HTTP status code  "message": "The operation is successful",  
  "data": {  
    // The data returned when the request is successful    "id": 1,  
    "name": "John Doe",  
    "email": "johndoe@"  
  },  
  "timestamp": "2023-10-01T12:00:00Z", // Optional  "requestId": "abc123" // Optional for tracking requests}

If the request fails, the response might look like this:

{  
  "code": 404, // Custom or HTTP status code  "message": "User not found",  
  "data": null, // Or contains error message  "timestamp": "2023-10-01T12:00:00Z", // Optional  "requestId": "def456" // Optional}

When implementing a unified return format, one or more basic response classes can be defined (as mentioned earlier).BaseResponseclass), and use these classes in the controller to construct the response. In addition, it can be usedAOP (System-oriented Programming)to intercept responses globally, automatically wrap into a unified format to reduce the need to repeatedly write the same code in each controller method.

7. Idempotence of API interfaces

API InterfaceIdepotency ofIdempotence)yesHTTP protocolAn important concept inRESTful APIIt is especially important in design. Impotence refers to an operation that has the same result no matter how many times it is performed, and will not have side effects on the system state (except those specifically designed for side effects, such as logging).

existAPIIn interface design, idempotence is mainly focused onHTTPThe use of methods and how the interface design itself ensures the uniqueness of operations and the consistency of results.

HTTP method and idempotence

HTTP protocolA variety of methods are defined, each with its specific semantic and idempotent properties:

  • GETIdepotential method. Used to request resources, the resources on the server will not be modified, so the result will be the same no matter how many times it is called.
  • POSTNon-idempotent method. Used to submit data to the server for processing, each call may produce different results (for example, creating a new resource).
  • PUTIdepotential method(existRESTfulunder principle). Used to update resources, if the same request body is used multiple times to perform the same resourcePUT operation, then the state of the resource should be the same. But please note that there may be differences in actual implementations, because the server may decide whether to update resources based on the specific content of the request.
  • DELETEIdepotential method(In most cases). Used to delete the resource, if the resource has been deleted, then execute againDELETE operationThere is usually no impact (although some servers may return different status codes to indicate whether the resource already exists).
  • PATCH: Non-idempotent method. Used to make partial modifications to the resource, and is not idempotent because the contents of each modification may be different.

Implementing the idempotence of API interfacesTo beAPI InterfaceTo achieve idempotence, the following strategies can be considered:

  • useIdepotent HTTP method:PreferredGETPUTandDELETEMethod to designAPI Interface, because they are easier to achieve idempotence.
  • Unique identifier: For non-idempotent methods (e.g.POST), can be included in the request by including a unique identifier (e.g.Request ID, tokens, etc.) to ensure the idempotence of the operation. The server can check this identifier and if the same request has been processed before, it can directly return the previous result instead of performing the operation again.
  • Status check: Before performing an operation, check the current status of the resource. If the resource is already in the desired state, a successful response can be returned directly without performing any action.
  • Optimistic lock: When updating resources, use optimistic locking mechanisms such as version numbers or timestamps to ensure the idempotence of operations. If the current version of the resource does not match the version specified in the request, the update request is denied.
  • Deduplication queue: Send the request to the deduplication queue. The queue checks whether the request has been processed before sending the request to the actual processing service.

Things to note

Idepotency does not mean that there are no side effects on the operation. For example,GET RequestLogs may be logged or caches are updated, but these side effects do not change the core state of the resource.

In designAPI InterfaceWhen , it should be clearly stated which operations are idempotent and explain this in the documentation.

Ideopotence implementations may require additional overhead, such as checkingRequest ID, maintain version number, etc. Therefore, in designAPI InterfaceWhen , the necessity of idempotence and the complexity of implementation should be weighed according to actual needs.

summary

By following the aboveJavarear endAPI InterfaceDeveloping specifications can significantly improve the readability, maintainability and security of code. Practices such as naming specifications, receiving parameter specifications, parameter verification, receiving method specifications, exception class processing, and unified return formats not only help the collaboration between team members, but also provide front-end developers with clear and consistent interface documents. In addition, security considerations are also an important part that cannot be ignored, which is directly related to the stability of the system and the security of user data.

This is the end of this article about Java backend API interface development specifications. For more related contents of Java API interface development specifications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!