Server Communication

The Basics and its Example Application in JavaScript

Introduction

For a long time, I have struggled with the concept of server communication. And to an extent, I will admit that I still do. However, after learning its application in JavaScript, I was able to grasp a broader understanding of it. And as a result, my confidence to master the concept of server communication one day has increased. I believe that it is much easier for people to understand non-programming technical-related concepts when we are taught how to apply them to the languages that we enjoy coding in. This idea can apply to any subject introduced to a student in any career or profession. This blog will guide you through the basics of server communication and how to apply them using JavaScript.

For those of you who are not familiar with JavaScript, I would highly recommend you learn at least the basics of that language to understand this article fully. However, this is not required. The syntax of JavaScript is very straightforward, so if you already have a background in at least one programming language, then you shouldn't have too many issues in understanding the examples given in this blog.

How It Works

Let's first understand basic internet terms, starting with HTTP. HTTP stands for HyperText Transfer Protocol. This protocol is used to communicate between the client and server. It is responsible for fetching resources from servers and displaying the resources and data to the user in a readable format. You see this acronym on many websites; sometimes, with an extra 's', making it HTTPS. HTTPS is a more secure version of HTTP.

With that in mind, I'll introduce you to more terms: GET, POST, PATCH, and DELETE. These are just some of the ways that HTTP interacts with data. They are essentially called, "methods", similar to what we call methods/functions in programming languages. When the client requests for data or resources to be displayed, the GET method is used to retrieve them from the server. Assuming that there are no errors in how the request is made, the server sends the data back and displays it to the user in a readable format via the web browser. POST is the method that allows for new data to be stored in the server or an API (which we'll talk about in a bit). If you ever want to modify or update any data or resources, PATCH is one method to use. You can guess what DELETE is for. But if you can't, this HTTP method is used for requesting certain data to be deleted.

Application in JavaScript

JSON

Before I show you how these concepts could be applied using JavaScript, it is important to learn about one other term: JSON. JSON, which stands for JavaScript Object Notation is a lightweight data storage used for data exchange. The cool thing about this is that it can work with any language and it's easy to read. JSON essentially stores data as a collection of objects. And when we say objects, we mean the JS definition of an object, which would have one or more key-value pairs. (Also known as dictionaries in some programming languages.) Example below:

{
  "characters": 
    [
        {
          "id": 1,
          "name": "Barney",
          "image": barneyImageURL,
          "species": "Dinosaur"
        },
        {
          "id": 2,
          "name": "Dora the Explorer",
          "image": doraTheExplorerURL,
          "species": "Human"
        },
        {
          "id": 3,
          "name": "Swiper the Fox",
          "image": swiperTheFoxURL,
          "species": "Fox"
        }
    ]
}

In this example, JSON file, we have one large object. Inside the object is an array of three smaller objects. Notice that the objects all have the same keys: id, name, image, and species. Similar to a database, these keys (or in this context, attributes) allow programmers to display and manipulate the data that they want. The "id" attribute is an automatic key that is added to the object when a POST request is called to create new resources and tie them to the server. The "id" is what preserves the uniqueness of each object. There are many API's that use JSON files, which you can check out in the link below titled: Big List of Free Open APIs.

One thing you can also do is make your own mock JSON file. To do this, you first need to have the JSON Server installed onto your machine. the JSON Server allows your machine to simulate data storage. Run the following command on your terminal to install JSON Server:

# Install in specific directory
npm install json-server
# Install everywhere on your machine
npm install -g json-server

To start the JSON server, go to the directory in which you wish to run your project and run the following command:

json-server --watch db.json

This command will start the server and create a file called db.json (if one doesn't already exist). Regardless, you will be able to programmatically access the contents of the file and manipulate them as you please. If you did everything correctly, you should see something like this:

The resources represent all the JSON objects. In this case, there is only one resource: toys.

Making Requests with JavaScript

Now that you understand the basics of server communication and how to work with JSON, this final section will show you how to use JavaScript to fetch requests for the data to use for your needs. For the rest of this article, assume that "resource" is a variable that represents a collection of JSON objects from a db.json file or an actual API.

To make a request, you'll have to use the "fetch" method, followed by two "then" methods. At the end of this code, you are returned a "Promise", meaning that the server will send you what you need. Hence the recommendation for a return statement. Examples below for GET:

// GET request
return fetch(RESOURCE)
        .then((response) => response.json())
        .then((data) => console.log(data));

// GET request
// You can also make fetch requests for a specifc object given the id.
// Assume id is a variable representing the object's id value.
return fetch(`${RESOURCE}/${id}`)
        .then((response) => response.json())
        .then((data) => console.log(data));

Let's break it down. First, we call "fetch", which will call the server to send us the resources. Afterward, the server responds by sending the client the resources. What to do then is to convert the resources returned (aka the response) into a readable format for the user. This is what the first "then" method is for. It takes an argument, "response", and converts it from a JSON format to an object with the code: response.json(). Finally, with the second "then" method, you can work with the data. I strongly recommend opening up the console on your browser and printing the data out using console.log(), so that you may experiment with the data and determine from there how to proceed.

Going back to our example resource: "characters", here are examples of how to use JavaScript to make POST and PATCH requests:

// POST Request
return fetch('http://localhost:3000/characters', {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
    },
    body: JSON.stringify(
      {
        "name": "Slinky Dog"
        "image": "https://www.freeiconspng.com/uploads/slinky-png-transparent-1.png"
        "species": "Dog"
      }
    ),
  })
    .then((response) => response.json())
    .then((data) => /* DO STUFF WITH DATA HERE */);

Additional code is needed. The method specifies the type of HTTP request being made. The headers allow you to add additional information for the request or response. The Content-Type header is used for specifying the type of data being used. The Accept header tells the server that what type of return data is being expected. The last thing needed is the body. This will allow you to create/update an object with specific attributes and convert it to a JSON object. The rest of the syntax is the same as that of the GET request. Now let's look at a PATCH request example:

// PATCH request
// In this example, assume the id is 1, the id for the Barney object.
return fetch(`http://localhost:3000/characters/${id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
        },
        body: JSON.stringify({
          "name": "Barney the Dinosaur"
        })
      })
        .then((response) => response.json())
        .then((data) => /* DO STUFF WITH DATA HERE */);

Similar to POST, except for the body, we only need to specify the attributes to update, instead of listing everything in that object.

Lastly, we will look at DELETE. In the example below, we still need to specify the method and the headers, but no body is needed.

// DELETE request
return fetch(`${RESOURCE}/${id}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            "Accept": "application/json"
        }
    })
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    });

Conclusion

And that's the basics of server communication with JavaScript. I hope you found this article helpful. If you would like to learn more, I have linked resources below. Happy coding.

Useful Resources:

HTTP request methods

Introducing JSON

Objects in JavaScript

Big List of Free and Open Public APIs (No Auth Needed)

HTTP Headers

Difference Between Content-Type and Accept Headers