Fetch methods GET, POST, PATCH, AND DELETE
Published: 2024-01-11 23:39:23

This blog is for novice coders, much like myself who are struggling to grapple what fetch functions are or would just like to learn how to structure basic fetch functions, It will go over how to create and understand the basics of these `fetch()` methods GET, POST, PATCH, and DELETE. all of the examples will be as if the requests to a public api url or a local db.json.


Learning JavaScript, One thing I had trouble with was 
understanding how a fetch POST, PATCH, and DELETE really worked.
Not understanding how the fetch worked is part of the reason I had to take phase 1 again. Most of the time for me it was just syntax I had typed out wrong, with that being said let's jump into what a `fetch()` function is.


## What is a Fetch() function?


A `fetch()` function is a JavaScript method used to request data 
from a resource path. A resource path could be pointed to an api url link , it could be a specified path to a local db.json, or it could be both of these stored into a named variable. I prefer to store mine into named variables, typically my code starts like this:

```
const url = 'https://localhost:3000/data'

or 

const url = 'https://example.com/api/data'
```


All `fetch()` requests contain two parameters in the function 
call.


```
fetch(url, options)
```

The options parameter allows you to define aspects of the fetch such as, the method, the headers, and body. That will be coded similarly to this:

```
fetch(url, {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
   },
   body: JSON.stringify(data)
})
```
Details about this code block will be discussed in the POST request section of the blog.

## What is a fetch GET request?

A fetch GET is the default request for a `fetch()` function. The fetch GET retrieves information from the first parameter passed into the fetch function. This is an example declaring the method as GET:

```
fetch(url, {
      method: 'GET'
})
.then((response) => response.json())
.then((dataArr) => console.log(dataArr))
.catch((error) => console.error('Error', error))
```
This fetch function is making a GET request to the api url. 

`.then()` is called a promise. It works Asynchronously which means the following code will run while this waits for the response from the api url or local db.json.
the first `.then()` will always be some variation of the code block above , another example could be `.then(r=>r.json()`.

The second `.then()` is storing the data requested from the url into a parameter called dataArr which is then being console logged in to the console.

The `.catch()` catches any errors and will console log them.

## What is a fetch POST request? 

A fetch POST request is a fetch function's method for creating a new set of data to send back to your api url or local db.json, an example of this is submitting a form. When you submit a form you send that information back to your api url or local db.json to have the changes persist. This is a POST request example: 

```
fetch(url, {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
   },
   body: JSON.stringify(data)
})
.then((r)=>r.json())
.then((newData) => console.log(newData))
```

In this fetch function the there are 3 options shown. I mentioned them earlier in the blog. They are:

**Method**: GET, POST, PATCH, DELETE, Etc.
**Headers**: Checks response for JSON format and accepts it if it is.
**body**: Contains the response in a JSON formatted string for the api url or local db.json

This fetch function is then taking the response from the fetch, passing it as the parameter newData. Then newData is console logged.

**What is a fetch PATCH request?**

A fetch PATCH is a request to update specific parts of the response. An example of this would be like updating specific elements in a user's profile like their email address. This is an example of the code that is written for a PATCH request:

```
fetch('https://example.com/api/user/profile', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: 'example@email.com',
  })
})
  .then((r)=>r.json())
  .then((newEmailPatch) => console.log(newEmailPatch))
  .catch((error) => console.error('Error:', error))
```

This fetch function is taking the response from the fetch, 
converting it into JSON format, then passing the data into the newEmailPatch parameter and console logging newEmailPatch.


**What is a fetch DELETE request?**

A fetch DELETE is a request to delete existing information in the response received from the fetch function. An example of this would be like deleting a post. This is what that would look like:

```
fetch(`${url}${id}`, {
  method: 'DELETE',
  headers: {
    // Add other headers as needed
  },
})
  .then((r) => r.json())
  .then((deltedPost) => console.log(deletedPost))
  .catch(error => console.error('Error:', error));
```

This fetch function is taking the response from the fetch, which is using interpolation to combine the specified url for the post we are trying to delete. It takes that response store converts it to JSON format. Then stores the data into the parameter deletedPost and then console logs deletedPost in the console.

## Conclusion

In conclusion, the fetch() function is a pivotal step for novice coders navigating the world of web development. Whether you're interacting with APIs or manipulating a local db.json, understanding GET, POST, PATCH, and DELETE requests is essential.

The fetch() function serves as the gateway to seamless communication between your application and external resources. Defining a resource path, such as a URL or a stored variable, sets the stage for building powerful interactions with the data.

Remember, the fetch() function takes two parameters: the resource path and the options, where you can specify the method, headers, and body. The clarity of these parameters becomes evident when exploring different request types.

GET requests, are the default for fetch functions.

POST requests, for creating new data, typically used for submitting forms and persisting changes in your API or database.

PATCH requests enable the targeted update of specific data elements, as demonstrated in the example of modifying a user's profile email address.

Lastly, DELETE requests facilitate the removal of existing data, showcasing the power to efficiently manage your application's content.

By grasping the intricacies of these fetch functions, you empower yourself to build dynamic and responsive web applications. Remember, persistence and practice are key to mastering these concepts. Happy coding!