Communicating with a JSON Server with GET, POST, DELETE, and PATCH Requests...It's Easier Than You Think
Tags: beginners, tutorial, javascript, json
Published: 2022-07-10 21:21:31

If you are a just beginning to get your feet wet with coding, learning about server requests such as GET, POST, PATCH, etc. can feel more like being thrown into the open ocean, rather than just getting your feet wet. Don't panic, the communication between you (the client/browser) and the server is actually very interesting and easy to understand once you get some practice with it. So what do you say, shall we take a swim in the JSON ocean together?

**What is a server and JSON anyway?**
Any time you open a website, an app, or even that cute puppy video on YouTube, you are establishing a communication between your browser and the server. This is what is referred  to as a "GET" request (we'll learn more about these later on). The GET request is, just like the name suggests, getting or fetching the server based on the URL that was entered. Once the browser contacts the server, the server then delivers a response by displaying the website you requested. This is what is known as the "Request-Response cycle," meaning that for any request you make (GET, PATCH, DELETE, etc.) you will receive a response from the server. This communication between the browser and the server is run through "JavaScript Object Notation" or JSON for short. The JSON is what establishes the virtual handshake between your browser and the server. JSON provides a lightweight format for sending information between the browser and server. Another way to think about it is that JSON is the language that the server speaks, while your browser speaks in JavaScript. In order for what you write in JavaScript to convert to JSON, you will need to convert the information into a string using this command: 
`JSON.stringify()`
This command will convert the information you are sending in the body of the request, into strings. Additionally, the server will send you JSON data in a string format and you can convert it back into JavaScript data by using this command:
`JSON.parse()`
This may seem a little esoteric but we will see how these commands are used when we run our various requests below. 

**How does a URL line get me to a website?**
This is a bit off topic but it is important to understand the constituent parts of a URL and how they guide our browser to the correct website. A URL is primarily composed of three separate parts: the protocol, the domain name, and the path. Let's take a look at an example by using the W3School website URL on JSON as an example:
https://www.w3schools.com/js/js_json_intro.asp
In this example, the "https" is the protocol meaning this is the format in which we want to send our request through Hyper Text Transfer Protocol (HTTP). The "www.w3schools.com" is the domain name. The domain name is basically just the name of the website. For example, Google's domain name is "google.com." Finally, the portion of the URL with "/js/js_json_intro.asp" is the path. This is what will get us to the exact webpage we are looking for, in this case it is the JSON intro on the W3School website. To recap, the various parts of the URL are just methods for refining the search of the specific website page we wish to access. Our HTTP provides the method that we want to access the website, the domain name is the general name of the website where our page is located, and the path directs our browser to the exact page we are interested in. 

**Let's talk about GET, POST, PATCH ,and DELETE Requests** 
Now, I want to clarify that there are other request methods but the primary methods all fall under the acronym of "CRUD" or "Create, Return, Update, and Delete." CRUD refers to the methods in which we can interact with the server. For example, let's say you want to fill out a form on a website, you will first need to access the website by using a "return/GET" request. Once you are on the website, you will then "create/POST" by filling out the form and submitting it. Then, once the form is submitted, let's say you misspelled something, you can use the "update/PATCH" request on the same form which will change the form on the server as well. Now, let's also say you change your mind and want to get rid of the form, you can finally use the "delete/DELETE" request to remove the file from the server. One more thing to note are the fetch() and .then() parts of the code. The fetch() is the part of the command that makes the connection to the website server. In the fetch() you will add the URL but also note that the URL needs to be incased in '' (quotation marks) in order to designate the information as a string for the server's JSON to recognize it. The .then() directs the JavaScript in what it should do with the data it sends and receives. We will see more examples of the .then() below.

**Let's see the CRUD in code...**
For a "create" request, we will use a "GET" request. This request would look like this in code:

```
fetch('http://localHost:3000/file')
.then(res => res.json())
.then(json => displayData(json))

function displayData() => {...
```

In the code example above, for demonstration purposes, I used a locally hosted URL that directs to a db.json file on my VS code. Now, depending on the server, you may or may not have access to where you can make changes to the server data. This won't affect a "GET" request, but it will for the other requests we will look in to. The first .then() in the request is instructing the request to send the response(res) to be converted into JSON script. The second .then() is instructing the JavaScript code to place the JSON data directly into our function which was labeled "displayData". Note, the function name can be anything you want it to be but it is important for the name to be consistent in both the second .then() and with the name of your function below. This consistency ensures that the data we receive from the server is directed to the exact part of our code we need it to go to. 

For the "POST" request, we have to make some additions to our code:

```
fetch('http://localHost:3000/file', {
  method: 'POST',
  headers: {
      'Content-Type':'application/json'
  }
  body: JSON.stringify(functionAbove)
  })
  .then(res => res.json())
  .then(json => consol.log(json))
```
 
For the POST method, we have to first specify that we are using the POST request method. For any request besides "GET", you **must specify** what type of request you are making. Next, we added the "header." The header allows us dictate the type of data we will be sending and receiving. Finally, we have the "body". The "body" instructs our JavaScript to convert the data that is housed in the body of our command (in this case it's in the "functionAbove" which is hypothetically above our request) to be converted into strings to be sent to the server. Note, for POST requests, this is **destructive** meaning that it will make changes directly into the server data array without cloning a new data array. One last thing to note, because you are not getting data from the server but rather sending data to the server, you will not get any response back. That's why, for the second .then() there is a consol.log() to confirm that that data we sent was indeed posted.

For PATCH and DELETE requests, we will lump these requests together as they don't differ much from a POST request except that with the PATCH, we are telling the server to make a change to a specific part of our server array data. This will make a change in an element of the data array instead of adding an element to the data array. For this, we will need to specify where in our data array we need to make the change. To do this, we will need to use the code: 
``${}``
With a DELETE request, we are then telling the server to remove a section from our data array on the server. Again, both will contain a console.log() in the second .then() to help us ensure that our data was indeed edited/deleted from the server. 

PATCH Request: 
```
function changeArray(dataChange){
fetch(`http://localHost:3000/file/${dataChange.name}`, {
  method: 'PATCH',
  headers: {
      'Content-Type':'application/json'
  }
  body: JSON.stringify(functionAbove)
  })
  .then(res => res.json())
  .then(json => consol.log(json))
}
```
For the example above, you will note that we added the ${dataChange.name}
to the end of our URL. This is important because we are telling the request where exactly we wish to change our data array. Since our data, hypothetically, on the server is also an object, we can use the "dot"(.) notation to specify where in the object we wish to change (in this case, the "name").


DELETE Request:
```
function deleteData(removeData){
fetch(`http://localHost:3000/file/${removeData.name}`, {
  method: 'DELETE',
  headers: {
      'Content-Type':'application/json'
  }
  body: JSON.stringify(functionAbove)
  })
  .then(res => res.json())
  .then(json => displayData(json))
}
```
For the example above, just like in the "PATCH" request, you will note that we added the ${removeData.name}
to the end of our URL. This is important because we are telling the request where exactly we wish to delete part of our data array. Since our data, hypothetically, on the server is also an object, we can use the "dot"(.) notation to specify where in the object we wish to delete.


**Conclusion**
The CRUD-JSON requests provide an excellent tool for managing the data housed within a server. Now that you have swam through JSON and the various requests, you will feel more comfortable the next time you have to take the plunge into these various browser-server communications.


Sources cited: 
-Cover image courtesy of: Taylor Vick, Unsplash
-JSON info/domain name info: https://www.w3schools.com/js/js_json_intro.asp,
https://www.cloudflare.com/learning/dns/glossary/what-is-a-domain-name/