How to Make API Calls in JavaScript

Published: Monday, June 13, 2022

Greetings, friends! In the last tutorial, I discussed APIs and what they are. In this tutorial, we will learn how to make API calls using JavaScript within the browser. As mentioned in my last article, we can make API calls natively in the browser using one of these two APIs:

  1. XMLHttpRequest (XHR) API
  2. Fetch API

Yes, we're using an API to call an API. How does that work? The XHR API and Fetch API are sets of tools created by developers who worked on the browser engine. These tools can be used natively in the browser without installing any third party packages. We'll be using a XHR object or fetch method to make a call to an API.

When we make an API call using an XHR object or fetch method, we are communicating to an external API to make updates or fetch data. In this sense, the term, "API" appears to take on two definitions. However, I often like to refer to an API as any kind of tool created by developers that other developers can use. We are using a tool to talk to another tool. We are using an API to communicate with another API.

There are technically other ways to interact with a server in the browser besides using the XHR API and Fetch API. However, I will only talk about these two methods as they are most commonly used to make updates to a page on a website asynchronously, so we don't have to refresh the whole page.

JSONPlaceholder API

In this tutorial, we will make API calls to the JSONPlaceholder API. This API is free and is not blocked by the cross-origin resource sharing policy. This means that you can make API calls freely from your app to their server without any sort of authentication or authorization. The JSONPlaceholder API is a great way to experiment with making API calls. You can use it to make API calls with the four most common HTTP request methods: GET, POST, PUT, DELETE. These four operations are sometimes referred to as CRUD operations in the context of RESTful APIs.

We will make a GET request to https://jsonplaceholder.typicode.com/posts. Notice that you can actually visit this link and see all the data as an array of objects in the browser. That is because the browser makes a GET request when you enter something in the URL address bar and hit Enter or Return on your keyboard. The server hosting the API will then return results based on the URL you entered into the browser.

Using XHR Objects

Before the Fetch API existed, developers had to use XHR objects to make API calls if they wanted to make updates to their website asynchronously. The fetch method makes it much easier to make API calls, but XHR objects still have their own set of advantages.

Let's make a simple GET request to the JSONPlaceholder API using an XHR object and the XHR API.

javascript
Copied! ⭐️
const getPosts = () => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
    xhr.responseType = 'json';
    xhr.onload = () => {
      console.log(xhr.response);
    }
    xhr.send();
};

getPosts();

When you run this code in the browser, you should see an array of objects. You just fetched data from an API using an API call! We create an xhr object by calling new XMLHttpRequest(). Then, we have to call special methods on this object to setup some configuration.

We call the xhr.open method to set the HTTP request method as GET. We also set the xhr.responseType to json because we are fetching data from an API that replies back with JSON data. The xhr.onload function describes anything we want to do with the data once we get it back from the server. In our case, we are logging the response, stored in xhr.response, to the console. After our preparations are complete, we call the xhr.send method to make the API call and send the request to the server to fetch data for us.

We could have also grabbed a single post instead of all of them by using this URL instead: https://jsonplaceholder.typicode.com/posts/1. The only difference is the /1 at the end of the URL.

Let's change our code a bit to grab only one item.

javascript
Copied! ⭐️
const getPost = (num) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `https://jsonplaceholder.typicode.com/posts/${num}`);
    xhr.responseType = 'json';
    xhr.onload = () => {
      console.log(xhr.response);
    }
    xhr.send();
};

getPost(1);

You should get back a single object instead. It'll probably contain some Latin. When creating dummy data, developers like to use Lorem ipsum as placeholder text.

json
Copied! ⭐️
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Using Fetch

When making lots of API calls, working with XHR objects start getting messy. The Fetch API was invented to make API calls simpler and perhaps more flexible. The biggest advantage of the Fetch API is that it returns Promises. Promises are used frequently in modern JavaScript because they help make the code cleaner and more intuitive.

Let's make an API call to the JSONPlaceholder API using the fetch method instead.

javascript
Copied! ⭐️
const getPost = (num) => {
  fetch(`https://jsonplaceholder.typicode.com/posts/${num}`)
    .then(response => response.json())
    .then(data => console.log(data));
};

getPost(1);

Seems easier to read, right? By default, the Fetch API will make a GET request. There's less configuration we have to setup compared to XHR objects. We simply get back the response wrapped in a promise and call the response.json() method to get the data from the JSONPlaceholder API.

If you wanted to make a POST request, we could have written the following code:

javascript
Copied! ⭐️
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
})
  .then((response) => response.json())
  .then((json) => console.log(json));

If the POST request is successful, the JSONPlaceholder API will return the ID of the post that was updated.

json
Copied! ⭐️
{"id": 101}

Note, however, that this API is meant for testing purposes only. If you try changing data using a POST request, you likely won't see those changes applied when you perform a GET request to look at that data.

Conclusion

We have now seen the two main ways to make API calls using JavaScript in the browser. You can use the JSONPlaceholder API in any language though! You can make API calls using Ruby, C#, Java, or any other language that supports making HTTP requests to a server.

Resources