Make a request to an API with Axios in Vue

Rory Smith
InstructorRory Smith

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

Let's see how to use the vue-axios NPM package to make a request to an API, and make use of the data returned.

[00:00] We'll start by adding axios and vue-axios as dependencies to our project. Then in our JavaScript let's import vue, axios, and vue-axios and then we'll use vue.use to install the plugins.

[00:15] Now, let's specify some data. We're going to make an app which queries the GitHub API for a user. We'll set an empty username value, which is going to be specified by the user, an empty data array, which will be populated when we make the API request, and an empty error message, which will change to a helpful error message should we encounter an error.

[00:39] Let's start writing our template. We'll have a form, which will execute the search method on Submit and we'll write the search method in just a moment. Inside the form is going to be a text input field and it's going to be bound to the username value that we specified in our data.

[00:57] Then, underneath the form, we'll make a paragraph which is only going to show if we've got name and location data for the user that's being searched for. If there is data, let's show the name, the login, and the location of the user. Otherwise we'll show an error message.

[01:16] The only thing left to do is write our search method, which is going to be run when the user presses Enter from within the text input. Let's set up our API string, which is going to be the GitHub API URL with the user-specified username value at the end.

[01:32] Then, we'll use the Get method of axios on the API and we'll assign to our data array the response.data that comes back. If there's no user found we'll set a helpful error message for the user and then we'll reset our data array to an empty array.

[01:51] Let's save and try out our app in a browser. Sure enough, here's the data being returned. Importantly, we can verify the data that we're getting back with the help of vue dev tools.

Devan Beitel
Devan Beitel
~ 5 years ago

What is the advantage of using vue-axios?

Rory Smith
Rory Smithinstructor
~ 5 years ago

vue-axios is a small wrapper that allows you to 'glue-together' Vue with Axios :)

alex rodriguez
alex rodriguez
~ 4 years ago

What editor/IDE are you using in this video?