How to Consume REST APIs Using Fetch and Axios

A beginner’s guide to fetching data from REST APIs in JavaScript.

Natasha Ferguson
5 min readDec 18, 2022

JavaScript provides several ways to send HTTP requests and get responses. There are some native as well as third-party libraries that help you send HTTP requests or parse a JSON response. In this article we’ll focus on getting data from APIs using Fetch API (native JavaScript REST API), XMLHttpRequest (a built-in API in JavaScript) and Axios (one of the most popular third-party packages used for making HTTP requests, a modern alternative to XMLHttpRequest ).

Let’s Start with Fetch

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch(url) method that provides an easy way to fetch resources asynchronously across the network. The API is promise-based.

No need for XMLHttpRequest anymore.

This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers.

For making a request and fetching a resource, use the fetch() method.

fetch(url) returns a pending Promise. Once the network request completes, the promise will either resolve or reject. Any response other than a network error will result in a resolved Promise. The url parameter can be either a string or a URL object.

This method can also take an options object as a second parameter. Some of the common options are:

  • method — the request method as a string, such as 'GET' or 'POST'
  • body — the body of the request, often used to pass FormData
  • headers — headers to be added to the network request, often by creating a Headers object, although a standard object can be used as well.

When a request comes back from the server, the Promise returned by fetch will resolve to a Response object. This object has a number of properties and methods for interacting with the network response. These are some of the most useful ones:

  • response.text() returns a promise with a text representation of the response body.
  • response.json() returns a promise with an object representation of the response body.
  • response.status gives a numerical representation of the response status code. A successful request in the 200–299 range will be true, everything else evaluates to false.
  • response.hearders gives a Headers object containing the headers included with the response.

A basic fetch request is really simple to set up:

First, you are passing in the API URL to the fetch() method. fetch() returns an HTTP response which is converted to JSON using the json() method. You get access to the data which you can then use in your application. Finally, the catch block allows you to handle errors.

const BASE_API = 'https://www.boredapi.com/api/activity';

fetch(BASE_API)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err))

// output
{activity: 'Go to a karaoke bar with some friends',
type: 'social',
participants: 4,
price: 0.5,
link: '',
…}

Want to learn more about Promises? Check out my below post:

Since Fetch is based on async and await, the example above might be easier to understand like this:

Async Function Example

const BASE_API = 'https://www.boredapi.com/api/activity';

async function main(){
try{
const response = await fetch(BASE_API)
const obj = await response.json()
console.log(obj)
} catch(err) {
console.log(err)
}
}
main()

// output
{activity: 'Learn about a distributed version control system such as Git',
type: 'education',
participants: 1,
price: 0,
link: 'https://en.wikipedia.org/wiki/Distributed_version_control',
…}

Learn more about async/await:

The pre-fetch approach using XMLHttpRequest

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh.Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

XMLHttpRequest() constructor initializes an XMLHttpRequest. It must be called before any other method calls.

The load event is fired when an XMLHttpRequest transaction completes successfully.

XMLHttpRequest.responseText Returns a string that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.

XMLHttpRequest.open() initializes a request.

XMLHttpRequest.send() sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.

const BASE_API = 'https://www.boredapi.com/api/activity';

const request = new XMLHttpRequest();

request.addEventListener('load', function() {
const data = JSON.parse(request.responseText);
console.log(data)
})

request.open('GET', BASE_API)
request.send()

// output
{activity: 'Explore a park you have never been to before',
type: 'recreational',
participants: 1,
price: 0,
link: '',
…}

Consuming REST APIs Using Axios, a promise-based HTTP Client

Instead of fetch(), you can consume APIs with Axios. Like fetch(), Axios allows you to make promise-based requests to an API endpoint. However, there differences between the two:

  • Axios automatically returns the response in JSON while you have to convert it to JSON when using the Fetch API.
  • Axios requires only one .then() callback unlike the Fetch API.

Install Axios by running the following command:

$ npm install axios

For cases where something went wrong when trying to import a module into a custom or legacy environment, you can try importing the module package using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Example of performing a GET request with Axios:

const BASE_API = 'https://www.boredapi.com/api/activity';

axios.get(BASE_API)
.then(function (response) {
console.log(response.data)
})
.catch(function (error) {
console.log(error)
})

// output
{activity: 'Do something nice for someone you care about',
type: 'social',
participants: 1,
price: 0,
link: '',
…}

In summary, in this tutorial, you leart about the JavaScript Fetch API and Axios and how to use them to make asynchronous HTTP requests. The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. If you have worked with XMLHttpRequest (XHR) object, the Fetch API can perform all the tasks as the XHR object does. In addition, the Fetch API is much simpler and cleaner. It uses the Promise to deliver more flexible features to make requests to servers from the web browsers. Sending HTTP requests to your API with Axios is a great approach. It has support for multiple request, response interception,
efficient error handling and automated JSON data translation. Axios makes handling HTTP requests and responses a snap.

--

--