REST API Explained
What is an API?
Before we dive into REST API, let us first see what an API is. API stands for Application Programming Interface and acts as a mediator between the users and the resources. Let us understand this with an example. When you go to a restaurant, do you have access to its kitchen to get the food you wish to eat? No. Instead, there is a waiter(mediator), with whom you(client) place your order(request). The waiter, in turn, serves you the food(response) that he gets from the kitchen(resource). So, the waiter in this example is an API.
What is a REST API?
Now, what makes an API a REST API? REST stands for Representational State Transfer. It is a software architectural style and provides a set of guidelines to create an API. An API that conforms to those guidelines is referred to as a REST API or sometimes, as RESTful API. The RESTful APIs should conform to the following constraints:
A client-server architecture consisting of clients, servers, and resources, where the requests are managed through HTTP.
Stateless client-server communication, that means a session establishment between client and server is not required. Each request is a separate and independent request.
Cacheability, the client should be able to cache information, whenever possible.
A uniform interface between the components so that the information is transferred in a standard form, regardless of how it is represented in the server.
Layered system architecture, a client may not be directly communicating to the server. There may be one or more intermediaries.
How REST APIs work?
REST APIs make use of HTTP protocol for communication between the client and the server. It uses HTTP requests to implement the CRUD operations - POST, GET, PUT and DELETE.
The request to the server is composed of three main parts:
URI - Uniform Resource Indicator to locate resources.
Headers - Carries meta-data associated with the request.
Payload - present in the POST and PUT requests and contains the data to be sent to the server.
The response from the server is composed of the following parts:
Status code - tells the status of the request, whether it was successful or not using HTTP response codes. For example, 200 for successful.
Status Message - tells the status in English Words. For example, "Successful".
Response Payload - present in the response to GET message. Contains the data requested.
If we go back to our restaurant example, you have to tell the waiter if your order is "For here or To Go". Your order will be delivered to you in the 'format' you requested. In the same way, you can request a REST API to deliver the data in any format you need, like JSON, HTML, XML or plain text.
That is all about REST API in a nutshell.