RESTAPI设计规则
2017-07-15 11:09
567 查看
再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
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:
Always use a singular concept that starts with a collection and ends to an identifier:
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:
Why:
Because for CRUD we use HTTP methods on
The request body or response type is JSON then please follow
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
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
Explain the CRUD functionalities using HTTP methods:
How:
For nested resources, use the relation between them in the URL. For instance, using
Why:
This is a natural way to make resources explorable.
How:
Use a simple ordinal number for version with a
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:
or for validation errors:
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.
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
The 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:
Pagination, filtering and sorting don’t need to be supported from start for all resources. Document those resources that offer filtering and sorting.
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.
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.
* 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
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
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!
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
原文链接
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 designis 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
resourceor
collectionURLs. The verbs we were talking about are actually
Controllers. You usually don’t develop many of these. read more…
The request body or response type is JSON then please follow
camelCasefor
JSONproperty 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_namefor a resource name and
column_nameresource 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
/addNewUseror
/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-resources
PUT: To update existing resources
PATCH: To update existing resources. It only updates the fields that were supplied, leaving the others alone
DELETE: To delete existing resources
For nested resources, use the relation between them in the URL. For instance, using
idto 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 2
GET /schools/2/students/31, should get the details of student 31, which belongs to school 2
DELETE /schools/2/students/31, should delete student 31, which belongs to school 2
PUT /schools/2/students/31, should update info of student 31, Use PUT on resource-URL only, not collection
POST /schools, should create a new school and return the details of the new school created. Use POST on collection-URLs
Use a simple ordinal number for version with a
vprefix (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 OKresponse represents success for
GET,
PUTor
POSTrequests.
201 Createdfor when new instance is created. Creating a new instance, using
POSTmethod returns
201status code.
304 Not Modifiedresponse is to minimize information transfer when the recipient already has cached representations
400 Bad Requestfor when the request was not processed, as the server could not understand what the client is asking for
401 Unauthorizedfor when the request lacks valid credentials and it should re-request with the required credentials.
403 Forbiddenmeans the server understood the request but refuses to authorize it.
404 Not Foundindicates that the requested resource was not found.
500 Internal Server Errorindicates 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
limitand
offsetparameters
The 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 LimitingWhy:
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 a406Not 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 theAPI Referencesection 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.相关文章推荐
- REST API 设计规则
- REST API的认证机制的设计规则
- [置顶] 分布式架构设计之Rest API
- 设计API的五大规则
- API设计中时间定义的5条规则
- 怎样更好的设计你的REST API之基于REST架构的Web Service设计及REST框架实现
- 设计优秀API的五大规则
- REST API设计指导——译自Microsoft REST API Guidelines(二)
- REST API设计指导——译自Microsoft REST API Guidelines(三)
- 5 个关于 API 中日期和时间设计规则
- 关于REST的文章—— 如何查看我的订单-REST的流程API设计案例
- REST API 安全设计指南
- 设计优秀API的五大规则
- REST API设计
- 如何更好的设计你的REST API之基于REST架构的Web Service设计及REST框架实现
- REST API设计指导——译自Microsoft REST API Guidelines(一)
- RESTFeel: 一个企业级的API管理&测试平台。RESTFeel帮助你设计、开发、测试您的API
- Rest API 设计最佳实践(2)
- 关于REST API设计的一些小经验
- 第3章 REST API设计