Restful Definition
References:
https://hub.packtpub.com/what-are-rest-verbs-and-status-codes-tutorial/
https://developer.mozilla.org/en-US/docs/Glossary/Idempotent
Definitions:
The name Representational state transfer (REST) was coined by Roy Fielding from the University of California. It is a very simplified and lightweight web service compared to SOAP. Performance, scalability, simplicity, portability, and modifiability are the main principles behind the REST design.
REST is a stateless, cacheable, and simple architecture that is not a protocol but a pattern.
In this tutorial, we will talk about REST verbs and status codes. The article is taken from the book Building RESTful Web services with Go by Naren Yellavula. In this book, you will explore, the necessary concepts of REST API development by building a few real-world services from scratch.
REST verbs
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 this information in the HTTP request:
REST verb Header information Body (optional) As we mentioned previously, REST uses the URI to decode its resource to be handled. There are quite a few REST verbs available, but six of them are used frequently. They are as follows:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
If you are a software developer, you will be dealing with these six most of the time. The following table explains the operation, target resource, and what happens if the request succeeds or fails:
REST Verb | Action | Success | Failure |
---|---|---|---|
GET | Fetches a record or set of resources from the server | 200 | 404 |
OPTIONS | Fetches all available REST operations | 200 | – |
POST | Creates a new set of resources or a resource | 201 | 404, 409 |
PUT | Updates or replaces the given record | 200, 204 | 404 |
PATCH | Modifies the given record | 200, 204 | 404 |
DELETE | Deletes the given resource | 200 | 404 |
The numbers in the Success and Failure columns of the preceding table are 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 has status codes for the response. REST defines the preceding status code types for a given operation. This means a REST API should strictly follow the preceding rules to achieve client-server communication.
All defined REST services have the following format. It consists of the host and API endpoint. The API endpoint is the URL path which is predefined by the server. Every REST request should hit that path.
A trivial REST API URI: http://HostName/API endpoint/Query(optional) Let us look at all the verbs in more detail. The REST API design starts with the definition 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.
GET Method
A GET method fetches the given resource from the server. To specify a resource, GET uses a few types of URI queries:
Query parameters Path-based parameters In case you didn’t know, all of your browsing of the web is done by performing a GET request to the server. For example, if you type www.google.com, you are actually making a GET request to fetch the search page. Here, your browser is the client and Google’s web server is the backend implementer of web services. A successful GET operation returns a 200 status code.
Examples of path parameters:
Everyone knows PayPal.
PayPal creates billing agreements with companies.
If you register with PayPal for a payment system, they provide you with a REST API for all your billing needs.
The sample GET request for getting the information of a billing agreement looks like this:
/v1/payments/billing-agreements/agreement_id
.
Here, the resource query is with the path parameter. When the server sees this line, it interprets it as I got an HTTP request with a need for agreement_id from the billing agreements. Then it searches through the database, goes to the billing-agreements table, and finds an agreement with the given agreement_id. If that resource exists it sends the details to copy back in response (200 OK). Or else it sends a response saying resource not found (404).
Using GET, you can also query a list of resources, instead of a single one like the preceding example.
PayPal’s API for getting billing transactions related to an agreement can be fetched with /v1/payments/billing-agreements/transactions
.
This line fetches all transactions that occurred on that billing agreement. In both, the case’s data is retrieved in the form of a JSON response. The response format should be designed beforehand so that the client can consume it in the agreement.
Examples of query parameters are as follows:
Query parameters are intended to add detailed information to identify a resource from the server. For example, take this sample fictitious API. Let us assume this API is created for fetching, creating, and updating the details of the book. A query parameter based GET request will be in this format:
/v1/books/?category=fiction&publish_date=2017
The preceding URI has few query parameters. The URI is requesting a book from the book’s resource that satisfies the following conditions:
It should be a fiction book
The book should have been published in the year 2017
Get all the fiction books that are released in the year 2017 is the question the client is posing to the server.
Path vs Query parameters—When to use them? It is a common rule of thumb that Query parameters are used to fetch multiple resources based on the query parameters. If a client needs a single resource with exact URI information, it can use Path parameters to specify the resource. For example, a user dashboard can be requested with Path parameters and fetch data on filtering can be modeled with Query parameters.
Use Path parameters for a single resource and Query parameters for multiple resources in a GET request.
POST Method
The POST method is used to create a resource on the server.
In the previous book’s API, this operation creates a new book with the given details. A successful POST operation returns a 201 status code.
The POST request can update multiple resources: /v1/books
.
The POST request has a body like this:
{"name" : "Lord of the rings", "year": 1954, "author" : "J. R. R. Tolkien"}
This actually creates a new book in the database. An ID is assigned to this record so that when we GET the resource, the URL is created. So POST should be done only once, in the beginning. In fact, Lord of the Rings was published in 1955. So we entered the published date incorrectly.
PUT Method
In order to update the resource, let us use the PUT request. The PUT method is similar to POST. It is used to replace the resource that already exists. The main difference is that PUT is idempotent. A POST call creates two instances with the same data. But PUT updates a single resource that already exists:
/v1/books/:id
Ex: /v1/books/1256
with body that is JSON like this:
{"name" : "Lord of the rings", "year": 1955, "author" : "J. R. R. Tolkien"}
PATCH Method
The PATCH method is similar to PUT, except it won’t replace the whole record. PATCH, as the name suggests, patches the column that is being modified. Let us update the book 1256 with a new column called ISBN:
/v1/books/1256
with the JSON body like this:
{"isbn" : "0618640150"}
It tells the server, Search for the book with id 1256. Then add/modify this column with the given value.
PUT and PATCH both return the 200 status for success and 404 for not found.
DELETE Method
The DELETE API method is used to delete a resource from the database. It is similar to PUT but without any body. It just needs an ID of the resource to be deleted. Once a resource gets deleted, subsequent GET requests return a 404 not found status.
Responses to this method are not cacheable (in case caching is implemented) because the DELETE method is idempotent.
Option Method
The OPTIONS API method is the most underrated in the API development.
Given the resource, this method tries to know all possible methods (GET, POST, and so on) defined on the server.
It is like looking at the menu card at a restaurant and then ordering an item which is available (whereas if you randomly order a dish, the waiter will tell you it is not available).
It is best practice to implement the OPTIONS method on the server.
From the client, make sure OPTIONS is called first, and if the method is available, then proceed with it.
Status Codes
There are a few families of status codes.
Each family globally explains an operation status. Each member of that family may have a deeper meeting.
So a REST API should strictly tell the client what exactly happened after the operation. There are 60+ status codes available. But for REST, we concentrate on a few families of codes.
2xx family (successful)
200 and 201 fall under the success family.
They indicate that an operation was successful. Plain 200 (Operation Successful) is a successful CRUD Operation:
- 200 (Successful Operation) is the most common type of response status code in REST
- 201 (Successfully Created) is returned when a POST operation successfully creates a resource on the server
- 204 (No content) is issued when a client needs a status but not any data back
3xx family (redirection)
These status codes are used to convey redirection messages.
The most important ones are 301 and 304:
- 301 is issued when a resource is moved permanently to a new URL endpoint. It is essential when an old API is deprecated. It returns the new endpoint in the response with the 301 status. By seeing that, the client should use the new URL in response to achieving its target.
- The 304 status code indicates that content is cached and no modification happened for the resource on the server. This helps in caching content at the client and only requests data when the cache is modified.
4xx family (client error)
These are the standard error status codes which the client needs to interpret and handle further actions. These have nothing to do with the server. A wrong request format or ill-formed REST method can cause these errors. Of these, the most frequent status codes API developers use are 400, 401, 403, 404, and 405:
- 400 (Bad Request) is returned when the server cannot understand the client request.
- 401 (Unauthorized) is returned when the client is not sending the authorization information in the header.
- 403 (Forbidden) is returned when the client has no access to a certain type of resources.
- 404 (Not Found) is returned when the client request is on a resource that is nonexisting.
- 405 (Method Not Allowed) is returned if the server bans a few methods on resources. GET and HEAD are exceptions.
5xx family (server error)
These are the errors from the server. The client request may be perfect, but due to a bug in the server code, these errors can arise. The commonly used status codes are 500, 501, 502, 503, and 504:
- 500 (Internal Server Error) status code gives the development error which is caused by some buggy code or some unexpected condition
- 501 (Not Implemented) is returned when the server is no longer supporting the method on a resource
- 502 (Bad Gateway) is returned when the server itself got an error response from another service vendor
- 503 (Service Unavailable) is returned when the server is down due to multiple reasons, like a heavy load or for maintenance
- 504 (Gateway Timeout) is returned when the server is waiting a long time for a response from another vendor and is taking too much time to serve the client
Idempotent
In Math, Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
In HTTP world, An HTTP method is idempotent if the intended effect on the server of making a single request is the same as the effect of making several identical requests.
Common idempotent methods: GET, HEAD, PUT, DELETE, OPTIONS, TRACE
Non-idempotent methods: POST, PATCH, CONNECT
For the explaination, here are some examples you might want to look at:
- GET is an idempotent method because of it's the read-only request to server and doesn't change the state of the server.
- DELETE (/delete/{itemId}) is idempotent, even if the returned status code may change between requests after the first request has been succeeded.
- POST (in this case, we gonna add new row) is not idempotent; if it is called several times, it adds several rows: