Skip to content

Commit c3c5949

Browse files
authored
Write a cookbook entry for axios requests (#1480)
* first section of axios article * add in formatted example, start error section * alternative patterns and finishing up * small final edits * update small text fixes * add in .finally * coindesk => CoinDesk * update functions to have space before parens
1 parent c1d5ce2 commit c3c5949

File tree

1 file changed

+172
-0
lines changed

1 file changed

+172
-0
lines changed
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
---
2+
title: Using Axios to Consume APIs
3+
type: cookbook
4+
order: 9
5+
---
6+
7+
## Simple Example
8+
9+
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](https://github.com/axios/axios), a promise-based HTTP client.
10+
11+
In this exercise, we'll use the [CoinDesk API](https://www.coindesk.com/api/) to walk through displaying Bitcoin prices, updated every minute. First, we'd install axios with either npm/yarn or through a CDN link.
12+
13+
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:
14+
15+
```js
16+
new Vue({
17+
el: '#app',
18+
data () {
19+
return {
20+
info: null
21+
}
22+
},
23+
mounted () {
24+
axios
25+
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
26+
.then(response => (this.info = response))
27+
}
28+
})
29+
```
30+
31+
```html
32+
<div id="app">
33+
{{ info }}
34+
</div>
35+
```
36+
37+
And what we get is this:
38+
39+
<p data-height="350" data-theme-id="32763" data-slug-hash="80043dfdb7b90f138f5585ade1a5286f" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="First Step Axios and Vue" class="codepen">See the Pen <a href="https://codepen.io/team/Vue/pen/80043dfdb7b90f138f5585ade1a5286f/">First Step Axios and Vue</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>) on <a href="https://codepen.io">CodePen</a>.</p>
40+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
41+
42+
Excellent! 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.
43+
44+
## Real-World Example: Working with the Data
45+
46+
### Displaying Data from an API
47+
48+
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:
49+
50+
```js
51+
axios
52+
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
53+
.then(response => (this.info = response.data.bpi))
54+
```
55+
56+
<p data-height="200" data-theme-id="32763" data-slug-hash="6100b10f1b4ac2961208643560ba7d11" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Second Step Axios and Vue" class="codepen">See the Pen <a href="https://codepen.io/team/Vue/pen/6100b10f1b4ac2961208643560ba7d11/">Second Step Axios and Vue</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>) on <a href="https://codepen.io">CodePen</a>.</p>
57+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
58+
59+
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](../api/#Vue-filter) to make sure that the decimal is in the appropriate place as well.
60+
61+
```html
62+
<div id="app">
63+
<h1>Bitcoin Price Index</h1>
64+
<div v-for="currency in info" class="currency">
65+
{{ currency.description }}:
66+
<span class="lighten">
67+
<span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
68+
</span>
69+
</div>
70+
</div>
71+
```
72+
73+
```js
74+
filters: {
75+
currencydecimal (value) {
76+
return value.toFixed(2)
77+
}
78+
},
79+
```
80+
81+
<p data-height="300" data-theme-id="32763" data-slug-hash="9d59319c09eaccfaf35d9e9f11990f0f" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Third Step Axios and Vue" class="codepen">See the Pen <a href="https://codepen.io/team/Vue/pen/9d59319c09eaccfaf35d9e9f11990f0f/">Third Step Axios and Vue</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>) on <a href="https://codepen.io">CodePen</a>.</p>
82+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
83+
84+
### Dealing with Errors
85+
86+
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:
87+
88+
* The API is down.
89+
* The request was made incorrectly.
90+
* The API isn't giving us the information in the format that we anticipated.
91+
92+
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. In an axios call, we'll do so by using `catch`.
93+
94+
```js
95+
axios
96+
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
97+
.then(response => (this.info = response.data.bpi))
98+
.catch(error => console.log(error))
99+
```
100+
101+
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.
102+
103+
```js
104+
new Vue({
105+
el: '#app',
106+
data () {
107+
return {
108+
info: null,
109+
loading: true,
110+
errored: false
111+
}
112+
},
113+
filters: {
114+
currencydecimal (value) {
115+
return value.toFixed(2)
116+
}
117+
},
118+
mounted () {
119+
axios
120+
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
121+
.then(response => {
122+
this.info = response.data.bpi
123+
})
124+
.catch(error => {
125+
console.log(error)
126+
this.errored = true
127+
}).
128+
.finally(() => this.loading = false)
129+
}
130+
})
131+
```
132+
133+
```html
134+
<div id="app">
135+
<h1>Bitcoin Price Index</h1>
136+
137+
<section v-if="errored">
138+
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
139+
</section>
140+
141+
<section v-else>
142+
<div v-if="loading">Loading...</div>
143+
144+
<div v-else v-for="currency in info" class="currency">
145+
{{ currency.description }}:
146+
<span class="lighten">
147+
<span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
148+
</span>
149+
</div>
150+
151+
</section>
152+
</div>
153+
```
154+
155+
You can hit the rerun button on this pen to see the loading status briefly while we gather data from the API:
156+
157+
<p data-height="300" data-theme-id="32763" data-slug-hash="6c01922c9af3883890fd7393e8147ec4" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Fourth Step Axios and Vue" class="codepen">See the Pen <a href="https://codepen.io/team/Vue/pen/6c01922c9af3883890fd7393e8147ec4/">Fourth Step Axios and Vue</a> by Vue (<a href="https://codepen.io/Vue">@Vue</a>) on <a href="https://codepen.io">CodePen</a>.</p>
158+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
159+
160+
This can be even futher 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.
161+
162+
## Alternative Patterns
163+
164+
### Fetch API
165+
166+
The [Fetch API](https://developers.google.com/web/updates/2015/03/introduction-to-fetch) 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. This may very well change in the future though.
167+
168+
If you're interested in using the Fetch API, there are some [very good articles](https://scotch.io/@bedakb/lets-build-type-ahead-component-with-vuejs-2-and-fetch-api) explaining how to do so.
169+
170+
## Wrapping Up
171+
172+
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.

0 commit comments

Comments
 (0)