Basic JS Fetch Requests: GET, POST, PATCH, and DELETE.
Published: 2023-07-25 16:14:51

<em>tldr</em>: We will briefly summarize the syntax and structure of basic GET, POST, PATCH, and DELETE requests using the Fetch API.

All fetch requests follow the same structure and contains two parameters in its function call: 

```
fetch(url, initObj)
```

1. url from which to fetch
2. init object which controls other parameters such as method

For our purposes, the target url will almost always be the local address of a db.json server hosted on our computer, but external API’s are also used. 

## GET:

By default, if an init object is not passed, the fetch function assumes a GET method which just means that it returns everything at the target url. It is very likely that the first fetch requests you will write as student will be GET requests so we’ll return to the init object later on.
 
The following two lines typically follow the fetch call:

```
fetch(url)
	.then( response => response.json())
	.then( data => … )
```

The response that comes back from the url is not yet in a form that we can work with in JavaScript, so the first line invokes the `.json()` method which unpacks the response, so to speak. Then the second line, takes the unpacked response from the first line as a parameter named data, in this case, then we can do what we need to do with it. 

As a check that the fetch request has been written correctly, we can `console.log()` the data in the second line. Once we can see the data in the console log, we can remove the console.log in the second .then statement and do what we need to do with it. 

This might be a good time to remind that we do this so that we do not have to manually declare what might be a very large data structure in the same file that we unpack and manipulate that data structure in. By having our data instead in an external `db.json` file or some other API, we can focus on the front-end JavaScript and separate out the data structure back-end. 

That’s the basic GET request. For the remaining fetch methods, we will assume a `db.json` server as the target url. 

## POST: 

When a user submits a form and information needs to be added to the `db.json`, we need to write a POST request. We can instruct the fetch function to perform a POST by including an init object in our function call. The init object, for our purposes, typically contains the following three keys:

1. **Method**: specifies why we need to communicate to the server
2. **Headers**: specifies how we will communicate to the server
3. **Body**: specifies what we need to communicate to the server

Their typical values, for our purposes, are shown below in its proper syntax:

```
{
method: “POST”,
headers: { “Content-Type” : “application/json” 
Accept: “application/json},
body: JSON.stringify( newObject )
}
```

The first line tells the fetch that we are trying to post data to the server, the second line tells it that the data we are sending it is in the form of `json`, and the third line contains the data we want to post, passed into the `JSON.stringify()` method which packs our data into a form that the server can then unpack and handle. 

Two `.then` statements follow, just like the GET request:

```
fetch(url, {
method: “POST”,
headers: { “Content-Type” : “application/json” },
body: JSON.stringify( newObject )
})
	.then( response => response.json()) 
	.then( newObjectPostedToServer => … )
```

Again, the first line unpacks the response from the server, which for a post request contains the new data (meaning our data has successfully been posted to the server!). The GET request receives a response containing all data on the server, but the POST request receives a response containing only the new data on the server. In the second line, therefore, we can do what we need to do with the new object. If we are pessimistic about the fetch request, we might update our client-side DOM at this point, if we didn’t already do it before the fetch request (optimistic). That’s the POST request.

## PATCH:

When a user updates existing data on the server, we need to write a PATCH request. Our init object will again, contain the needed parameters to instruct our fetch request. This time we need to change our url too in order to direct our fetch request to the correct place/object in the db.json file. 

For example, let’s say our url has been `http://localhost:8001/food` at which our `db.json` file stores food data. Data stored in a `db.json` is uniquely labeled with id’s starting from 1 at the first entry. So the first entry in our `db.json` might look like this:

```
{
id: 1, 
name: “strawberry”,
in-stock: true
}
```

If we want to update this item on our `db.json` to change its in-stock property to false, the fetch request would need to target this item with its url. We do this with the id. So the targeted url is: `http://localhost:8001/food/1`, with the id at the end so that the fetch request is only looking at the item with id 1 rather than all items. Eventually, we use back-ticks so interpolate the id in our function writing. So that the url parameter in the fetch request usually ends up looking like:

```
url/${target-id}
```

Now onto the init object. Again our method key specifies “PATCH”. The headers key doesn’t change. Now the body, instead of containing an entire entry, contains only the key/value pair we’d like to update in the target object, still string-ified with the JSON method:

```
fetch(`url/${target-id}`, {
method: “PATCH”,
headers: {“Content-Type” : “application/json”},
body: JSON.stringify({ key-to-update: updated-value })
})
```

In our food example, the fetch request would be:

```
fetch(`http://localhost:8001/food/1`, {
method: “PATCH”,
headers: {“Content-Type” : “application/json”},
body: JSON.stringify({ in-stock: false })
})
```

The following .then statements match the response we get from a POST request. The server unpacks the string-ified data, updates the target object at the specified id, then sends the updated object back as our response. First we unpack it, then we do what we need to do with it. Below is a full fetch request for patching:

```
fetch(`url/${target-id}`, {
method: “PATCH”,
headers: {“Content-Type” : “application/json”},
body: JSON.stringify({ key-to-update: updated-value })
})
	.then( response => response.json())
	.then( updatedObject => … )
```

That’s the PATCH request.

## DELETE:

When a user needs to delete data on the server, we need to write a DELETE request. Typically, this targets a specific entry at a specific id on the `db.json`, so again our url needs to target this entry with its url. But since we are not sending anything to the server, our init object is much shorter and contains only a method key specifying delete, no headers, no body. The fetch request is shown below:

```
fetch((`url/${target-id}`, {
method: “DELETE”
})
```

The server doesn’t send anything back in this case, and we just need to make sure that our client-side dom is updated accordingly. That’s it. That’s the DELETE request.