HTTP request: Fetch vs Axios

HTTP request: Fetch vs Axios

The bedrock of any programming language is the ability to make requests from an API. The absence of this means we are operating a static non-dynamic application. Data fetching is key in software development, as the majority of the data we would be needing to operate with comes from an API. Using JavaScript means we are building a dynamic web application that fetches data from an API and also sends the same, hence, we will be using some methods to fetch these data from its source, receive these data and also send some information to an API where they will be processed and used. This calls for the use of data-fetching methods.

In JavaScript, there are several methods and ways through which you can make your HTTP requests, but we will be talking about the two most used HTTP clients;

1. Fetch

2. Axios

These two HTTP clients are used to build CRUD (Create, Read, Update, Delete) operations. A CRUD operation is used to perform certain requests and calls from and to an API. There are mainly four HTTP request methods that can be performed using either Fetch or Axios:

  1. GET: Used to request data from a resource.

  2. POST: Used to send data to a resource.

  3. PUT: Used to update data in a resource.

  4. DELETE: Used to delete data in a resource.

Both of these methods have some differences and similarities, and I am sure as we take a deeper dive in each one, we will discover them. Hang on with me as we explore them together.

FETCH:

Fetch is a method that stemmed out of the Fetch API interface. The Fetch API is a native JavaScript API and it is available in all modern browsers. Since it is an in-built JavaScript API, you do not to install it.

Fetch returns a Promise. A promise is used to handle asynchronous operations in JavaScript. It holds the result of the operation in 3 stages; pending, fulfilled or rejected.

Now back to Fetch, let’s see in practical terms how Fetch is used.

Fetch can be used for data fetching in 2 ways;

1. USING FETCH WITHOUT CONFIGURATION SETTINGS:

When using fetch without configuration settings, the default method for Fetch is a GET. That means you are trying to pull data from a resource.

fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    });

The result of our fetch is thus:

Using this method, Fetch knows you are performing a GET operation, so you don't necessarily need to do this fetch.get('https://jsonplaceholder.typicode.com/users').

2. USING FETCH WITH CONFIGURATION SETTINGS:

When setting configurations with Fetch, a lot of parameters can be set manually, such as method, headers, data etc. This method is more suitable if you need to stringify the data, if you are expecting a different content-type, if you need to set a timeout for the page etc.

const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

fetch('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    body: JSON.stringify(newUser)
})
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    });

This code above is a POST method, meaning we are sending data to an API. The data we are sending is the newUser object, and if you see the id in the response below, you will see the id has been updated to 11.

.then() is where the promise is handled. It either resolves or rejects the response from the API. When it resolves, we then convert our response to json(), after which we use another .then() to receive the data we are expecting.

To handle error in fetch, you use the .catch() method.

fetch('https://jsonplaceholder.typicode.com/users', )
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log(error.message)
    })

And if you want to create a custom error message, you can do this:

fetch('https://jsonplaceholder.typicode.com/users', )
    .then((response) => {
        if (!response.ok) {
            throw new Error(
                `This is a ${response.status} error`
            )
        }
        return response.json()
    })
    .catch((error) => {
        console.log(error.message);
    })

POINTS TO NOTE:
The object you are expecting from the API is in the response object.
Fetch does not convert its data to json by default.
When sending or updating data to an API, your content will always be in the body property. Also, always remember to JSON.stringify() your content.
Always set content-type to application/json or your preferred type.

AXIOS:

Axios is a third party library that allows you to make HTTP requests. And just like Fetch, it returns a promise.

To install axios, you can run this code as it pertains to you.

Install using npm
npm install axios

Install using yarn
yarn add axios

Like Fetch, Axios can be used for data fetching in 2 ways;

1. USING AXIOS WITHOUT CONFIGURATION SETTINGS:

Using axios without configurations is a default GET method. And that is used when we are trying to fetch data from the resouce. Let's get at it.

axios('https://jsonplaceholder.typicode.com/users')
    .then((response) => {
    console.log(response.data);
})

The result will be the same as Fetch, only difference is that the result will be found in an array inside the data file**.**

2. USING AXIOS WITH CONFIGURATION SETTINGS:

Using axios with configuration parameter isn't much different from Fetch. The two obvious difference being that content is attached to data, as against body in Fetch, and you don't need to stringify the content as axios automatically converts it's data into json(). Let's see for ourselves.

    const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

axios('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    data: newUser
})
    .then((response) => {
        console.log(response.data);
    })

This is not an array because it is a single object. Moreso, the result is the same as the Fetch Method.

We can also write the code like this and get the same result:

    const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

axios({
    url: 'https://jsonplaceholder.typicode.com/users' 
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    data: newUser
})
    .then((response) => {
        console.log(response.data);
    })

Like Fetch, .then() is where the promise in axios is handled. It either resolves or rejects the response from the API.

To handle error in axios, you use the .catch() method.

axios('https://jsonplaceholder.typicode.com/users')
    .then((response) => console.log(response.data))
        .catch((error)=>{
        if (error.response) {
        // When a request is made but the resource returns an error
        console.log(error.response.data);
        console.log(error.response.status);
    } else if (error.request) {
        // When the request is made but no response from the resource.
        console.log(error.request);
    } else {
        console.log('Error', error.message);
    }
})

POINTS TO NOTE:
The object you are expecting from the API is in the data object.
Data is automatically set to the json format by default.
When sending or updating data to an API, your content will always be in the data property. Also, no need to stringify your content.

Hope this was helpful. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.

Thanks and have a great day.