In this article, we will look at how to make a HTTP request in Vue using fetch API.
We will begin by creating a new application using Vue CLI.
❯ vue create http-request-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd http-request-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
Now, that we have the project structure ready, let’s start making HTTP requests from Vue. For the demonstration purpose, we will be making use of the Meme generator API called Imgflip API
Fetch API
Fetch is a web API used for making HTTP requests from the client side. In this section, we will see how to make use of fetch()
method in Vue application.
We want to get the first 10 memes from the ImgFlip API and display it in the Vue application. To get them we have to hit a GET request to the below URL.
fetch("https://api.imgflip.com/get_memes")
To trigger this request, we will create a button that will call a method on click.
<button @click="getMemes">Get Memes</button>
The getMemes
method can then call the external API to fetch the data.
getMemes() {
fetch("https://api.imgflip.com/get_memes")
.then((response) => response.json())
.then((json) => {
console.log(json);
});
}
We will also have a data property memes
that will be an empty array initially.
data() {
return {
memes: [],
};
}
Let’s make changes to the App.vue
file to see the above code in action.
// App.vue
<template>
<button @click="getMemes">Get Memes</button>
<div v-if="memes.length">
<div v-for="meme in memes" :key="meme.id">
<h2>{{ meme.name }}</h2>
<img :src="meme.url" width="100" />
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
memes: [],
};
},
methods: {
getMemes() {
fetch("https://api.imgflip.com/get_memes")
.then((response) => response.json())
.then((json) => {
this.memes = json.data.memes.slice(0, 10);
});
},
},
};
</script>
The content is only displayed if memes
is not empty.
<div v-if="memes.length">
The API by default provides 100 memes with the following structure.
{
"success": true,
"data": {
"memes": [
{
"id": "61579",
"name": "One Does Not Simply",
"url": "https://i.imgflip.com/1bij.jpg",
"width": 568,
"height": 335,
"box_count": 2
},
{
"id": "101470",
"name": "Ancient Aliens",
"url": "https://i.imgflip.com/26am.jpg",
"width": 500,
"height": 437,
"box_count": 2
}
// more data..
]
}
}
Using v-for
we are looping through the content and displaying the name and the image of the meme.
<div v-for="meme in memes" :key="meme.id">
<h2>{{ meme.name }}</h2>
<img :src="meme.url" width="100" />
</div>
In this case, we are only extracting the first 10 objects to display them on the page.
this.memes = json.data.memes.slice(0, 10);
Output:
This a basic example to show how to make an HTTP GET request using fetch API. You can also make POST, PATCH, DELETE, and PUT requests, in the same manner, using fetch API in Vue.