REST API 设计规则

-------REST API Design Rulebook

URIs

REST API用URI(Uniform Resource Identifiers )来表示资源。

例如:

 http://api.example.restapi.org/france/paris/louvre/leonardo-da-vinci/mona-lisa
下面的URI就可读性很差: 

http://api.example.restapi.org/68dd0-a9d3-11e0-9f1c-0800200c9a66 

不过,现在流行短网址,我们可以用可读性差点URI表示此类资源。

URI Format

  URI 语法:

URI = scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]

 

Rule: 我们必须用符号“/”来表示URI中资源的层级关系(Forward slash separator (/) must be used to indicate a hierarchicalrelationship )

例如:http://api.canvas.restapi.org/shapes/polygons/quadrilaterals/squares

Rule: 在URI末尾,不可以出现符号“/”(A trailing forward slash (/) should not be included in URIs )

例如:http://api.canvas.restapi.org/shapes/ 这种URI不要使用。

Rule: 在URI路径部分,我们可以使用连字符"-"分割单词提高可读性(Hyphens (-) should be used to improve the readability of URIs )

Rule: 在URI中不要出现下划"_"线字符,要使用连字符"-"(Underscores (_) should not be used in URIs )

Rule: URI路径的单词要使用小写形式(Lowercase letters should be preferred in URI paths )

Rule: URI中不要出现文件扩展名(File extensions should not be included in URIs )

例如:http://api.college.restapi.org/students/3248234/transcripts/2005/fall.json

一般我们利用Content-Type 头信息的media type 类型表示消息格式。

Rule: 在API中使用一致的子域名名字(Consistent subdomain names should be used for your APIs)

例如:http://api.soccer.restapi.org  ,api作为子域名,soccer.restapi.org是顶级域名。

Rule: Consistent subdomain names should be used for your client developer portal

例如:http://developer.soccer.restapi.org ,子域名developer的定义。


 

Rule: A singular noun should be used for document names

Rule: A plural noun should be used for collection names

Rule: A plural noun should be used for store names

Rule: A verb or verb phrase should be used for controller names

Like a computer program’s function, a URI identifying a controller resource should be named to indicate its action. For example:
http://api.college.restapi.org/students/morgan/register
http://api.example.restapi.org/lists/4324/dedupe 

Rule: Variable path segments may be substituted with identity-based values

Rule: CRUD功能名称不应该出现在URI中(CRUD function names should not be used in URIs )

HTTP request methods should be used to indicate which CRUD function is performed.
For example, this API interaction design is preferred:
DELETE /users/1234 

Rule: URI中的查询部分可以用来过滤资源(The query component of a URI may be used to filter collections or stores )

Rule: URI中的查询部分应当具有分页功能(The query component of a URI should be used to paginate collection or store results )

Rule: GET and POST must not be used to tunnel other request methods

Rule: GET must be used to retrieve a representation of a resource

Rule: HEAD should be used to retrieve response headers

Rule: PUT must be used to both insert and update a stored resource

Rule: PUT must be used to update mutable resources

Rule: POST must be used to create a new resource in a collection

Rule: POST must be used to execute controllers

Rule: DELETE must be used to remove a resource from its parent

Rule: OPTIONS should be used to retrieve metadata that describes a resource’s available interactions


Table 3-1. Response status code categories
Category Description
1xx: Informational Communicates transfer protocol-level information.
2xx: Success Indicates that the client’s request was accepted successfully.
3xx: Redirection Indicates that the client must take some additional action in order to complete their request.
4xx: Client Error This category of error status codes points the finger at clients.
5xx: Server Error The server takes responsibility for these error status codes.

Rule: 200 (“OK”) should be used to indicate nonspecific success

Rule: 200 (“OK”) must not be used to communicate errors in the response body

Rule: 201 (“Created”) must be used to indicate successful resource creation

Rule: 202 (“Accepted”) must be used to indicate successful start of an asynchronous action

Rule: 204 (“No Content”) should be used when the response body is intentionally empty

