Flow for User Registration and User Login
You’re browsing the documentation for v2.x and earlier. For v3.x, click here. There are many times when building application for the web that you may want to consume and display data from an API. There are several ways to do so, but a very popular approach is to use axios, a promise-based HTTP client. In this exercise, we’ll use the CoinDesk API to walk through displaying Bitcoin prices, updated every minute.
First, we’d install axios with either npm/yarn or through a CDN link. There are a number of ways we can request information from the API, but it’s nice to first find out what the shape of the data looks like, in order to know what to display.
In order to do so, we’ll make a call to the API endpoint and output it so we can see it. We can see in the CoinDesk API documentation, that this call will be made to https://api.coindesk.com/v1/bpi/currentprice.json.
So first, we’ll create a data property that will eventually house our information, and we’ll retrieve the data and assign it using the mounted lifecycle hook:.
And what we get is this:. See the Pen First Step Axios and Vue by Vue (@Vue) on CodePen. We’ve got some data. But it looks pretty messy right now so let’s display it properly and add some error handling in case things aren’t working as expected or it takes longer than we thought to get the information.
Run Vue.js 3 CRUD example
Setup Vue 3 Project
It’s pretty typical that the information we’ll need is within the response, and we’ll have to traverse what we’ve just stored to access it properly.
- In our case, we can see that the price information we need lives in response.data.bpi.
- If we use this instead, our output is as follows:.
Add Navbar and Router View to Vue 3 CRUD example
See the Pen Second Step Axios and Vue by Vue (@Vue) on CodePen. This is a lot easier for us to display, so we can now update our HTML to display only the information we need from the data we’ve received, and we’ll create a filter to make sure that the decimal is in the appropriate place as well.
See the Pen Third Step Axios and Vue by Vue (@Vue) on CodePen.
There are times when we might not get the data we need from the API. There are several reasons that our axios call might fail, including but not limited to:.
The API is down. The request was made incorrectly.
The API isn’t giving us the information in the format that we anticipated. When making this request, we should be checking for just such circumstances, and giving ourselves information in every case so we know how to handle the problem.
How to handle errors in Axios
In an axios call, we’ll do so by using catch. This will let us know if something failed during the API request, but what if the data is mangled or the API is down?
Right now the user will just see nothing. We might want to build a loader for this case, and then tell the user if we’re not able to get the data at all.
You can hit the rerun button on this pen to see the loading status briefly while we gather data from the API:.
See the Pen Fourth Step Axios and Vue by Vue (@Vue) on CodePen. This can be even further improved with the use of components for different sections and more distinct error reporting, depending on the API you’re using and the complexity of your application.
The Fetch API is a powerful native API for these types of requests. You may have heard that one of the benefits of the Fetch API is that you don’t need to load an external resource in order to use it, which is true!
Except… that it’s not fully supported yet, so you will still need to use a polyfill. There are also some gotchas when working with this API, which is why many prefer to use axios for now.
What is Axios?
This may very well change in the future though. If you’re interested in using the Fetch API, there are some very good articles explaining how to do so.
There are many ways to work with Vue and axios beyond consuming and displaying an API.
You can also communicate with Serverless Functions, post/edit/delete from an API where you have write access, and many other benefits.
Due to the straightforward integration of these two libraries, it’s become a very common choice for developers who need to integrate HTTP clients into their workflow.
Caught a mistake or want to contribute to the documentation?Edit this on GitHub!Deployed onNetlify .
In this tutorial we learn how to use the popular Axios API for HTTP requests in Vue. We cover some of its benefits, error handling and the convenience methods that allow us to easily get, post, update and delete data.
If you want to follow along with the examples in this lesson, you will need an app generated by the Vue CLI.
Axios was inspired by theHTTP service in Angularand is built with the following features. MakesXMLHttpRequestsfrom the browser. Makeshttprequests from Node.js. Supports thePromise API.
Configure Port for Vue 3 CRUD example
Intercepts requests and responses. Transform request and response data. Ability to cancel requests. Automatic transformation of JSON data.
Client side support for protecting againstCross Site Request Forgery (XSRF). In this lesson we will show examples of how to use Axios with theJSONPlaceholderservice.
It’s a free online REST API with fake data that makes it easy for us to focus on learning Axios with Vue, instead of worrying about setting up a database. Everything we learn here will be applicable to whatever API you’re using, like Firebase. You can install Axios with npm by executing the following command in your project folder.
Vue.js 3 Component Diagram with Vue Router & Axios
tipIf you’re working in VSCode, you can go toTerminal>New Terminalto open a terminal or command prompt with the project folder already selected. Alternatively, you can useyarnorbower.
How to delete data with axios.delete
Once the installation is complete, you should see Axios in the list of dependencies in yourpackage.jsonfile.
When we want to use it in a component in Vue, we have to import the axios package above the config object in the component’s script block.
If you want to load Axios through a CDN, you can use JsDeliver or unpkg. Axios allows us to send HTTP requests in one of two ways.
We can pass a configuration object to its constructor that consists of at least the request method (get, post etc.) and the url we want to send the request to.
If we’re creating or updating data, we also include a data object. Alternatively, we can use one of the following convenience methods. These methods take up to three arguments, with only the first parameter (the url we want to send the request to) being required. We will use these methods in this lesson. To keep the demonstrations simple, we’ll do everything in the mounted Lifecycle hook.
To receive data with Axios, we use thegetconvenience method with the URL of the API we send the request to as argument.
For our example, we want to fetch only a single blog post from JSONPlaceholder so the url ishttps://jsonplaceholder.typicode.com/posts/1.
The get method will return a response object and because Axios is promise-based, we can chain athenblock to the request to handle the response.
Create Vue 3 Components
As an example, let’s add athenblock and use it to log the data we get back to the console. If we open the developer tools and go to the console, we will see an object in the log. If we expand this object and then itsdataproperty, we will see the post data. So if we want to access values like the post title, we have to do it throughresponse.data.
The Axios API and convenience methods
But logging the data to the console isn’t very useful, so let’s show it in the template block.
The blog posts from JSONPlaceholder contain 4 properties.