RESTful API Design: Building Structured API's [In 5 easy steps]
Tags: javascript, node, tutorial
Published: 2021-08-08 12:44:23

Hey everyone welcome back 👋, You might have built several APIs for your application or APIs in general but do you follow the **Five-step** procedure to build scalable and maintainable APIs. If you are not aware of the **Five-step**  procedure don't worry, I will take you through them in a while.

## What is an API?
Before moving ahead if you have never worked with APIs let me tell you about them super quickly. Take an example of a hotel *(I know this is the most common and famous example)*. You go to the hotel and don't directly rush to the kitchen right? You give the order to the waiter. Then the waiter goes to the manager and then the order goes to the kitchen for preparation. After that, the cook sends the dish to the managing counter, and then the waiter servers it to you (BUT how is it related to APIs). Here the waiter can be considered as an API where you ***request*** data as an API call and then API server data to you in ***response***. Look at the image below for a better understanding. 
<img src="https://www.elletownsend.co.uk/img/blog-img/1_MXjEMSYAq_6H_TId6li5aQ-min.jpg">

## What is RESTful API

According to [RedHat](https://www.redhat.com/en/topics/api/what-is-a-rest-api), RESTful API is defined as
> A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.

and this is pretty much self-explanatory. But our current focus is "RESTful API design in 5 easy steps" so let's move towards it.

## RESTful API design

### 1. Separate API (data) into logical resources:
This happens a lot of time (especially as a beginner), while defining data people tend to put all the data as a single field which may feel handy when you have less amount of data but that is not at all scalable or maintainable in the long run

The solution is segregating the data into useful and separate categories instead of adding all the data in one category making it big and messy.  Example: Take a look at the data below

1. *bad example*
```json
{
    "id1":1,
    "name1":"abc",
    "id2":2,
    "name2":"def"
}
```
2. *good example*
```json
{
    0:{
         "name":"abc"
    },
    1:{
        "name":"def"
    }
}
```

### 2. Expose structured resource-based URL's
Expose URLs or endpoints in order to retrieve the data. The endpoints can be used for several things like getting all the data or getting only 1 block of data about that object or anything which matches the use-case scenario. There are some conventions on exposing this url which we will see in the upcoming step (3rd step).

### 3.Use HTTP methods (verbs)
Did you ever think that there is a much better URL/ endpoint exposing convention the what you currently use? Let me tell you about it. Before I tell you what is convention let me tell you what is an endpoint?

An endpoint is simply a URL that demonstrates what data is going to be returned on the basis of request type.

Okay, so what is the convention? Let's take the example of school. So, consider that you are making an API for a students management application what are the possible endpoints you would expose (*Let's only consider CRUD for simplicity*)
1. `.../addStudents`
2. `.../getStudents`
3. `.../updateStudent`
4. `.../deleteStudent`

But what if I tell you this is not the most scalable and maintainable method? So what is the conventional method?

The convention says that you should ***not use verbs*** to define the endpoints but should use ***nouns*** instead. No this is not some sort of English lesson but you will understand as we move forward. So let's take the same student example.

Now,
1. Instead of `.../addStudents` we can use `POST /students` (POST request to students)
2. Instead of  `.../getStudents` we can use `GET /students` (GET request to students)
3. Instead of `.../updateStudent` we can use `PATCH /students` or `PUT /students` (PATCH/ PUT request to studnets)
4. Instead of `.../deleteStudent` we can use `DELETE /students` (DELETE request to students)

Now this convention is far more scalable and manageable.

### 4. Send data as JSON (usually)

JSON is the most preferred language for data transfer and it can be found in most API responses. But before sending data to the user we should simply create a new object, add status to it and then add the original data under the separate data object. This is called **enveloping**. And this standard of sending response is known as **JSend**. (There are many standards you could follow but this is the one I like the most). For example, take a look below

1. *Sending the data directly*
```json
{
    "name":"abc",
    "age":"6"
}
```

2. *Enveloping the data and then sending* //Done in the response handler
```json
{
    "status" : "success",
    "data" : {
        "name":"abc",
        "age":"6"
    }
}
```

### 5. Be Stateless
API should be stateless which means everything should be done on the client and side and nothing should be left for the server-side. For example, you want to move to the next page and you just hit the endpoint of the next page (`.../nextpage`) then the server has to remember the current page every time and compute the next page accordingly and the server it. Instead, you can do `.../user/page/6` where 6 is the page and if you want to go to the 7th page then you just need to add `1` to `6` which we handle on the client side.

Done!!!!!! Awesome, you now have a solid understanding of how you should structure your current API so that it becomes more scalable and maintainable. If you are confused or have some questions let me know in the comments below.


### Thank you so much for reading 💖

Like | Follow | Share

Catch me on my socials here: https://bio.link/kaiwalya