---
description: Representational State Transfer
---

# REST

REST is great for web services that prioritize simplicity and scalability. Use it when building public-facing APIs or when you want a stateless, resource-oriented design.

REST API (also known as RESTful API) is an application programming interface (API) that adheres to REST architectural constraints and conventions used in communication between clients and servers. REST stands for REpresentational State Transfer, it was created by computer scientist Roy Fielding.

REST APIs often still use the HTTP/1 protocol with previous definitions that both the client and server need to comply with.

Currently, REST APIs using JSON are very popular. A few may still use XML.

### Difference between REST and RESTful:

REST web service is a Representational State Transfer and an architectural pattern for creating web services whereas the RESTful service is one that implements that pattern. So there is no special difference in between. However, how good your architecture complies with an absolute standard but how well it tallies your needs & grows with your business.

### When to use REST?

* Limited bandwidth and resources: SOAP messages are heavy in content and consume greater bandwidth, REST should be used where network bandwidth is the constraint.
* Ease of coding: coding REST service and implementing is easier than SOAP. So, if a fast solution is required for web services, then REST web service is the best way.
* Cache: if there is a need for cache and a lot of requests then REST is the perfect one. This increases the no of requests which are sent to the server. Implementing a cache, the most frequent queries results stored in an intermediate solution. Whenever the clients request for a resource, it checks the first cache. If resources exist, then it will not proceed to the server. Caching can help to minimize the number of trips.

### Advantages and disadvantages of REST API:

#### Advantages of REST API:

* REST API is easy to understand and learn, due to its simplicity, known API.
* With REST API, being able to organize complicated applications & makes it easy to use resources.
* The high load can be managed with the help of HTTP proxy server & cache.
* REST API is easy to explore and discover.
* It makes it simple for new clients to work on other applications, whether it is designed specifically for purpose or not.
* Use standard HTTP procedure call- outs to retrieve data and requests.
* REST API depends on codes, can use it to synchronize data with a website without any complications.
* Users can avail access to the same standard objects and data model when compared to SOAP-based web services.
* Brings flexibility in formats by serializing data in XML or JSON format.
* Allows Standard-based protection with the use of OAuth protocols to verify your REST requests.

#### Disadvantages or Challenges in REST:

* Lack of state: most web applications require stateful mechanisms. Suppose you purchase a website that has a mechanism to have a shopping cart. It is required to know the number of items in the shopping cart before the actual purchase is made. This burden of maintaining the state lies on the client, which makes the client application heavy and difficult to maintain.
* Last of security: REST does not impose security such as SOAP. That is the reason REST is appropriate for public URLs, but it is not good for confidential data passage between client and server.&#x20;

### Two components in RESTful API

<figure><img src="https://statics.cdn.200lab.io/2023/05/rest-api-la-gi-1.jpeg" alt="rest-api" height="277" width="600"><figcaption><p><strong>RE</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer</p></figcaption></figure>

REST (REpresentational State Transfer) is a representation of data transformation. In this architecture, the client and server are completely independent, they do not know anything about each other. Each REST API request does not carry the previous state (stateless).&#x20;

So for both sides to exchange states, they will have to go through resources. These resources are the representation of data changes.&#x20;

API (Application Programming Interface) is an application programming interface. This interface is not for end users but for developers. It is a "surface", only the declaration part (name, parameters, return type) can be seen, and the body part is unknown. “Know your face, don't know your heart” is API.

### Request and Response in REST API

<figure><img src="https://1722711354-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwNXdoUkfmcozr29fRrfb%2Fuploads%2FADfp2CQvboZq9NehbYep%2Fimage.png?alt=media&#x26;token=c47bd06f-9454-48a6-a0d7-c92f17c88b6d" alt=""><figcaption></figcaption></figure>

#### **Methods** <a href="#methods-ph-c6-b0-c6-a1ng-th-e1-bb-a9c" id="methods-ph-c6-b0-c6-a1ng-th-e1-bb-a9c"></a>

As mentioned above, to exchange state they will need to communicate resources by sending request responses via HTTP/1. Specifically, what this communication, we need to specify the corresponding methods including:&#x20;

* GET: Returns a Resource or a list of Resources.&#x20;
* POST: Create a new Resource. PUT: Update information for Resource (entire resource).&#x20;
* PATCH: Update information for resource (part of resource).&#x20;
* DELETE: Delete a Resource. If you have ever heard of CRUD APIs, they represent Create, Read, Update and Delete a resource.

#### **Header: Authentication** and specify the return data type <a href="#header-authentication-v-c3-a0-quy-c4-91-e1-bb-8bnh-ki-e1-bb-83u-d-e1-bb-af-li-e1-bb-87u-tr-e1-ba-a3" id="header-authentication-v-c3-a0-quy-c4-91-e1-bb-8bnh-ki-e1-bb-83u-d-e1-bb-af-li-e1-bb-87u-tr-e1-ba-a3"></a>

