再oschina上面看到一篇翻译文章,介绍了Api的一些设计规则,REST设计规则受益匪浅,进行转载
原文链接
Why:
Because we try to enforce development of sanely constructed RESTful interfaces, which team members and clients can consume simply and consistently.
Why:
Lack of consistency and simplicity can massively increase integration and maintenance costs. Which is why
API design
is included in this document.
We mostly follow resource-oriented design. It has three main factors: resources, collection, and URLs.
- A resource has data, gets nested, and there are methods that operate against it
- A group of resources is called a collection.
- URL identifies the online location of resource or collection.
Why:
This is a very well-known design to developers (your main API consumers). The core idea of REST is the resource and each resource is identified by a URL, and you retrieve that resource by sending a GET request to that URL. Very simple.
Always use a plural nouns for naming a url pointing to a collection:
/users
.Always use a singular concept that starts with a collection and ends to an identifier:
/students/245743 /airports/kjfk
Keep verbs out of your resource URLs.
Why:
because we use verbs for something else
Use verbs for non-resources. In this case, your API doesn’t return any resources. Instead, you execute an operation and return the result. These are not CRUD (create, retrieve, update, and delete) operations:
GET `/translate?text=Hallo`
Why:
Because for CRUD we use HTTP methods on
resource
orcollection
URLs. The verbs we were talking about are actuallyControllers
. You usually don’t develop many of these. read more…The request body or response type is JSON then please follow
camelCase
forJSON
property names to maintain the consistency.Why:
This is a JavaScript project guideline, Where Programming language for generating JSON as well as Programming language for parsing JSON are assumed to be JavaScript.
Even though a resource is a singular concept that is similar to an object instance or database record, you should not use your
table_name
for a resource name andcolumn_name
resource property.Why:
Because your intention is to expose Resources, not your database schema details
Again, only use nouns in your URL when naming your resources and don’t try to explain their functionality.
Why:
Only use nouns in your resource URLs, avoid endpoints like
/addNewUser
or/updateUser
. Also avoid sending resource operations as a parameter.Explain the CRUD functionalities using HTTP methods:
How:
GET
: To retrieve a representation of a resource.POST
: To create new resources and sub-resourcesPUT
: To update existing resourcesPATCH
: To update existing resources. It only updates the fields that were supplied, leaving the others aloneDELETE
: To delete existing resourcesFor nested resources, use the relation between them in the URL. For instance, using
id
to relate an employee to a company.Why:
This is a natural way to make resources explorable.
How:
GET /schools/2/students
, should get the list of all students from school 2GET /schools/2/students/31
, should get the details of student 31, which belongs to school 2DELETE /schools/2/students/31
, should delete student 31, which belongs to school 2PUT /schools/2/students/31
, should update info of student 31, Use PUT on resource-URL only, not collectionPOST /schools
, should create a new school and return the details of the new school created. Use POST on collection-URLsUse a simple ordinal number for version with a
v
prefix (v1, v2). Move it all the way to the left in the URL so that it has the highest scope:http://api.domain.com/v1/schools/3/students
Why:
When your APIs are public for other third parties, upgrading the APIs with some breaking change would also lead to breaking the existing products or services using your APIs. Using versions in your URL can prevent that from happening. read more…
Response messages must be self descriptive. A good error message response might look something like this:
{ "code": 1234, "message" : "Something bad happened", "description" : "More details" }
or for validation errors:
{ "code" : 2314, "message" : "Validation Failed", "errors" : [ { "code" : 1233, "field" : "email", "message" : "Invalid email" }, { "code" : 1234, "field" : "password", "message" : "No password provided" } ] }
Why:
developers depend on well-designed errors at the critical times when they are troubleshooting and resolving issues after the applications they’ve built using your APIs are in the hands of their users.
Note: Keep security exception messages as generic as possible. For instance, Instead of saying ‘incorrect password’, you can reply back saying ‘invalid username or password’ so that we don’t unknowingly inform user that username was indeed correct and only password was incorrect.
Use only these 8 status codes to send with you response to describe whether everything worked,
The client app did something wrong or The API did something wrong.200 OK
response represents success forGET
,PUT
orPOST
requests.201 Created
for when new instance is created. Creating a new instance, usingPOST
method returns201
status code.304 Not Modified
response is to minimize information transfer when the recipient already has cached representations400 Bad Request
for when the request was not processed, as the server could not understand what the client is asking for401 Unauthorized
for when the request lacks valid credentials and it should re-request with the required credentials.403 Forbidden
means the server understood the request but refuses to authorize it.404 Not Found
indicates that the requested resource was not found.500 Internal Server Error
indicates that the request is valid, but the server could not fulfil it due to some unexpected condition.
Why:
Most API providers use a small subset HTTP status codes. For example, the Google GData API uses only 10 status codes, Netflix uses 9, and Digg, only 8. There are over 70 HTTP status codes. However, most developers don’t have all 70 memorized. So if you choose status codes that are not very common you will force application developers away from building their apps and over to wikipedia to figure out what you’re trying to tell them. read more…
Provide total numbers of resources in your response
Accept
limit
andoffset
parametersThe amount of data the resource exposes should also be taken into account. The API consumer doesn’t always need the full representation of a resource.Use a fields query parameter that takes a comma separated list of fields to include:
GET /student?fields=id,name,age,class
- Pagination, filtering and sorting don’t need to be supported from start for all resources. Document those resources that offer filtering and sorting.
9.2 API security
9.2.1 TLS
To secure your web API authentication, all authentications should use SSL. OAuth2 requires the authorization server and access token credentials to use TLS.
Switching between HTTP and HTTPS introduces security weaknesses and best practice is to use TLS by default for all communication. Throw an error for non-secure access to API URLs.
9.2.2 Rate limiting
If your API is public, you may want to consider Rate Limiting
Why:
To protect your APIs from bot threats that call your API thousands of times per hour. You should consider implementing rate limit early on.
9.2.3 Input Validation
It’s difficult to perform most attacks if the allowed values are limited.
* Validate required fields, field types (e.g. string, integer, boolean, etc), and format requirements. Return 400 Bad Request with details about any errors from bad or missing data.
Escape parameters that will become part of the SQL statement to protect from SQL injection attacks
As also mentioned before, don’t expose your database scheme when naming your resources and defining your responses
9.2.4 URL validations
Attackers can tamper with any part of an HTTP request, including the URL, query string,
9.2.5 Validate incoming content-types.
The server should never assume the Content-Type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a 406
Not Acceptable response.
9.2.6 JSON encoding
A key concern with JSON encoders is preventing arbitrary JavaScript remote code execution within the browser or node.js, on the server. Use a JSON serialiser to entered data to prevent the execution of user input on the browser/server.
9.3 API documentation
- Fill the
API Reference
section in README.md template for API. - Describe API authentication methods with a code sample
- Explaining The URL Structure (path only, no root URL) including The request type (Method)
For each endpoint explain:
* URL Params If URL Params exist, specify them in accordance with name mentioned in URL section
Required: id=[integer]
Optional: photo_id=[alphanumeric]
- If the request type is POST, provide a working examples. URL Params rules apply here too. Separate the section into Optional and Required.
- Success Response, What should be the status code and is there any return data? This is useful when people need to know what their callbacks should expect!
Code: 200
Content: { id : 12 }
- Error Response, Most endpoints have many ways to fail. From unauthorised access, to wrongful parameters etc. All of those should be listed here. It might seem repetitive, but it helps prevent assumptions from being made. For example
json
{
"code": 403,
"message" : "Authentication failed",
"description" : "Invalid username or password"
}
9.3.1 API design tools
There are lots of open source tools for good documentation such as API Blueprint and Swagger.