# REST

* REST stands for **REpresentational State Transfer**.
* REST is web standards based architecture style for distributed hypermedia systems and uses HTTP Protocol for data communication.
* It revolves around resource, where every component is a resource and a resource is accessed by a **common interface** using HTTP standard methods.
* REST was first introduced by Roy Fielding in 2000 in his [disertion](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm).
* In REST architecture, a REST Server simply provides access to the resources and REST client accesses and presents the resources.
* In this architecture, each resource is identified by URIs.
* REST uses various representations to represent a resource like `text`, `JSON` and `XML`. Most popular light weight data exchange format used in web services is `JSON`.

## Background

* Web services have really come a long way since its inception. In 2002, the World Wide Web consortium(W3C) had released the definition of WSDL(web service definition language) and SOAP web services. This formed the standard of how web services are implemented.
* In 2004, the web consortium also released the definition of an additional standard called RESTful. Over the past couple of years, this standard has become quite popular. And is being used by many of the popular websites around the world which include Facebook and Twitter.
* REST is a way to access resources which lie in a particular environment. For example, you could have a server that could be hosting important documents or pictures or videos. All of these are an example of resources. If a client, say a web browser needs any of these resources, it has to send a request to the server to access these resources. Now REST defines a way on how these resources can be accessed.
* For example, a web application which has a requirement to talk to other applications such Facebook, Twitter, and Google.
* Now if a client application had to work with sites such as Facebook, Twitter, etc. they would probably have to know what is the language Facebook, Google and Twitter are built on, and also on what platform they are built on.
* Based on this, one can write the interfacing code for our web application. But this could prove to be a nightmare, as if the external provider changes to their resource representation, you will also have to make the changes in your interfacing code.
* So instead, Facebook, Twitter, and Google expose their functionality in the form of Restful web services. This allows any client application to call these web services via REST.

![Interfacing diagram](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-8765b7434816a9e7c36b0b8be49c04755b52cb0c%2Frest_Interfacing.png?alt=media)

### HTTP Methods

*   Following well known HTTP methods are commonly used in REST based architecture.

    | HTTP Methods | Description                                                   |
    | ------------ | ------------------------------------------------------------- |
    | GET          | Provides a read only access to a resource.                    |
    | POST         | Used to create a new resource.                                |
    | PUT          | Used to update an existing resource or create a new resource. |
    | DELETE       | Used to remove a resource.                                    |

![Http Methods](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-1fa26f8daa3e7c0699c0469cb92d58b469b1acee%2FHttp_methods_interfacing.png?alt=media)

### RESTFul Web Services

* A web service is a collection of open protocols and standards used for exchanging data between applications or systems.
* REST is used to build web services that are lightweight, maintainable, and scalable in nature. A service which is built on the REST architecture is called a **RESTful service**. The underlying protocol for REST is HTTP, which is the basic web protocol. But it doesnt have to be HTTP always.
* Platform & technology independent solution.
* Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer.
  * This interoperability _(e.g., between Java and Python, or Windows and Linux applications or java & .NET )_ is due to the use of open standards.
* These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, _(Uniform Resource Identifier)_.
* A service, provides resource representation such as JSON and set of HTTP Methods.
* The key elements of a RESTful implementation using HTTP protocol are as follows:
  1. **Resources**: The first key element is the resource itself. Lets assume that a web application on a server has records of several employees. Let's assume the URL of the web application is http://www.server.com. Now in order to access an employee record resource via REST, one can issue the request at http://www.server.com/employee/1 - This request tells the web server to provide the details of the employee whose employee number is 1. Basically, resources are nouns.
  2. **Request Verbs**: These describe what you want to do with the resource. A browser issues a GET verb to instruct the endpoint it wants to get data. However, there are many other verbs available including things like `POST`, `PUT` and `DELETE`. So in the case of the example GET http://www.server.com/employee/1 , the web browser is actually issuing a GET Verb because it wants to get the details of the employee record. In rest, action are represented by verbs.
  3. **Request Headers**: These are additional instructions sent with the request. These might define the type of response required or the authorization details.
  4. **Request Body**: Data is sent with the request. Data is normally sent in the request when a `POST`/`PUT` request is made to the REST web service. In a `POST` call, the client actually tells the web service that it wants to add a resource to the server. Hence, the request body would have the details of the resource which is required to be added to the server.
  5. **Response Body**: This is the main body of the response. So in our example, if we were to query the web server via the request http://www.server.com/employee/1, the web server might return an XML document with all the details of the employee in the Response Body.
  6. **Response Status codes**: These codes are the general codes which are returned along with the response from the web server. An example is the code `200` which is normally returned if there is no error when returning a response to the client.
