The best way to learn something or solve a problem is to break it down into the smallest pieces. While transitioning from Axios to the Fetch API and integrating it into my VueJS application, I had to start small. I actually wrote both requests side by side so I could migrate in pieces and ensure the integrity of the app. In this tutorial, we are going to be making some basic GET requests using Fetch and comparing those requests to Axios.

I tend to learn best when I need to solve a problem and apply new tools to do it. For this course, I’m building a budgeting app (I actually am too as a side project, if it ever gets polished up, we’ll release it). This will provide a great example of the different use-cases we need to account for during our migration.

Since Fetch is a web browser API, there’s no need to configure it globally! All methods are made available through the web browser. For this tutorial we are just creating a simple VueJS component. This VueJS component will call the /api/v1/transactions endpoint on our API through both the Fetch API and Axios so you can see how they both work.

Step 1: Create your API Request

For loading our transactions, I made 2 methods (one with the Fetch API and the other with Axios) within the same component. I’ll show both of the methods and then break down the differences.

Fetch API GET Request

methods: {
    loadAxiosTransactions(){
        fetch( this.API_BASE_URL+'/api/v1/transactions' )
            .then( function( response ){
                if( response.status != 200 ){
                    console.log( response.status );
                }else{
                    response.json().then( function( data ){
                        this.response = data;
                    }.bind(this));
                }
            }.bind(this))
    }
    ...
}

Axios API GET Request

methods: {
    loadAxiosTransactions(){
        axios.get( this.API_BASE_URL+'/api/v1/transactions' )
            .then(function( response ){
                this.response = response.data;
            }.bind(this))
            .catch(function( error ){
                this.error = error;
            }.bind(this));
    }
    ...
}

I also had to import the library in to our component:

import axios from 'axios';

So those are our two requests! From first glance, they are extremely similar! In the next step, we will break down the differences.

Step 2: Breaking Down the Method Signature

So these are very simple GET requests, we will get to the more advanced stuff later on, but starting here we can begin to see the differences between the two requests.

So to make the request, the method signature is very similar. Fetch API uses fetch( END_POINT_URL ) and Axios uses axios.get( END_POINT_URL ). Right away you can see that Axios provides a method where you can explicitly call the HTTP Verb of GET. You can also do that with:

axios({
    method: 'get',
    url: END_POINT_URL
})

or using their default (which looks just like a Fetch API request):

axios( END_POINT_URL )

I prefer the .get() when using Axios, just because it’s easy to read and very explicit.

Fetch API doesn’t provide that explicit .get() method. Nor does it apply the .post() method when we get to that later. To specify more options to your request, the method allows for a second parameter which is an object of configuration. We won’t touch on that now, but it will look very similar to the Axios method without the explicit .get().

Step 3: Breaking Down the Method Response

This is where the two methods differ a little bit. Both return promises which is nice and both work with async/await. However, the fetch() API returns a Response object when the request completes successfully. This object has a ton of methods and settings you can work with!

Axios returns the response in an object as well and it’s accessible through response.data. To get the data from the request with the Fetch API you can call a method on the Response object. In our example we called .json() which returns another promise.

However, let’s take a step up one block of code and look at:

if( response.status != 200 ){

We first check to see if the response completed successfully. Within the Fetch API, the promise will be resolved even if there was a server side error. Axios allows you to catch the server side error with .catch(). For me, I can see this being a hard habit to break, I like the .catch() syntax.

There’s another handy method which is response.ok which checks to make sure the status code is a 2XX status code (perfect for 204 and other API type responses).

If we don’t get an error in our Fetch API request, we then call response.json() and chain another promise to load our data:

response.json().then( function( data ){
     this.response = data;
}.bind(this));

This is called on the implemented Body interface. There are a variety of other methods you can parse your response body with as well depending on your circumstance.

One thing to note about both of these functions is the .bind(this) at the end of them. That statement gives the methods scope to our VueJS component so we can set local variables within it. You have to bind twice since there’s a child promise returned in the Fetch API when you convert the response to json().

Conclusion

So this is beginning our journey of learning the Fetch API alongside Axios. So far, in my opinion, what I like about the Fetch API is:

  • No external library
  • Powerful enough to give you access to the data and settings you need

What I don’t like about the Fetch API is:

  • Parsing the data with another promise (response.json) feels weird.
  • Not catching server side errors with .catch() will be a hard habit to break.

I’m looking forward to doing some data creation with both libraries and eventually authentication (both handling oAuth Tokens and Laravel Sanctum). Also, I’m interested to see how we can make some API wrappers with Fetch API like we did with Axios.

For the rest of the series, I’ll be focusing on the side-by-side comparison with Axios and using them both within VueJS. Matt Netkow over at Ionic wrote a super helpful article about switching to Fetch as well.

On to more advanced requests!