Rule: 301 (“Moved Permanently”) should be used to relocate resources

Rule: 302 (“Found”) should not be used

Rule: 303 (“See Other”) should be used to refer the client to a different URI

Rule: 304 (“Not Modified”) should be used to preserve bandwidth

Rule: 307 (“Temporary Redirect”) should be used to tell clients to resubmit the request to another URI

Rule: 400 (“Bad Request”) may be used to indicate nonspecific failure

Rule: 401 (“Unauthorized”) must be used when there is a problem with the client’s credentials

Rule: 403 (“Forbidden”) should be used to forbid access regardless of authorization state

Rule: 404 (“Not Found”) must be used when a client’s URI cannot be mapped to a resource

Rule: 405 (“Method Not Allowed”) must be used when the HTTP method is not supported

Rule: 406 (“Not Acceptable”) must be used when the requested media type cannot be served

Rule: 409 (“Conflict”) should be used to indicate a violation of resource state

Rule: 412 (“Precondition Failed”) should be used to support conditional operations

Rule: 415 (“Unsupported Media Type”) must be used when the media type of a request’s payload cannot be processed

Rule: 500 (“Internal Server Error”) should be used to indicate API malfunction


Table 3-2. Vocabulary review
TermDescription
DELETEHTTP request method used to remove its parent.
GET HTTPrequest method used to retrieve a representation of a resource’s state.
HEAD HTTP request method used to retrieve the metadata associated with the resource’s state.
OPTIONS HTTP request method used to retrieve metadata that describes a resource’s available interactions.
POST HTTP request method used to create a new resource within a collection or execute a 

controller.
PUT HTTP request method used to insert a new resource into a store or update a mutable 

resource.
Request-LineRFC 2616 defines its syntax asMethod SP Request-URI SP HTTP-Version CRLF
Request methodIndicates the desired action to be performed on the request message’s identified resource.
Response status code A three-digit numeric value that is communicated by a server to indicate theresult of a client’s request.
Status-Line RFC 2616 defines its syntax as: HTTP-Version SP Status-Code SP Reason-Phrase
CRLF TunnelingAn abuse of HTTP that masks or misrepresents a message’s intent and undermines the 

protocol’s transparency.

 

HTTP Headers

Rule: Content-Type must be used

Rule: Content-Length should be used

Rule: Last-Modified should be used in responses

Rule: ETag should be used in responses

Rule: Stores must support conditional PUT requests

Rule: Location must be used to specify the URI of a newly created resource

Rule: Cache-Control, Expires, and Date response headers should be used to encourage caching

Rule: Cache-Control, Expires, and Pragma response headers may be used to discourage caching

Rule: Caching should be encouraged

Rule: Expiration caching headers should be used with 200 (“OK”) responses

Rule: Expiration caching headers may optionally be used with 3xx and 4xx responses

Rule: Custom HTTP headers must not be used to change the behavior of HTTP methods

Rule: Custom HTTP headers must not be used to change the behavior of HTTP methods

Rule: Media type negotiation should be supported when multiple representations are available

Rule: Media type selection using a query parameter may be supported

Message Body Format

Rule: JSON should be supported for resource representation

Rule: JSON must be well-formed

Rule: XML and other formats may optionally be used for resource representation

Rule: Additional envelopes must not be created

Hypermedia Representation

Rule: A consistent form should be used to represent links

Rule: A consistent form should be used to represent link relations

Rule: A consistent form should be used to advertise links

Rule: A self link should be included in response message body representations

Rule: Minimize the number of advertised “entry point” API URIs

Rule: Links should be used to advertise a resource’s available actions in a state-sensitive manner

Media Type Representation

Rule: A consistent form should be used to represent media type formats

Rule: A consistent form should be used to represent media type schemas

Error Representation

Rule: A consistent form should be used to represent errors

Rule: A consistent form should be used to represent error responses

Rule: Consistent error types should be used for common error conditions

猜你喜欢

转载自blog.csdn.net/cqg1988/article/details/81271437