Hands-On RESTful Web Services with Go
上QQ阅读APP看书,第一时间看更新

REST verbs and status codes

REST verbs specify an action to be performed on a specific resource or a collection of resources. When a request is made by the client, it should send the following information in the HTTP request:

  • The REST verb
  • Header information
  • The body (optional)

As we mentioned previously, REST uses the URI to decode the resource to be handled. There are quite a few REST verbs available, but six of them are used particularly frequently. They are presented, along with their expected actions, in the following table:


        
REST Verb           Action
GET           Fetches a record or set of resources from the server
OPTIONS           Fetches all available REST operations 
POST           Creates a resource or a new set of resources
PUT           Updates or replaces the given record
PATCH           Modifies the given record
DELETE           Deletes the given resource 

 

The status of these operations can be known from HTTP status codes. Whenever a client initiates a REST operation, since REST is stateless, the client should know a way to find out whether the operation was successful or not. For that reason, HTTP responses have a status code. REST defines a few standard status code types for a given operation. This means a REST API should strictly follow the following rules to achieve stable results in client-server communication. There are three important ranges available based on the types of error. See the following table for error ranges:

   
        
Status Code Type           Number Range           Action
Success           200 - 226            The 2xx family is used for successful responses.
Error           400 - 499 (client), 500 - 599 (server)           The 4xx family is used for indicating client errors. The 5xx is for server failures to process the request.
Redirect           300 - 308           The 3xx family is for URL redirection.

 

The detail of what each status code does is very precisely defined, and the overall count of codes increases every year. We mention the important ones in the upcoming section.

All requests to REST services have the following format. It consists of the host and the API endpoint. The API endpoint is the URL path that is predefined by the server. It can also include optional query parameters.

A trivial REST API URI looks like the following:  http://HostName/APIEndpoint/?key=value(optional)

Let's look at all the verbs in more detail. The REST API design starts with the defining of operations and API endpoints. Before implementing the API, the design document should list all the endpoints for the given resources.

In the following section, we carefully observe the REST API endpoints using PayPal's REST API as a use case.