Remember that REST API is stateless. Each request does not know any previous information. Unlike when we access the web, the browser will have session and cookies to help distinguish whose request it is and what the previous information is.&#x20;

In REST, if a request needs to authenticate access, they will have to use additional information in the header. For example, Authorization information will carry a user token. There are currently 3 main Authentication mechanisms:

* HTTP Basic
* JSON Web Token (JWT)
* OAuth2

In addition, Header also helps the client specify the type of content that needs to be returned from the server - content type. This is done through the Accept section in the header. Its value is usually the MIME type:

* **image** — image/png, image/jpeg, image/gif
* **audio** — audio/wav, audio/mpeg
* **video** — video/mp4, video/ogg
* **application** — application/json, application/pdf, application/xml, application/octet-stream

Example request to get list of posts:

```
GET /v1/posts
Accept: application/json
```

#### **Status Code trong RESTful API** <a href="#status-code-trong-restful-api" id="status-code-trong-restful-api"></a>

<figure><img src="https://statics.cdn.200lab.io/2023/05/rest-api-la-gi-2.jpeg" alt="rest-api-la-gi" height="333" width="600"><figcaption></figcaption></figure>

See at [here](../status-code)

Support version of REST API&#x20;

Normally REST API will have versions like /v1, /v2 to support older data versions. This is especially important when we upgrade the API to higher versions, which can be very different: changing the URL, the way users authenticate, or even the resource name and its structure.

### HTTP methods

An important point about HTTP is that it distinguishes whether a method is secure or insecure. A method is said to be safe if it does not modify resources. In other words, requests are "read-only" operations. For example, making a GET (or HEAD) request for a resource on a server will not change it. All other methods are default unsafe.

Finally, there is the concept of **idempotent**. An HTTP method is said to be idempotent if repeated requests lead to the same result. Just as the request parameters do not change, the request can be created multiple times and the resource has the same state as if the request was created only once.

GET, OPTIONS and HEAD are naturally idempotent methods, as they are read-only operations. Additionally the PUT and DELETE methods are also described as idempotent. This is because updating every resource with the same parameters over and over again leads to the same final result.

It might be a bit confusing that DELETE is also idempotent. Consider what happens to the system when there are multiple concurrent DELETE requests. The first DELETE request will delete the resource. Making multiple DELETE requests at this time will not change the system state. The system will continue to maintain the same state after the first DELETE request is performed.

<figure><img src="https://1722711354-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwNXdoUkfmcozr29fRrfb%2Fuploads%2FAuEVi5SvfttSOTfOs4bq%2Fimage.png?alt=media&#x26;token=6ff86e3e-35db-47c3-ac87-4a3347334d59" alt=""><figcaption></figcaption></figure>

### How to design REST API according to convention

<figure><img src="https://statics.cdn.200lab.io/2023/05/rest-api-la-gi-3.jpeg" alt="cach-thiet-ke-rest-api" height="351" width="600"><figcaption></figcaption></figure>

Although the above constraints and conventions do not need to be followed by developers. However, if done "right", they will bring many benefits.

### Design REST API URI

I have seen many REST API designs written roughly as follows:

```
POST /create_post
GET /list_posts
POST /feature_posts
POST /edit_post/:post_id
```

These REST APIs still work fine, no problem!! It's just that they don't follow convention.&#x20;

This leads to a problem for the document maker (or the designer) who has to check if the URL is correct.&#x20;

The API user must also set up a correct API list. Please compare with the following URL design:

```
POST /v1/posts
GET /v1/posts
GET /v1/posts/:post_id
PUT /v1/posts/:post_id
DELETE /posts/:post_id
```

With this design, you will see that there is a very clear principle of using request methods to express the API's mission. The URI part can be the same, it does not need to contain verbs such as: create, get, update, or delete. Resource names will be plural.

_**Other example:**_

```
GET /v1/posts/:post_id/liked-users
POST /v1/posts/:post_id/liked-users
GET /v1/posts?page=2&limit=50
```

### Other conventions you need to pay attention to&#x20;

* Use the correct Status Code. If the API returns an error, please use the correct status, and avoid always returning the 2xx status when the body is an error message (many of you are doing this wrong).&#x20;
* Don't use underscore (\_), use hyphen (-) in the URI All URIs are lowercase letters.&#x20;
* Do not use file extensions in the URI (eg: .html, .xml, .json).

> Details of the entire REST API convention: [https://restfulapi.net/resource-naming](https://restfulapi.net/resource-naming?ref=200lab.io)
