Using Axios to Make API Requests With VueJS

Part 1 of 4 in Your Guide to Using an API with VueJS/NuxtJS and Axios
Dan Pastori avatar
Dan Pastori August 2nd, 2020

Let’s start with the basics, making API requests with Axios from within VueJS. This will give us a solid foundation to work from as we get into more complex requests.

If this is your first time working with an API, it can seem intimidating. However, once you learn the basics, APIs begin to make a lot more sense. You can then apply these principals to figure out how to make tools and integrate with a variety of platforms.

Types of Requests

Let’s start with the types of API requests you can make with Axios.

GET Request

This is probably the request you are most familiar with. Every time you request a web page through the web browser, you run a GET request. GET requests essentially “get” data from a server in the form of HTML, XML, JSON, an image, etc.

You can also pass data to the API with a GET request. Be aware though, that the data will be passed through a string in the URL. Ever see a clean URL with ?variable=xyz&another=123? That’s how you pass data using a GET request. Not ideal if you need to pass secure information, but wonderful if you need to limit what’s returned! For passing data securely (granted everything is configured on your server correctly), that brings us to our next type of request.

POST Request

The POST request is used when you need to send data to a server with the intent of creating a resource or submitting a form such as a login or registration form. POST requests pass data through the body of the request. Assuming you are using https:// (which you better be!) this should be a secure way to send data to the server.

PUT Request

This is a relatively new “HTTP Verb” which is meant to be used to send data to update a specific resource, not create a resource like POST. When working with properly structured APIs (or creating them), it’s important to use the right verb. Other developers can integrate easily and read your code with the right intent. There’s one more verb that comes with the intent of “updating” a resource and that’s the PATCH request.

PATCH Request

Very similar to the PUT request, the PATCH request is meant for updating a specific resource in an API. Now, when should you use each? Well they both have a specific purposes. The difference is slight but really important.

The PATCH request should be used when you need to send part of a piece of data to update on an API, where PUT should be used when you essentially want to replace an entire resource with an updated resource. Let’s think about this example. Say we have an API that works with music. You have a song resource at /api/v1/songs. The user wants to change the name of the song only. They’d submit a PATCH request to /api/v1/songs/{id_of_song} with just the name of the song. The intent of the PATCH request is to update the name in the database, and if the API is designed correctly, that’s what it should do.

Now, if there was a form where you could edit all of the information about the song (name, artist, album), you’d send a PUT request to the /api/v1/songs/{id_of_song} with the entire song resource. This would update every attribute on the song submitted by the user.

DELETE Request

This request is probably the most straight forward. You submit a DELETE request when you want to delete a resource from the API. That’s it, nothing real special to it.

Now that we have a little background on what types of requests you can send, let’s get to it!

Installing Axios

For all of the different ways to install Axios, visit their installation documentation. When I create a VueJS app I use NPM or Yarn, so I’d run either:

npm install axios

or

yarn add axios

If you are using NuxtJS, then you will want to install their Axios module. They have an amazing Axios module that works seamlessly within their framework. There are going to be a few tutorials that are NuxtJS only using this module.

To install this module within your NuxtJS framework, use NPM or Yarn

npm install @nuxtjs/axios

or

yarn add @nuxtjs/axios

Next, you will have to go to your nuxt.config.js file and add the following:

modules: [
  '@nuxtjs/axios',
],

axios: {

}

You’ve now registered the Axios module with your NuxtJS project. The axios key allows you to have a global configuration set up to use on all of your API requests. Super convenient for keeping track of base urls, authorization headers, etc.

We are all set up to make a few requests!

Making an Axios Request

So we’ve went through the different types of requests and installed let’s take a look at how you’d actually create and send a request.

So for every request we mentioned, Axios has a specific method to call to perform one of the requests. Their documentation does a wonderful job of going through these if you need more information. The only thing I’d like to point out is between the GET requests and the POST, PUT, DELETE requests and where you send the data.

If you are making a GET request, the method signature is:

axios.get('https://api.com/your/GET/url', config)

Now if you wanted to pass some query parameters to filter the results (like only grab resources after a certain date) and create a query URL that looks like https://api.com/your/GET/url?date=YYYY-MM-DD you’d add the following configuration:

axios.get('https://api.com/your/GET/url', {
    params: {
        date: 'YYYY-MM-DD'
    }
})

So what’s the point? Well, with a POST, PUT, PATCH request, there are 3 method parameters to those axios methods and you’d send the data as the second parameter (which will put it in the body of the request). A POST request would be like:

axios.post( 'https://api.com/your/POST/url', {
    name: 'name',
    date: 'date'
}, config );

