官术网_书友最值得收藏!

An overview of REST

Representational State Transfer (REST) is an architecture style for designing network applications. REST is all about resources, so when creating an API, we need to separate it into logical resources. Resources represent information, and they need to be nouns, not verbs.

To manipulate resources, we use HTTP requests where the methods/verbs are meaningful: GET, POST, PUT, PATCH, and DELETE.

HTTP methods (verbs)

HTTP methods are used to specify the action that should be performed on a resource. The most popular methods are GET and POST, but there are others that are defined as well: CONNECT, DELETE, HEAD, OPTIONS, PUT, PATCH, and TRACE.

Some HTTP methods do not generate any side effects, so they are called safe methods. GET, HEAD, OPTIONS, and TRACE are considered safe, while other methods such as POST, PUT, PATCH, and DELETE are unsafe because they are normally used to change the state of a resource on the server.

Another property of methods is idempotence. A method is idempotent if multiple invocations of it have the same result as a single one. For example, calling DELETE twice won't remove the same resource two times because after the first call it will have already been deleted.

It's really important to correctly implement the safeness and idempotence properties for HTTP clients to do their job. For example, you may have noticed that the browser asks for confirmation when trying to reperform a POST request. This happens because it needs to make sure that you understand the implications of that request, such as creating the same item multiple times.

Now, let's have a quick look at the most common HTTP methods. We are going to use these methods in RESTful applications:

  • GET: This method is used to retrieve information for the requested resource.
  • HEAD: This method is similar to GET, but should not contain the message body in the response. It is useful to check the validity, accessibility, and modification of resources.
  • POST: This method sends a new subordinate of the resource to the server. If a new resource has been created, the server should respond with the 201 Created status code; however, if the action did not result in an identifiable resource, it should respond with 200 OK or 204 No Content.
  • PUT: This method requests that the entity sent is stored at the requested URI. It can be used to update a resource or create a new one if the URI does not point to an existing one.
  • DELETE: This method is used to remove the entity stored at the requested URI; it should respond with 200 OK, 204 No Content, or 202 Accepted (which means the deletion has not occurred yet, but it will).

For a more detailed description of these methods, you can read the Method Definitions section of Hypertext Transfer Protocol -- HTTP/1.1 at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.

