Navigating fetch API
Tags: javascript, beginners
Published: 2022-04-30 22:02:54

So you've started to nail down some of the basics of vanilla JavaScript and want to move on to the fetch API. While fetch can do a plethora of calls to your backend we're going to focus on its syntax, primarily, and how to use three basic requests: GET, POST, and PATCH.

I'm going to assume you've already visited the MDN page on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">Using the Fetch API</a>, or another similar site, and seen a code snippet along the lines of:
```
fetch('http://example.com/movies.json')
   .then(response => response.json())
   .then(data => console.log(data));
```
Since the verbiage on these technical sites can be difficult to understand at times, let's try to make it simpler. The example code above defines a few variables, let's work through each of them and figure out what's going on. First, in the fetch request, we are passing a link to the file we want data from, in this case a json file hosted on example.com. This link can be either to a website hosting a file, or your own files stored locally. In the next line, we see the variable, "response" and again in the arrow function along side the .json() method. The response can be declared using whatever word or abbreviation you like. In this example, it might more sense if the response variable were called movies, since that is what we appear to be after in that json file. Next, the .json() method, takes in the json object response, and turns it into a useable JavaScript object. Essentially we can now iterate through it and use Object methods on it like any normal JavaScript object. The next .then takes in the response from the previous .then (which is our now useable JavaScript object), defines that object as data, which again could be defined as any phrase, and logs it to the console. Now that we have have a rough image of the fetch API's syntax, let's get down to methods and usage.

The above code snippet can be seen as the default for a fetch. Without specifying a method for the fetch, it will default to the GET method. The GET method simply returns a copy of the requested resource. From there, that copy can be interpreted and manipulated using JavaScript. Using the GET method is great for appending data to the DOM. Assuming the response from our movies.json looks something like:
```
[
  {
    "id": 1,
    "title": "Star Wars: Revenge the Sith"
  },
  {
    "id": 2,
    "title": "Star Wars: The Last Jedi"
  },
  etc...
]
```
We could then write the following fetch to append a list of movie titles to the DOM.
```
fetch("http://www.example.com/movies.json")
  .then(resp => resp.json())
  .then(movies => {
    movies.forEach(movie => {
      const titleList = document.querySelector("ul")
      const movieTitle = document.createElement("li")
      movieTitle.innerText = movie.title
      titleList.append(movieTitle)
    })
  })
```
We would then expect the DOM to display each movie's title as a li element within the ul element.

Using what we've learned about the fetch API so far, we're going to figure out how to make a POST request. A post request is similar to a GET request, with some added requirements. First, let's look at an example:
```
const configObj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
}
fetch("http://www.example.com/movies", configObj)
```
In addition to the url, in POST requests, we also pass the fetch a configuration object, this object can be written inline or as a separate constant to be referenced. This object can contain more keys than the one above, but we're going to focus on these ones today. The method, headers, and body keys are essential to most POST requests and we can get away without using the rest, depending on usage. The method key specifies the type of fetch request being made, ie: GET, POST, or PATCH. POST means that we are requesting to add data to our target url. In our headers, we are passing another object, inside we are specifying the content type of the data that we wish to send, and in the body we specify what that data is; the content type of the body must match that which was specified in the headers. JSON.stringify is going to stringify the data that we pass into it so that it can be read as JSON.
```
const data = {
  title: "Captain America: The Winter Soldier"
}
const configObj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
}
fetch("http://www.example.com/movies", configObj)
```
Above we have defined data as an object containing the title of a movie that we want to append to the target json file at that url. We should expect the json file located at http://www.example.com/movies.json to update to contain the data from our POST request.
```
[
  {
    "id": 1,
    "title": "Star Wars: Revenge the Sith"
  },
  {
    "id": 2,
    "title": "Star Wars: The Last Jedi"
  },
  {
    "id": 3,
    "title": "Captain America: The Winter Soldier"
  }
]
```
One last final remark, the data passed into out POST request can be handled just like the response from our GET request, should we want to use that data to update our DOM.

Finally, we are gonna go over PATCH requests. PATCH requests are syntactically very similar, we will still require a configuration object containing a method, headers, and body. Our method this time will be PATCH, our headers will be exactly the same, and the body will contain data we would like to send to the target url. PATCH requests differ from POST requests in the URL and functionality. The URL for the PATCH request must specify the endpoint, or which part of the JSON file we would like to access. This is necessary as the PATCH request will be patching or changing that endpoint. Using the same example:
```
const data = {
  title: "Star Wars: Revenge of the Sith"
}
const configObj = {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
}
fetch("http://www.example.com/movies/1", configObj)
```
Now we are making a request to the first object in the json file, to edit the string associated with the title key. As you may have noticed earlier, the title had been listed as "Star Wars: Revenge the Sith" so with this PATCH request we are changing the title to correct it to "Star Wars: Revenge of the Sith". After using the Patch request, would expect the json file to show the updated title. 
```
[
  {
    "id": 1,
    "title": "Star Wars: Revenge of the Sith"
  },
  {
    "id": 2,
    "title": "Star Wars: The Last Jedi"
  },
  {
    "id": 3,
    "title": "Captain America: The Winter Soldier"
  }
]
```
We can then use .then to handle its response just like a POST request or leave it as just the request.

I hope this aids in your understanding of the fetch API, and you will hopefully be able to build out from these examples to fulfill your projects needs.