- Mastering Web Application Development with Express
- Alexandru Vl?du?u
- 1590字
- 2021-08-05 17:54:21
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 toGET
, 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 the201 Created
status code; however, if the action did not result in an identifiable resource, it should respond with200 OK
or204 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 with200 OK
,204 No Content
, or202 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:
- 1xx – informational
- 2xx – success
- 3xx – redirection
- 4xx – client error
- 5xx – server error
Note
You can read more about HTTP status codes from the official RFC page at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
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 succeeded201 Created
: This status code indicates that the request has succeeded and a new resource has been created202 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 asynchronously204 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 theLocation
response header302 Found
: This status code indicates that the resource is temporarily located at another URI, provided by theLocation
field304 Not Modified
: This status code should be used when the client makes a conditionalGET
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 with404 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 theRetry-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 error501 Not Implemented
: This is used when the server does not recognize the request method503 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:
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html (Status Code Definitions)
- https://tools.ietf.org/html/rfc4918 (HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV))
- http://tools.ietf.org/search/rfc6585 (Additional HTTP Status Codes)
- 大學計算機基礎實驗教程
- BeagleBone Media Center
- C語言程序設計
- The DevOps 2.4 Toolkit
- Kotlin Standard Library Cookbook
- ASP.NET程序設計教程
- Learning JavaScript Data Structures and Algorithms
- C++面向對象程序設計習題解答與上機指導(第三版)
- Raspberry Pi Home Automation with Arduino(Second Edition)
- Mobile Device Exploitation Cookbook
- Hands-On JavaScript for Python Developers
- C#面向對象程序設計(第2版)
- SaaS攻略:入門、實戰與進階
- JavaScript設計模式與開發實踐
- 大話C語言