RESTful is a popular interface path design specification. It is based on HTTP and generally defined in JSON mode. The resource actions of corresponding interfaces are defined using different Httpmethods, such as Add (POST), DELETE (DELETE), update (PUT, PATCH), and query (GET).
Path design
In the RESTful design specification, each interface is considered a resource request, so let’s look at the API path design for each resource type.
Precautions for path design are as follows:
- Use plural resource names
- Resource names use nouns
- The path contains no special characters
- Avoid multilevel urls
New resources
Request way | Sample path |
---|---|
POST | api.yuqiyu.com/v1/users |
The interface for new resources is defined in POST mode, and the data for new resources is transmitted in RequestBody mode, as shown below:
curl -X POST -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users -d '{" name ", "heng yu young", "age" : 25, "address" : "the shandong jinan"}'
Copy the code
After a new resource is added, the interface should return the unique identifier of the resource, such as the primary key value.
{
"id" : 1."name" : "Heng Yu Youth"
}
Copy the code
Other data interfaces that operate on the resource through the unique identity returned.
Delete the resource
Request way | Sample path | note |
---|---|---|
DELETE | api.yuqiyu.com/v1/users | Deleting Resources in Batches |
DELETE | Api.yuqiyu.com/v1/users/ {I… | Deleting a Single Resource |
To DELETE a resource, use DELETE to define an interface.
-
Delete a single resource based on the primary key value
curl -X DELETE https://api.yuqiyu.com/v1/users/1 Copy the code
The primary key value of the resource is passed to the interface as a path.
-
Deleting Multiple Resources
curl -X DELETE -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users -d '{ "userIds": [ 1, 2, 3 ] }' Copy the code
RequestBody is used to pass the list of criteria for deleting multiple resources, either through the primary key set of the resource in the above example, or through other elements of the resource, such as name
Update the resource
Request way | Sample path | note |
---|---|---|
PUT | Api.yuqiyu.com/v1/users/ {I… | Update of a single resourceallThe element |
PATCH | Api.yuqiyu.com/v1/users/ {I… | Update of a single resourcePart of theThe element |
PUT is commonly used when updating resource data, as shown below:
curl -X PUT -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users/1 -d '{" name ", "heng yu young", "age" : 25, "address" : "the shandong jinan"}'
Copy the code
Querying a Single Resource
Request way | Sample path | note |
---|---|---|
GET | Api.yuqiyu.com/v1/users/ {I… | Querying a Single Resource |
GET | Api.yuqiyu.com/v1/users?na… | Non-uniquely identifies resources to be queried |
-
Uniquely identifies a resource to be queried
curl https://api.yuqiyu.com/v1/users/1 Copy the code
When a unique identifier is used to query resources, a path is used to transfer the identifier value to reflect the hierarchical relationship.
-
Non-uniquely identifies a resource to be queried
Juvenile curl https://api.yuqiyu.com/v1/users?name= heng yuCopy the code
Resource data is not only queried by a unique identifier value, but also may be queried by an element in the resource object.
Paging query resources
Request way | Sample path |
---|---|
GET | Api.yuqiyu.com/v1/users?pa… |
Page represents the number of pages currently paging and size represents the number of resources queried per page.
curl https://api.yuqiyu.com/v1/users?page=1&size=20
Copy the code
You can continue appending request parameters if you need to pass query conditions during paging.
https://api.yuqiyu.com/v1/users?page=1&size=20&name= heng yuCopy the code
Action resources
Sometimes we need to change the element content of a resource dynamically, such as resetting the password.
Request way | Sample path | note |
---|---|---|
POST | Api.yuqiyu.com/v1/users/ {I… | – |
The unique identity of the user is passed in the request path, and the changed password is passed in the RequestBody as follows:
curl -X POST -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users/1/actions/forget-password -d '{ "newPassword": "123456" }'
Copy the code
The version number
Version numbers are the old and new standards used to distinguish BETWEEN Api interfaces. The two most popular methods are interface path and header information.
-
Interface path mode
When deploying the interface, we agreed to use HTTP proxy to forward requests of different versions to the interface gateway of the corresponding version. The commonly used request forwarding proxy is: Nginx, etc.
This way, there is a disadvantages, if multiple versions and forwards the request to the same gateway, will cause the failure of the specific version of the forward requests, may be forwarded to the when we visit the v1 v2, this is not our desired results, of course you can add a layer in the gateway interceptors, by extracting the version number to forward control path work.
# request for version V1 curl https://api.yuqiyu.com/v1/users/1 # request for version V2 curl https://api.yuqiyu.com/v2/users/1 Copy the code
-
Header mode
We can pass the version of the accessed interface through HttpHeader, and forward it to the service of the corresponding version according to the control of the extracted header information in the gateway. In this way, the presentation form of the resource path does not change with different versions.
# request for version V1 curl -H 'v1' Accept - Version. https://api.yuqiyu.com/users/1 # request for version V2 curl -H 'Access-Version: v2' https://api.yuqiyu.com/users/1 Copy the code
The two versions of the request may have different parameters and return values, but the request path is the same.
The Key of the version header can be defined according to your own situation. It is recommended to use the Accpet format. For details, see Versioning REST Services.
Status code
The HttpStatus status code is used to determine whether a request is valid or not. The HttpStatus code is used to determine whether a request is valid.
Status code | Takes place |
---|---|
200 | The request is successful |
201 | The new resource is created successfully |
204 | Nothing is returned |
400 | The format of the parameter passed is not correct |
401 | No access |
403 | Protected resources |
404 | The access path is incorrect |
405 | The access mode is incorrect. The GET request is accessed through POST |
410 | The address has been transferred and is not available |
415 | The interface is required to return an incorrect format. For example, the client requires JSON format and the interface returns XML |
429 | The number of client requests exceeds the upper limit. Procedure |
500 | A system exception occurs on the accessed interface |
503 | The service is unavailable and generally in the maintenance state. |
We need to make different feedbacks for different status codes. Let’s first look at a common parameter abnormal error response design method:
Make a request
curl -X POST -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users -d '{"name": "", "age": 25, "address": ""}'
# Response status
HttpStatus 200
# Response content
{
"code": "400"."message": "Username mandatory."
}
Copy the code
On the server side, we can control the fixed return format of different status codes and different exceptions. We should not return 200 for all exception requests and then return an error.
Make a request
curl -X POST -H 'Content-Type: application/json' https://api.yuqiyu.com/v1/users -d '{"name": "", "age": 25, "address": ""}'
# Response status
HttpStatus 400
# Response content
{
"error": "Bad Request"."message": "Username mandatory."
}
Copy the code
The response format
The response format of the interface should be uniform.
The outer format of the interface return value for each successful request should be uniform, and the server can use entity for generic return.
As follows:
/** * Api unified response entity * {@link#data} The data content of each different interface response * {@link#code} Service exception response status code * {@link#errorMsg} Error message * {@link#timestamp} The timestamp of the interface response * *@authorYu Qiyu */
@Data
public class ApiResponse<T> implements Serializable {
private T data;
private String code;
private String errorMsg;
private Long timestamp;
}
Copy the code
-
data
Since the response data type of each API is inconsistent, the generic type used above is returned. Data can return any type of data.
-
code
Service logic exception code, for example, USER_NOT_FOUND (the user does not exist) This is the convention of the interface
-
errorMsg
The corresponding code is worth describing.
-
timestamp
The timestamp of the request response
conclusion
RESTful is an API design specification. Not all interfaces should follow this set of specifications, but we should be more prescriptive at the beginning of the design, so that when we read the code later, we can understand what the main work of the interface is doing based on the path and request mode.