How to use the Fetch API with Vue.js?

Fri Mar 31 2023

4 min read

When building web applications with Vue.js, integrating the Fetch API can be a powerful way to fetch and integrate data from an API.

The Fetch API is a modern JavaScript API for making network requests, and it provides a more powerful and flexible alternative to traditional XMLHttpRequest requests.

By combining the Fetch API with Vue.js, you can build dynamic and responsive web applications that communicate with APIs and display real-time data to users.

Setting up Vue.js project

To set up a basic Vue app, you'll need Node.js and npm installed on your machine. If you don’t, you can download it from here.

Here are the steps to set up a new Vue.js project:

Step #1

You can create a Vue Project by running the following command in the terminal:

sh
npx @vue/cli create my-app

You can replace my-app with the name of your application.

Step #2

To start the development server and run your app in the browser, navigate to the app directory and execute the following command:

sh
cd my-app
npm run serve

This should open a new browser window showing your app.

Using Fetch API with Vue.js

When building an application, we often fetch data from external APIs. One way to call these REST APIs is by using Fetch.

Fetching data

Let’s look at an example of how to use fetch API. We can use Jokes API from Rapid API Hub for this purpose.

js
async fetchJokes() {
try {
const response = await fetch('https://jokes-api-by-api-ninja.p.rapidapi.com/v1/jokes');
const jokes = await response.json();
} catch (error) {
console.error(error);
}
}

This function uses the fetch() method to make a GET request to the Jokes API. It then parses the response using response.json().

Note that we're using the async/await syntax here to handle the asynchronous nature of the Fetch API.

Using the fetched data in Vue.js components

Let’s now use Fetch API in Vue.js to make an API call.

Step #1: Find an API

Let’s go over to Rapid API Hub. It has thousands of APIs that we can use. We will use the Facts API by API-Ninja. So please go ahead and subscribe to it.

Loading component...

Step #2: Create and edit the component

Let’s write our code in HelloWorld.vue file. Go to src/components directory and you will find it there. Remove all the HTML under the H1 tag and create a button using the button tag. Once done, set an onclick event on the button.

vue
<template>
<div class="hello">
<h1>Random Fact</h1>
<button @click="fetchData">Click Me!</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
button {
padding: 12px 32px;
font-size: 16px;
border-radius: 8px;
}
</style>

Step #3: Create a method

To create a method for making API calls using Fetch, we will create a methods object within the export default object. This object will contain all the necessary methods your application will use.

The API playground of Facts API offers different code snippets in multiple languages. We will use the (JavaScript) fetch code snippet in our example.

Let’s paste this snippet in our code. Here is how the code will look like:

vue
<template>
<div class="hello">
<h1>Random Fact:</h1>
<button @click="fetchData">Click Me!</button>
<p v-if="fact">{{ fact }}</p>
</div>
</template>
<script>
export default {
props: {
msg: String,
},
data() {
return {
fact: "",
};
},
methods: {
fetchData() {
fetch('https://facts-by-api-ninjas.p.rapidapi.com/v1/facts', {
method: "GET",
headers: {
"X-RapidAPI-Key": 'your-api-key',
"X-RapidAPI-Host": 'facts-by-api-ninjas.p.rapidapi.com',
},
})
.then((response) => {
response.json().then((data) => {
this.fact = data[0].fact;
});
})
.catch((err) => {
console.error(err);
});
},
},
};
</script>
<style>
button {
padding: 12px 32px;
font-size: 16px;
border-radius: 8px;
}
</style>

In this code, the fact data property is initialized as an empty string in the data() function. In the fetchData() method, the fetch() function is used to make a GET request to the API with the appropriate headers. When the response is received, the response data is extracted as JSON and the fact property is set to the text of the fact.

You will something like this on your screen:

Wrap up

By the end of this guide, you have a basic understanding of how to use Fetch API in Vue.js. This is really knowledge useful in building more complex Vue.js applications that require data from APIs.