Using Fetch API with Vue.js (Part 1 of 4)

Basic GET Requests with Fetch API and VueJS

Dan Pastori

November 18th, 2020

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

Fetch API Example

methods: {
    loadFetch(){
        fetch( 'https://api.roastandbrew.coffee/api/v1/companies' )
            .then( function( response ){
                if( response.status != 200 ){
                    throw response.status;
                }else{
                    return response.json();
                }
            }.bind(this))
            .then( function( data ){
                this.fetchResponse = data;
            }.bind(this))
            .catch( function( error ){
                this.fetchError = error;
            }.bind(this));
    }
}

Axios API GET Request

Axios API Example

methods: {
    loadAxios(){
        axios.get(' https://api.roastandbrew.coffee/api/v1/companies' )
            .then( function( response ){
                this.axiosResponse = response.data;
            }.bind(this))
            .catch( function( error ){
                this.axiosError = error;
            }.bind(this));
    }
}

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

Import the Axios module

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:

Define the GET method on an Axios Request

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

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

Use the default GET call

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:

Ensure we have a valid response code

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:

Access the JSON response returned from the server

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.

If you want to see the actual components that make these Fetch API requests, head over to our Github repo. The Fetch API could also be used instead of Axios if you are creating an API driven web and mobile application. Feel free to reach out if you have any more questions.

On to more advanced requests!

Want to work together?

Professional developers choose Server Side Up to ship quality applications without surrendering control. Explore our tools and resources or work directly with us.

Join our community

We're a community of 3,000+ members help each other level up our development skills.

Platinum Sponsors

Active Discord Members

We help each other through the challenges and share our knowledge when we learn something cool.

Stars on GitHub

Our community is active and growing.

Newsletter Subscribers

We send periodic updates what we're learning and what new tools are available. No spam. No BS.

Sign up for our newsletter

Be the first to know about our latest releases and product updates.

    Privacy first. No spam. No sharing. Just updates.