Aside from the HTTP methods described previously, there is another method called PATCH that is being adopted more and more. PATCH is similar to PUT since it is used to modify the resource identified by the requested URI or create a new one in case it does not exist. However, the big difference between the two is that PATCH performs a partial update on a resource, so it will not send the whole updated resource, but instead just send the pieces that have been modified. In addition, as opposed to PUT, the protocol ( the resource needs to be modified:

"The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request- URI. The set of changes is represented in a format called "patch document" identified by a media type."

This means that it is not quite correct to send only a partial JSON representation of the resource without describing how the changes should be applied, as shown in the following command:

PATCH /api/users/john HTTP/1.1
 Host: www.example.com
 Content-Type: application/json

 {
 "age": 32,
 "website": "johndoe.domain"
 }

In the preceding example, there is no description of the changes needed to modify the existing user called John. Fortunately, there is a proposed draft called JSON Patch that aims to solve the problem. The draft specifies how to use JSON objects to describe the operations that need to be applied when updating the resource, http://tools.ietf.org/html/rfc6902. Let's rewrite the example and see how it should work according to this standard:

PATCH /api/users/john HTTP/1.1
 Host: www.example.com
 Content-Type: application/json-patch+json

 [{
 "op": "replace",
 "path": "/age",
 "value": 32
 }, {
 "op": "replace",
 "path": "/website",
 "value": "johndoe.domain"
 }]

The JSON body has now become more verbose, but it's standards-compliant according to the JSON Patch draft. This specification allows us to perform more complex operations, such as adding an element to an array property without sending the whole value of the array (and the same goes for an object property).

HTTP status codes

Status codes represent three-digit integers sent by the server to the client that describe the result of the action performed. The first digit of the code is an indication of the class of the response, which can be one of the following:

There are some applications that only use the 200 OK and 500 Internal Server Error status codes, but that is not the way to do it. Since we are creating RESTful applications, we should embrace the HTTP status codes to make our lives easier and not duplicate existing functionality.

For example, you might have seen the following response when trying to retrieve information on a resource without being logged in or sending the proper authentication data:

HTTP/1.1 200 OK
Content-Type: application/json

{"error":"unauthorized"}

Instead of using the correct status code, 401 Unauthorized, the server responded with 200 OK and an unauthorized error message in the message body.

Next, we are going to have a look at some of the most-used status codes and their meaning.

Successful 2xx

The following Successful 2xx class of status codes tell us that the request has been received, understood, and accepted by the server:

  • 200 OK: This status code indicates that the request has succeeded
  • 201 Created: This status code indicates that the request has succeeded and a new resource has been created
  • 202 Accepted: This status code does not say anything about the actual result; it only states that the request has been accepted and that it is being processed asynchronously
  • 204 No Content: This status code indicates that the request has succeeded, but it does not include a message body

Redirection 3xx

The following Redirection 3xx status codes are all about sending the client somewhere else for the actual resource:

  • 301 Moved Permanently: This status code indicates that the resource has a new permanent URI, provided by the Location response header
  • 302 Found: This status code indicates that the resource is temporarily located at another URI, provided by the Location field
  • 304 Not Modified: This status code should be used when the client makes a conditional GET request but the document has not been modified

Client error 4xx

The following Client error 4xx group of status codes are intended for situations related to a client error, and the server should indicate whether it is a temporary or permanent error:

  • 400 Bad Request: This indicates that the syntax of the request is malformed and could not be understood by the server.
  • 401 Unauthorized: This indicates that the client is not authenticated and thus cannot access the resource.
  • 403 Forbidden: This indicates that the client does not have access to the resource, and authorization will not help. The server might not want to let the user know that the resource exists at this URI and could respond with 404 Not Found (for example, because of privacy or security reasons).
  • 404 Not Found: This indicates that the server could not find anything at the requested URI.
  • 409 Conflict: This indicates that the request was not completed because of a conflict with the current state of the resource.
  • 429 Too Many Requests: This status code is defined in the proposed standard for Additional HTTP Status Codes (http://tools.ietf.org/search/rfc6585#section-4), and it indicates that the client has exceeded the imposed rate limit (the client has sent too many requests) and they should only retry after a certain period (defined by the Retry-After header).
  • 422 Unprocessable Entity: This status code has been defined in the proposed standard for HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) (https://tools.ietf.org/html/rfc4918#section-11.2), and it indicates that the content type is understood and the syntax is not malformed, but it was not able to process the request.

Server error 5xx

The following Server error 5xx group of HTTP status codes indicate a problem on the server, which can be temporary or permanent:

  • 500 Internal Server Error: This indicates that the server could not fulfill the request due to an unexpected error
  • 501 Not Implemented: This is used when the server does not recognize the request method
  • 503 Service Unavailable: This indicates that the server was unable to handle the request at the time due to a temporary overload or maintenance

The status codes presented so far are the ones we will most likely use, but if we want to check out their detailed definition or read about the other status codes available, the following links will help:

主站蜘蛛池模板: 通许县| 大安市| 宜兴市| 伽师县| 壶关县| 大安市| 太保市| 都江堰市| 中方县| 昌邑市| 武陟县| 凤凰县| 海伦市| 邢台市| 灵台县| 郯城县| 蓝山县| 高雄市| 洪湖市| 鄱阳县| 冕宁县| 长海县| 沽源县| 赤壁市| 灵寿县| 会同县| 墨江| 松潘县| 徐汇区| 普安县| 宾川县| 江永县| 曲松县| 新河县| 泰宁县| 神农架林区| 克拉玛依市| 东宁县| 滨海县| 大足县| 安龙县|