With the explicit data as the second parameter in a POST, PUT, PATCH request, it tripped me up when trying to pass query data in a GET request. Just thought I’d point that out.

Using Axios Within VueJS

This is what we are all looking for right? Making Axios API requests from within VueJS? We’ve got Axios installed in our project, so let’s say we have a simple Vue component that displays all of our users.

export default {
    data(){
        return {
            users: []
        }
    }
}

So how do we get those users into the component from the API? First, let’s start by making Axios accessible within the component by importing it:

import axios from 'axios';

export default {
    // Component data, methods, etc.
}

Now, we can create a method to call the users endpoint and load all of the users! I’d add a method to the component like:

methods: {
    loadUsers(){
        axios.get('https://api.com/v1/users')
            .then(function( response ){
                this.users = response.data;
            }.bind(this));
    }
}

Whoa! There’s a lot going on in there besides just a request, so let’s break it down!

Breaking Down the Request

First, we are loading users, so we need to use a GET request. Essentially, this means we aren’t creating or updating resources, we are just retrieving them.

Next, we are chaining a then() statement to the request. Axios is a promise based HTTP client, meaning that the request is either resolved or rejected (successful or not). This is extremely useful for loading data since we can handle a request and any errors that come with (400, 404, 403, 401 any of the friendly 4xx error codes).

What the then() method chained to the end of the request is doing, is essentially saying “when this request completes successfully, then handle the data returned from the request” (we will be covering errors in a later tutorial). The callback function passed to the then() method accepts the response as it’s first parameter. The response parameter contains all of the details about the response sent back from the server such as header information, status code, and most importantly, data.

Now that our request has been completed, we can set the local users variable to the response.data returned from the API. However, there’s one more thing to note! Within the callback function, we reference this.users . Since the callback function doesn’t have a users variable and no access to the Vue Component’s scope, we need to attach .bind(this) to the end of the callback function. This is extremely important for working with Axios within VueJS. This gives the callback function scope to the Vue component, allowing us to set the component’s local data from the response of the API.

Using Axios Within NuxtJS

Implementing the same request within NuxtJS is very similar, however you don’t have to import Axios every time you need to use it. This is because the module that was installed, is available across all components out of the box.

The main difference you will see in the NuxtJS ecosystem is the more heavily used async/await syntax. This syntax simply makes working with promises a little bit easier to read. You can chain a ton of callback functions after a promise and it gets messy really quick. With async/await, it’s a much cleaner syntax. Using the combination, your script won’t run until the “promise settles and returns its result” – https://javascript.info/async-await.

Let’s see how we’d make the same request with NuxtJS:

methods: {
    async loadUsers(){
       let users = await this.$axios.$get('https://api.com/v1/users');
       this.users = users
    }
}

Breaking Down The Async/Await Request

In half the amount of code, we get the same result! You can use the syntax in straight VueJS as well if you want! By putting the async keyword in front of the loadUsers() method, we are stating that we are working with promises.

Within the method, we have the await keyword. They have to co-exist. The await keyword will return the result of the promise.

The other thing to note is see we are using this.$axios.$get? This is how you access the NuxtJS axios plugin. It’s bound globally which is super nice! Now we don’t have to import it every time (which we will solve in the next tutorial for VueJS).

So let’s assume we that the request goes as planned (terrible to do this as a dev, but for now, errors don’t exist)! The response from the promise will be the users that we want. We will then assign it locally using this.users. There are no callbacks, so we don’t have to bind the local component to the callback function which really cleans up the code!

That’s the exact same request, just from a NuxtJS perspective.

Next Up, Making Axios Global for VueJS

In the next tutorial, we will want to re-use axios globally across the entire VueJS application. NuxtJS has this set up easily with their Axios module, but with the normal VueJS ecosystem, we will have to do this ourselves.

Resources

Axios Documentation: https://github.com/axios/axios
NuxtJS Axios Module: https://axios.nuxtjs.org/

Keep Reading
View the course View the Course Your Guide to Using an API with VueJS/NuxtJS and Axios
Up Next → Configuring Axios Globally with VueJS

Support future content

The Ultimate Guide to Building APIs and Single-Page Applications with Laravel + VueJS + Capacitor book cover.

Psst... any earnings that we make off of our book is being reinvested to bringing you more content. If you like what you read, consider getting our book or get sweet perks by becoming a sponsor.

Written By Dan

Dan Pastori avatar Dan Pastori

Builder, creator, and maker. Dan Pastori is a Laravel certified developer with over 10 years experience in full stack development. When you aren't finding Dan exploring new techniques in programming, catch him at the beach or hiking in the National Parks.

Like this? Subscribe

We're privacy advocates. We will never spam you and we only want to send you emails that you actually want to receive. One-click unsubscribes are instantly honored.