Links to other specifications
JavaScript specification and naming
CSS specifications and naming
Git Usage Specification
1. A RESTful specification
RESTful: Representational State Transfer
Resources: Each resource has a specific URI(Uniform resource Locator), which is the address or unique identifier of each resource.
Representation layers: A Representation of a resource is called its Representation layer, with urIs representing the location of the resource. This representation should be specified in the HTTP request header in the Accept and Content-Type fields that describe the “presentation layer.”
State Transfer: If the client wants to operate the server, it must somehow make the server “State Transfer”. And this transformation is built on top of the presentation layer, so it is “presentation layer state transformation”. The method used by the client is the HTTP protocol, which represents the operation of the four verbs: GET, POST, PUT, DELETE. They correspond to four basic operations: GET to obtain resources, POST to create resources (which can also be used to update resources), PUT to update resources, and DELETE to DELETE resources.
Conclusion:
- Each URI represents a resource
- Some representation layer of this resource is passed between the client and the server
- The client uses four HTTP verbs to perform operations on server-side resources to achieve “presentation layer state transformation”
1.1 the domain name
The API should be deployed under a private domain as much as possible.
https://api.example.com
Copy the code
Version 1.2
You should put the API version number in the URL.
V1 is the version number.
https://api.example.com/v1/
Copy the code
1.3 the path
The path represents the specific URL of the API. In a RESTful architecture, each url represents a resource, so there can be no verbs in the url, only nouns, and the nouns usually correspond to the table names in the database.
2. The HTTP request
2.1 Request Method
2.1.1 the Get
A Get request is used to fetch a resource (one or more items) from the server, and the request parameters are put into the URL.
Example:
// Get resource details
/api/v1/resource/:id
// Get the resource list/api/v1/resource? pageNum=1&pageSize=10
Copy the code
2.1.2 Post
The Post request is used to create a new resource on the server with the request parameters in the body.
There are four ways to encode a Post request:
- application/x-www-form-urlencoded
The most common way to submit data is by POST. The submitted data is encoded as key1=val1&key2=val2. The KEY and val are URL transcoded.
- multipart/form-data
When we use forms to upload files, we must make the form enctyped equal to this value. This method is usually used to upload files.
- application/json
This method is used to tell the server that the response body returned is a serialized JSON string. This approach makes it easy to submit complex structured data.
- text/xml
It is a remote invocation specification that uses HTTP as the transport protocol and XML as the encoding method. Used to transfer XML structures.
2.1.3 the Put
Used to update resources on the server, request parameters can be placed in the URL and body, respectively.
Example:
Request the address | /api/resource/:id |
---|---|
Request parameters | The id of the resource to be modified is carried in the URL, and the data to be modified is put in the body |
2.1.4 the Delete
Used to remove resources from the server, request parameters put into the URL.
Example:
Request the address | /api/resource/:id |
---|---|
Request parameters | The ID of the resource to be deleted is carried in the URL |
3. The HTTP response
3.1 response body
parameter | type | instructions |
---|---|---|
code | Number | Status code |
message | String | The success or error information is displayed |
data | Object / Array | The data/data list returned |
Example:
// When data is null, data is null or []
{
"code": 200."message": "Request successful"."data": {... }}Copy the code
3.2 status code
code | message | instructions | Usage scenarios |
---|---|---|---|
200 | The request is successful | Ok | Of all successful requests. |
201 | Xx created successfully | Created | The server successfully creates data. |
202 | Request received, in process | Accept | Scenarios requiring a long time, such as SMS sending, email notification, and template notification push, require queues. |
204 | Succeeded in deleting or updating. Procedure | No Content | useDelete Or is used when the resource is successfully deletedPut The resource update succeeds. |
301 | The requested resource has been permanently migrated | Moved Permanently | The requested resource has been permanently moved to the new URI, the return message will include the new URI, and the browser will automatically redirect to the new URI. Any future new requests should be replaced with a new URI. |
302 | The requested resource is temporarily migrated | Found | Temporary move. Similar to 301, but the resource is only temporarily moved and the client should continue to use the original URI. |
304 | The requested resource has not been modified | Not Modified | The requested resource is not modified, and the server does not return any resources when it returns this status code. Clients typically cache accessed resources by providing a header indicating that the client wants to return only resources that have been modified after a specified date. |
400 | Request syntax error | Bad Request | Client request syntax error, server cannot understand. |
401 | Unauthenticated | Unauthorized | When an unauthenticated user accesses an API that requires authentication, ortoken Invalid/expired. |
403 | Insufficient permissions | Forbidden | This status code can be interpreted as no permission to access the request, and the server receives the request but refuses to provide services. For example, when a common user requests an operation administrator. |
404 | Resource not found | Not Found | This status code must be returned when the requested resource does not exist. Should return if the resource no longer exists permanently410 The response. |
405 | HTTP request methods are not allowed | Method Not Allowed | This status code must be returned when the HTTP request method used by the client is not allowed by the server. The response must return a message withAllow Is used to represent a list of request methods that the current resource can accept. |
406 | Unsupported data format | Not Acceptable | The server could not complete the request based on the content nature of the client request. This status code should be returned when the API does not support the data format specified by the client. For example, supportJSON 和 XML The output of theAPI Be specified to returnYAML Format data when. The Http protocol usually passes through the request headerAccept To specify the data format) |
408 | The client request timed out. Procedure | Request Time-out | The server waited for a request sent by the client for a long time and timed out. Procedure This status code must be returned when a client request times out. Note that this status code indicates thatThe client request timed out. Procedure, where third parties are involvedAPI The status code cannot be returned when the call times out. |
409 | Conflicting requests | Conflict | The server completes the clientPUT This code may be returned on a request, and a conflict occurred while the server was processing the request. This status code indicates that the request cannot be processed because of a conflict. For example, the API that provides registration by mobile phone number must return this status code if the mobile phone number submitted by the user already exists. |
410 | The resource is permanently deleted | Gone | The resource requested by the client does not exist.410 Different from the404 If the resource previously had is now permanently deleted from use410 Code can be passed301 The code specifies the new location of the resource. |
413 | Request data is too large | Request Entity Too Large | The request was rejected because the requested entity data was too large for the server to process. To prevent continuous requests from clients, the server may close the connection. It contains one if the server is temporarily unable to process itRetry-After To tell the client how much time it can retry access. |
414 | The requested URL is too long | Request-URI Too Large | The requested URI is too long for the server to process. |
415 | Image format not allowed to upload | Unsupported Media Type | The server could not process the media format attached to the request. For example, if only image files are allowed to be uploaded, but the media files submitted by the client are illegal or not images, the status code should be returned. |
429 | Too many requests | Too Many Request | The status code indicates that the number of user requests exceeds the upper limit. For example, the API is set to60 beats per minute If the user requests more than 60 times within a minute, the status code should be returned. And add the corresponding content to the response header. |
500 | Server error | Internal Server Error | The server had an internal error and could not complete the request. This status code must be thrown when the server fails. |
503 | Server maintenance | Service Unavailable | The server is temporarily unable to process client requests due to overloading or system maintenance. The length of the delay can be included in the serverRetry-After Response header information. |
10000 + | The custom code | For any custom code, the value must be greater than 10000 |
4. Application scenarios
4.1 Obtaining a Single Resource
Request method | Get | |
---|---|---|
Request the address | /api/resources/:id |
/* not recommended *//api/getResourceById |
Request parameters | The id of the resource to be obtained is carried in the URL |
Response body:
{
"code": 200."message": "Request successful"."data": {
"id": 1."nickname": "west"."username": "myName"}}Copy the code
4.2 Obtaining the Resource List
4.2.1 When paging is not required
Request method | Get | |
---|---|---|
Request the address | /api/resources |
/* not recommended *//api/getResourseList |
Response body:
{
"code": 200."message": "Request successful"."data": [{"id": 1."nickname": "west"."username": "myName1"
},
{
"id": 2."nickname": "east"."username": "myName2"},... ] }Copy the code
4.2.2 When paging and sorting are needed
Request method | Get | |
---|---|---|
Request the address | /api/resources |
/* not recommended *//api/getResourseList |
Request parameters:
// Parameters are carried in the URL
{
// The current page number must be pageNum
"pageNum": 1.// Display the number of items per page
"pageSize": 10.The value format is "property,type", and the value of type can be desc or ASC
"orderBy": "createTime,desc".// Other conditions
"searchCondition": "* * *". }Copy the code
Response body:
// When paging is required, the data set is stored in the items of data. Total indicates the total number of items
{
"code": 200."message": "Request successful"."data": {
// You must list the data set
"items": [{"id": 1."nickname": "west"."username": "myName1"
},
{
"id": 2."nickname": "east"."username": "myName2"},... ] .// Must indicate the total number of entries
"total": 100}}Copy the code
4.3 Creating Resources
Request method | Post | |
---|---|---|
Request the address | /api/resources |
/* not recommended *//api/createResource |
Request parameters:
// Request parameters are placed in the body
{
"name": "Zhang"."phone": "11011011011". }Copy the code
Response body:
// Whether to return the response data can be negotiated (the front end can refresh the list to get the latest data after judging the creation success)
{
"code": 201."message": "Created successfully"
// No Content, No data returned (negotiable)
}
Copy the code
4.4 Modifying Resources
Request method | Put | |
---|---|---|
Request the address | /api/resources/:id |
/* not recommended *//api/updateResource |
Request parameters:
// The id of the resource to be modified is carried in the URL, and the data to be modified is placed in the body
{
"name": "Zhang"."phone": "11011011011". }Copy the code
Response body:
// Whether to return the response data is negotiable (the front end can refresh the list to get the latest data after judging the success of the update)
{
"code": 204."message": "Update successful"
// No Content, No data returned (negotiable)
}
Copy the code
4.5 Deleting a Resource
Request method | Delete | |
---|---|---|
Request the address | /api/resources/:id |
/* not recommended *//api/deleteResourceById |
Request parameters | The ID of the resource to be deleted is carried in the URL |
Response body:
{
"code": 204."message": "Deleted successfully"
// No Content, No data returned
}
Copy the code
5. API naming conventions
5.1 Resource-oriented Naming
In resource-oriented apis, a resource name consists of an API service name, a collection ID, and a resource ID, organized hierarchically and separated by a forward slash /. If a resource contains child resources, the name of the child resource consists of the parent resource name followed by the ID of the child resource, also separated by a forward slash. The following table.
The convenience is that by splitting the resource name (for example, name.split(“/”)[n]), you can get a single collection ID and a resource ID (assuming none of the segments contain forward slashes).
API Service name | Collection ID | Resource ID | Collection ID | Resource ID |
---|---|---|---|---|
//storage.xxx.com | /buckets | /bucket_id | /objects | /object_id |
Full resource name:
//library.com/shelves/shelf_1/books/book_2
Copy the code
Relative resource name:
shelves/shelf_1/books/book_2
Copy the code
5.2 URL Naming Mode
-
The set ID must be plural with a lowercase hump. If the word does not have a proper plural, it should be singular.
-
English words must be easy to read and concise.
-
Avoid words that are too general, and use them only when they are limited. For example, rowValues take precedence over values. And you should avoid using the following words without qualification:
- elements
- entries
- instances
- items
- objects
- resources
- types
- values
-
Cannot appear – in URL, must be replaced with underscore _.