* An Example
  * Let's assume that we have a RESTful web service which is defined at the location `http://www.server.com/employee`. When the client makes any request to this web service, it can specify any of the normal HTTP verbs of `GET`, `POST`, `DELETE` and `PUT`. Below is what would happen If the respective verbs were sent by the client.
  * `POST`: This would be used to create a new employee using the RESTful web service.
  * `GET`: This would be used to get a list of all employee using the RESTful web service.
  * `PUT`: This would be used to update all employee using the RESTful web service.
  * `DELETE`: This would be used to delete all employee using the RESTful web service.

## REST Constraints

* Following are the rest constraints,
  1. **Uniform interface**
     * The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently.
     * The principle of Uniform interface, are
       1. **Resource-Based**: Individual resources are identified in requests using URIs as resource identifiers. The resources themselves are conceptually separate from the representations that are returned to the client.
       2. **Manipulation of Resources through representations** : When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource on the server, provided it has permission to do so.
       3. **Self descriptive messages** : Each message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type _(previously known as a MIME type)_. Responses also explicitly indicate their cache-ability.
       4. **Hypermedia as the Engine of Application State (HATEOAS)** : Clients deliver state via body contents, query-string parameters, request headers and the requested URI (the resource name). Services deliver state to clients via body content, response codes, and response headers. This is technically referred-to as hypermedia (or hyperlinks within hypertext). _HATEOS_ also means that, where necessary, links are contained in the returned body _(or headers)_ to supply the URI for retrieval of the object itself or related objects.
     * The uniform interface that any REST services must provide is fundamental to its design.
  2. **Client-Server**
     * The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable.
     * Servers and clients may also be replaced and developed independently, as long as the interface is not altered.
  3. **Stateless**
     * The necessary state to handle the request is contained within the request itself, whether as part of the URI, query-string parameters, body, or headers.
     * The URI uniquely identifies the resource and the body contains the state (or state change) of that resource. Then after the server does it's processing, the appropriate state, or the piece(s) of state that matter, are communicated back to the client via headers, status and response body.
     * In REST, the client must include all information for the server to fulfill the request, resending state as necessary if that state must span multiple requests.
     * Statelessness enables greater scalability since the server does not have to maintain, update or communicate that session state. Additionally, load balancers don't have to worry about **session affinity** for stateless systems.
     * State, or application state, is that which the server cares about to fulfill a request—data necessary for the current session or request. A resource, or resource state, is the data that defines the resource representation — the data stored in the database, for instance. Consider application state to be data that could vary by client, and per request. Resource state, on the other hand, is constant across every client who requests it.
  4. **Cacheable**
     * Clients can cache response.
     * Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests.
     * Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.
  5. **Layered System**
     * A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way.
     * Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
     * Layers may also enforce security policies.
  6. **Code-on-Demand** _(optional)_
     * Servers are able to **temporarily extend or customize the functionality of a client by transferring logic** to it that it can execute. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.
* Complying with these constraints, and thus conforming to the REST architectural style, will enable any kind of **distributed hypermedia system** to have desirable emergent properties, such as
  * performance
  * scalability
  * implicity
  * modifiability
  * visibility
  * portability
  * reliability
* The only optional constraint of REST architecture is code on demand. If a service violates any other constraint, it cannot strictly be referred to as RESTful.

## RMM Model

* Richardson Maturity Model describes four different levels of REST (starting at Level 0). A REST API that supports hypermedia controls is classified as Level 3 in this maturity model.
* More about it can be read [here](https://martinfowler.com/articles/richardsonMaturityModel.html)
