HTTP Methods for RESTful Services (Part 1)
Tags: programming, webdev, beginners, javascript
Published: 2021-07-19 06:55:32

HTTP Methods -- one of the commonly asked interview topics for web developers. 

What are they? Why do they exist? How are they useful for web development? If you are preparing for your tech interview, I hope this article will be helpful to you! 

I am splitting this into two parts to avoid the article getting too lengthy as I would like to discuss some common interview questions as we continue our discussion!

## Introduction

According to MDN,
> HTTP defines a set of **request methods** to indicate the desired action to be performed for a given resource.

If you are familiar with full-stack, you probably know the **CRUD** operation, which stands for **C**reate, **R**ead/**R**etrieve, **U**pdate, **D**elete. The HTTP methods are closely associated with CRUD and are used to communicate with servers whenever there's data involved.

A common example where you will see these actions is when a platform involves users, like Twitter and Facebook. However, a lot of resources have used this as examples. Therefore, I would use recipes as example.

<table>
<tr>
<th>HTTP Methods</th>
<th>CRUD</th>
<th>What For?</th>
<th>Example Request URIs</th>
</tr>
<tr>
<td><code>GET</code></td>
<td>Read/Retrieve</td>
<td>Retrieve the recipes from our server</td>
<td><code>http://www.example.com/recipes</code> or <code>http://www.example.com/recipes/1</code></td>
</tr>
<tr>
<td><code>POST</code></td>
<td>Create</td>
<td>Create a new recipe that is sent from client side</td>
<td><code>http://www.example.com/recipes/new</code>
</tr>
<tr>
<td><code>PUT</code></td>
<td>Update/Replace</td>
<td>Update an existing recipe that is sent from client side</td>
<td><code>http://www.example.com/recipes/{:id}</code>
</tr>
<tr>
<td><code>PATCH</code></td>
<td>Update/Modify</td>
<td>Update an existing recipe partially that is sent from client side</td>
<td><code>http://www.example.com/recipes/{:id}</code>
</tr>
<tr>
<td><code>DELETE</code></td>
<td>Delete</td>
<td>Remove/Delete an existing recipe from the resource</td>
<td><code>http://www.example.com/recipes/{:id}</code>
</tr>
</table>

Let's break down each of them one by one!

---

## <code>GET</code>

We use `GET` requests to **retrieve information only** -- not to modify the information in any way. Since the `GET` request does not modify anything, it is considered a "safe method". On top of that, GET APIs should be **idempotent**, which means making multiple identical requests must and will produce the same result. 

---

####✋🏻Sidebar✋🏻

Question 1️⃣ : What does "idempotent" mean? 
Answer: Something Idempotent (or idempotence in noun form) in RESTful API standpoint means **the client can make as many requests as they want and the fetch result will still be the same**, i.e. the resource is not going to be modified just because someone make multiple calls. We will see this keyword again later in this article. 

Question 2️⃣ : Why is `GET` method defined as "safe"?
Answer: A method is defined as "safe" when they are intended to retrieve data only, which makes the method idempotent in other words, since multiple identical requests will behave the same. `HEAD`, `OPTIONS` and `TRACE` in REST are also defined as "safe" methods. However, we will not cover these three methods in this article -- hopefully something I will cover in future articles! 
[My resource for the definition of idempotent and safe method](https://www.restapitutorial.com/lessons/idempotency.html) (REST API tutorial)

---

(And continue)
Whenever we make any `GET` request, if the resource is found on the server, it must return HTTP response code `200 (OK)` -- along with the response body, which is usually XML or JSON content. If the resource is not found, the server must return the infamous HTTP response code `404 (NOT FOUND)`. If the resource is determined that the `GET` request is incorrectly formed, the server will return `409 (BAD REQUEST)`.

**Syntax**
```javascript
axios({
  method: 'get',
  url: 'https://geek-jokes.sameerkumar.website/api?format=json',
});
```
(This is a working API, here's the [repo](https://github.com/sameerkumar18/geek-joke-api) for this API!)

---

## <code>POST</code>

We would use the `POST` method because we want to **create a new (subordinate) resource into the collection of resources**, e.g. adding a newly found recipe to our collection of recipe! When creating new resource, the server will automatically assign an ID (new resource URI) to this new resource. 

If successfully created, the server will return the HTTP status code `201 (CREATED)`, returning a location header with a link to the newly-created resource with the `201` HTTP code. (like `https://www.example.com/recipes/1`)

`POST` methods are neither **safe** nor **idempotent** and invoking two identical `POST` requests will result in two different resources containing the same information. 

**Syntax**
```javascript
axios('/login', {
  firstName: 'Megan',
  lastName: 'Lo'
});
```

---

## <code>PUT</code>

We use the `PUT` method primarily to **update existing resource**. If the resource does not exist, then the API may decide to create a resource or not. On a successful update, the server will return `200 (OK)`, or `204 (NO CONTENT)`. If `PUT` is used for creation and success, the server will return `201 (CREATED)`, like `POST`.

`PUT` is not a safe operation, since it modifies (or creates) states within the resource, however it is idempotent. If you create or update a resource with the same cal again, the resource is still there and has the same state as it did in the same call. (It is however not idempotent, if you are trying to increment a state.)

**Syntax**
```javascript
const article = { title: 'React PUT Request Example' };
axios.put('https://reqres.in/api/articles/1', article)
  .then(response => this.setState({ updatedAt: response.data.updatedAt }));
```
(Code Example from [here](https://jasonwatmore.com/post/2021/04/22/react-axios-http-put-request-examples))

---

There you go! You learned what `GET`, `POST`, `PUT` are in this article. In the next article, I will like to dive into the difference between `POST` and `PUT` (common interview question). We will also discuss what `PATCH` and `DELETE` are.

Stay tuned and see you in the next article!!
  
---

## Further Readings

[What happens when you submit an article?](https://dev.to/antogarand/what-happens-when-you-submit-an-article-3f8a) (A Real-World Example Breakdown by Antony Garand published in dev.to)

#### Understanding and Using REST APIs (and My Resources)
- [Using HTTP Methods for RESTful Services](https://www.restapitutorial.com/lessons/httpmethods.html) (REST API Tutorial)
- [HTTP Methods](https://restfulapi.net/http-methods/) (REST API Tutorial)
- [Consuming REST APIs In React With Fetch And Axios
](https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/) (Smashing Magazine)
- [Understanding And Using REST APIs](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/) (Smashing Magazine)
- [How to make HTTP requests with Axios](https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/#axiospostreturn) (LogRocket)

#### HTTP Response Codes
- [418 I'm a teapot](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/418) (MDN -- some tech humor lol)
- [HTTP STATUS DOGS](https://httpstatusdogs.com/) (Super adorable dog pics with the corresponding HTTP codes)
- [Classic, Shady, Funny : What is your Page’s HTTP Status Code?](https://www.oncrawl.com/oncrawl-infographics/pages-http-status-code/) (Oncrawl)

#### Random and Fun
- [A Curated List of 100 Cool and Fun Public APIs to Inspire Your Next Project](https://betterprogramming.pub/a-curated-list-of-100-cool-and-fun-public-apis-to-inspire-your-next-project-7600ce3e9b3) (by Angelica Dietzel on Medium/Better Programming)