Integrating Axios in a Vue Component to Communicate with an Outside API
This is going to be a really fun guide. In this guide we're finally going to connect to an outside API service, and we're going to pull real data in from another application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So before we can get started on this, we are going to bring in a library that is going to allow us to effectively communicate with that service. So any time that you are communicating with an API or some type of service the way we're going to, you need to have a proper set of rules for your application.

So in other words you need to set up a step by step process for how your application is going to be able to communicate with that other app. So what we're going to do is bring in a library called Axios.

So in order to do that you can open up the terminal and run npm install --save and then from there just type axios and that is going to add it to our package json file and then it's also going to bring this library down and install it in our node modules directory so that we can import it into any component that needs to communicate with the outside world.

So it looks like that worked.

large

I'm going to close that off and now inside of the home page component right under the script tag I'm going to import it. So I'll say import axios and just like this you don't need to do something like put curly braces around it or anything and the reason for that is because axios is exported as the default name.

So I'm gonna say import axios from axios, and now that we have that we have access to work with it. Now if you go to the axios documentation, so let's go to axios and if you go to that and actually it would be a good idea to say js because I guess there are some companies that are called that.

So if you click on this axios this is one of the most popular libraries for communicating with outside API's. But one thing I will mention is that if you went and tried to simply copy and paste some of their documentation, then you might run into some confusing bugs.

The main reason is because they are using function calls here, and what that is going to do is it's going to change the scope of the word this though what I'm going to do is I'm going to have something similar to this but I'm going to use arrow functions and this is a great example of when you want to use arrow functions and how they really help streamline your process with using the this keyword.

So I'm going to come down and right underneath submit query, I'm going to add a new line here. So this new method here is going to say getRecentPosts just like this. It's not going to take in any arguments and then inside of it we are going to do a few things. First we need some kind of data element inside of our application or inside of our component.

So inside of data return I'm going to say recent posts and I'm gonna set this equal to an empty array now inside of here what I'm going to do is now I can actually have a piece of data that I can work with. So now I'll say axios.get and now what axios expects here with the argument to its get function is whatever path we're wanting to communicate with.

So right here I have the documentation to the dailysmarty API and if you want to find the most recent posts you can just click on that box and now let's just copy this link here

large

and you can go to this directly in the browser, and this is the data from the API.

large

Now you're also seeing exactly why you need to have some tool for using it because this is not the most user friendly way of seeing this data. But our application is going to be able to take in this data, parse through it because it's just json data it's just javascript object notation and then it's going to be able to render it on the screen.

So let's come here to our Homepage.vue I'm going to paste in that url just like this. And now what we can do is we can go out and we can tell axios what we want to do with it when it comes back with a successful message or if it comes back with an error.

Now one other thing I want to point out with the axios documentation because it's very important to understand this, is right here, what you see in its description it says axios is a promise based HTTP client for the browser and node.js

large

What this means is if you remember back to when we discussed modern JavaScript and working with promises what this means anytime you see the word promise inside of a library. That means that you are expected to use the word then in order to get the data. So when we call axios.get this is going to go out and it is going to attempt to get this API data, but you cannot simply say store this in a variable.

So I can't just say something like this.results = axios.get because then all I'm going to be doing is storing the promise. What you need to do is and this is the same for all javascript promises at the very end here. You need to say axios.git and then you say then and I'm going to put it on a different line.

So I'm going to say .then and then inside of here then expects a function. So I'm gonna say response and here is that key difference between the documentation and how we're going to do it. So you say response arrow function and now inside of here let's just console log this out. So I'm going to say console log and now say response.data.posts.

Homepage.vue

getRecentPosts() {
    axios.get("https://api.dailysmarty.com/posts").then(response => {
        console.log(response.data.posts);
    });
}

Now if you're curious on how I came up with that, if you come back to the documentation you can see that what gets returned here is all of these posts.

large

So you get access to all of that data and if you come to the link I sent you, notice how the very first element here is post.

large

So what this means is that posts is the key here, and because this is an object we were able to just say .post and this is going to bring it back to us, so we're going to have response data. So inside of our response from axios we have access to a data element and then inside of the data is that set of posts.

