Monday, 25 November 2019

Everything RESTful


REST is a lightweight web service and stands for Representational State Transfer. REST uses the HTTP protocol to model and implement these web services. In its ideology, it aims to manipulate resources in a stateless fashion using the HTTP methods GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS and TRACE.

History 

Roy Fielding defined REST in 2000 as part of his Ph.D. dissertation "Architectural Styles and the Design of Network-based Software Architectures" at UC Irvine.[3]


Prerequisites 

In order to understand how REST works you must have a good understanding of the underlying HTTP protocol works.

HTTP protocol consists of a REQUEST and RESPONSE sequence

Both 
REQUEST and RESPONSE are made up of a header and body. 

header - consists of metadata modeled as key-value pairs. Header data consists of information such as the type of data, length of data, security information and so on.  Some examples of header tags Content-TypeContent-Length

body - consists of the payload which is the data to be transported. this data can be XML, JSON or just plain text. 

Understanding REST 


Below we can see how CRUD operations are implemented using REST.

a) Creating a resource 

POST method 
POST /path/myAPI

{"key":"FieldName","Value":"someValue"}

b) Retrieving a resource


GET method  


GET /path/myAPI

{"key":"FieldName","Value":"someValue"}

c) Updating a resource

PUT method 


PUT /path/myAPI

{"key":"FieldName","Value":"someValue"}


PATCH method

Below is an example of how to use PATCH and overcome the ambiguity of identifying which fields need to be modified vs those that don't.


PATCH /path/myAPI

{"key":"FieldName","Value":"someValue"}


There is a very good article from 
William Durand please-do-not-patch-like-an-idiot. He goes further in its use to specify various operations that can be achieved with the PATCH method. Which addresses the common design problem in a PATCH call, differentiating a request value to be set to null as opposed to using null to retain its current state. 


d) Deleting a resource 

DELETE method 

Naming conventions 

There is a preference to name resources in the plural, as they can be collections of data.

No comments:

Post a Comment