Uniform interface

When we encounter the word interface, the first thing that comes to our mind is decoupling. We create interfaces to have loosely coupled architecture, and the same type of architecture is seen in the case of RESTful.

While implementing REST, we use the same concept to decouple the client from the implementation of the REST service. However, to implement such a decoupling between the client and the service, standards are defined that every RESTful service supports.

Note the word standard in the preceding line. We have so many services in the world and, obviously, the consumers outnumber the services. As a result, we have to follow some rules while designing the services because every client should understand the service easily without any hassle.

REST is defined by four interface constraints:

HTTP 1.1 provides a set of methods, called verbs. Implementing these verbs in our services would mark them as standardized. The important verbs are as follows:

Method

Operation Performed on Server

Method Type

GET

Read/retrieve a resource.

Safe

PUT

Either insert a new resource or update the resource if it already exists.

Idempotent

POST

Insert a new resource. Can be used to update an existing resource as well.

Nonidempotent

DELETE

Delete a resource .

Idempotent

OPTIONS

Get a list of all the allowed operations for a resource.

Safe

HEAD

Return only the response headers with no response body.

Safe

 

The preceding table is quite self-explanatory, except the Method Type column. Let me clarify this.

A safe operation when performed on the service does not have any effect on the original value of the resource. As the GET, OPTIONS, and HEAD verbs only retrieve or read the resource-related stuff and does not update that, they are safe.

An idempotent (can be repeated) operation when performed gives the same result no matter how many times we perform it. For example, when you make a DELETE or PUT operation, you are actually operating on a particular resource, and the operation can be repeated with no issues.

POST versus PUT: This is a very common topic of discussion on the internet, and one that is very easy to understand. Both POST and PUT can be used to insert or update a resource. However, POST is nonidempotent, meaning that it isn't repeatable. The reason is that each time you call using POST, it will create a new resource if you don't provide the exact URI of the resource. The next time you use POST, it will again create a new resource. However, in PUT, it will first validate the existence of the resource. If it exists, it will update it; otherwise, it will create it.