So let's just see if this is working now, so I'm going to come here and let's just hit refresh and say, OK so that just a dumb thing here, I didn't actually call it a function, that would probably be a good idea.

So now we also actually have to call the function and I'm going to put it inside of another lifecycle method here. So before mount once again this is one of my favorite ones to use, inside of here let's say this.getRecentPosts and then call it like a function and then add a comma there, that would be an important thing.

Homepage.vue

export default {
    name: "Homepage",
    data() {
        return {
            recent_Posts: []
        };
    },
    beforMount() {
        this.getRecentPosts();
    },
    methods: {
        submitQuery(evt) {
            this.$router.push({
                name: "SearchResults",
                params: {query: evt.target.value }
            });
        },
        getRecentPosts() {
            axios.get("https://api.dailysmarty.com/posts").then(response => {
                console.log(response.data.posts);
            });
        }
    }
}

The function, remember by itself inside our methods doesn't do anything until it's been called. So now you can see that this is actually working. So if we click here you can see that we got an array of posts and this is all of the data coming from this live API.

large

So that is pretty cool, that means that everything's working, our axios call is working so that's exciting. Now if I come down here, it's really considered a best practice to make sure that you always end your get requests and so when you say .then you also have the ability to say .catch.

So I'm going to come down one more line and say .catch and then I'm going to catch any errors, and then for right now I'm just going to log them out. So I'll say log and inside of here we're just going to capture that error and print it out to the console.

Homepage.vue

getRecentPosts() {
    axios
    .get("https://api.dailysmarty.com/posts")
    .then(response => {
        console.log(response.data.posts);
    })
    .catch(error => {
        console.log(error);
    });
}

And the reason for this is because all API's any time that you have a connection to some outside service even if it's one you built.

There's always a chance that there could be some kind of error or bug in that program and so maybe their server is down or who knows what it could be. So you always want to make sure that you're listening for that and that you're capturing it. In a full production application what you would do is you would also update something on the screen and you'd say something like it looks like there's a problem connecting to the service, please try again later or something like that.

Let me save this and now let's see if this is all still working. And yes it is, I'll clear this and just hit refresh and there we go, we get our ten most recent post. Now before we take a little break let's also add this to our data component.

So instead of just logging it out I'm gonna say this.recentPosts and then from there what we can do is we can actually push to it. So I'm going to say push which is because recent post is an array remember we created recent posts up here inside of our data. We said I want you to start out as an empty array, so push is just a method you can call on empty arrays and then we want to pass in the data we're getting.

So there is one little trick with this, if you've never worked with the JavaScript's spread operator this may look a little weird but you need to say ... and then response.posts. And the reason for that is because we are pushing an array into another array. So if we don't put these dots if we don't put this what's called a spread operator then what's going to happen is we're going to end up with two arrays we're going to have one array which is our recent post and then we're going to have a second array that contains all the posts.

Homepage.vue

getRecentPosts() {
    axios
    .get("https://api.dailysmarty.com/posts")
    .then(response => {
        this.recentPosts.push(...response.data.posts);
        console.log(response.data.posts);
    })
    .catch(error => {
        console.log(error);
    });
}

But instead what we want is we just want to push all of the elements inside of here. So everything that you saw right here what push does with the spread operator. It's kind of like we're iterating over the entire collection and we're saying I just want you to take each one of these and I want you to add them to recent posts. So I'm going to come up top and let's just make sure that this is working.

So I'm going to come inside of our template I'm going to use a pre tag. So this gives some pre formatting which just makes it a little bit easier to see json code and inside of here let's just say recent posts.

Homepage.vue

<template>
    <div>
        <h1>Homepage</h1>

        <input type="text" @keyup.enter="submitQuery">

        <pre>
            {{ recentPosts }}
        </pre>
    </div>
</template>

Remember we don't have to say this when we're inside of the template. And now I'll hit save, and there we go, it's all getting rendered out to the screen right here.

large

So we have a post with an ID, a title, it has content, it has a URL for the posts, it has everything that we need right here so this is really cool. So we are now communicating with an outside service and it's working really well.

Great job if you went through that, you now know how to communicate with an outside API and bring the data into your own application. In the next guide, we're going to see how we can parse through this data and render it on the screen so it actually looks good.

Resources