If you’re a web developer, chances are overwhelming you’ve had to fetch data from an API at some point. And if you’re using the Vue framework, you might be wondering how to fetch data and save it inside a Vue component.

Luckily, this is very easy to do with the native Fetch API. In this article, we’ll learn how to do it both with the Options and Composition API, the two official ways of writing Vue components.

If you’re trying to make sense on how to connect a frontend built with Vue and an external API, read on!

Why use the Fetch API?

If you’re not familiar with the fetch API, it’s a way to make asynchronous HTTP requests in JavaScript. Essentially, it allows you to fetch data from an external source and then do something with that data inside your code.

The fetch API is available in most modern browsers, but if you’re using an older browser you might need to use a polyfill.

To use the Fetch API, we first need to create a Request object. This object will take an url and options object as parameters. The url parameter is where we specify the endpoint of the API that we want to call. The options object is where we can specify things like the HTTP method (e.g. GET or POST), headers, body, etc.

Once we have our Request object, we can call the native fetch method, which will return a Promise. This Promise will resolve with a Response object. The Response object has a json() method, which we can call to get the JSON data that we’re after.

This is how a simple GET call will look like in practice:

fetch("https://api.example.com/users")
.then(res => res.json())
.then(data => console.log(data))

This would simply show the API data in our local console.

However, how do you store and use that data in a Vue component? Let’s learn how to do it by creating a very simple example: an app that calls the JSON placeholder API and renders a list of the items we retrieve from a particular endpoint.

Let’s jump right in and see how to call an API using the Options API.

Calling an API using the Options syntax

As you probably know, the Options syntax is the traditional way to create Vue components. Here, you need to declare a couple of options (hence the name) depending on which kind of data you have inside of your component.

Let’s see how we can fetch data from an API and use it in a component written with the options syntax.

First, we need to create a new Vue instance and define a variable. We’ll initialize it as an empty array, as we will add here all the information we retrieve from the JSON placeholder API:

<script>
  export default {
    data() {
      return {
        listItems: []
      }
    }
  }
</script>

Then, in our Methods section, we will create a method that will retrieve the data from the actual API. In this case, we’ll use the Async/Await syntax for added clarity:

<script>
  export default {
    data() {
      return {
        listItems: []
      }
    },
    methods: {
      async getData() {
        const res = await fetch("https://jsonplaceholder.typicode.com/posts");
        const finalRes = await res.json();
        this.listItems = finalRes;
      }
    }
  }
</script>

As you’ve probably noticed, during the final step we’ve saved our API response directly in our previously generated variable. This means that the data is now available globally inside our component, and we can render it using the v-for syntax in our template:

<template>
  <div v-for="item in listItems">
    {{item.title}}
  </div>
</template>

Is your HTML not showing anything? Before our app actually shows anything, we have to call the getData method. We can do this when we load our component using the mounted hook:

<script>
  export default {
    data() {
      return {
        listItems: []
      }
    },
    methods: {
      async getData() {
        const res = await fetch("https://jsonplaceholder.typicode.com/posts");
        const finalRes = await res.json();
        this.listItems = finalRes;
      }
    },
    mounted() {
      this.getData()
    }
  }
</script>

And that’s it! We now have a list displaying data we’ve fetched from an external API.

Calling an API using the Composition syntax

Calling an external data source using the Composition API is, in some ways, even easier than with Options. The only thing we need to change is our <script> section; our <template> can stay just the same.

Here’s how the same code would look like if using the Composition API. Notice we’re using the <script setup> method:

<script setup>
  import { ref } from 'vue';

  const listItems = ref([]);

  async function getData() {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts");
    const finalRes = await res.json();
    listItems.value = finalRes;
  }

 getData()
</script>

Pretty simple, huh? As you can see, getting data in a Vue project using the Fetch API is actually something very easy to achieve. We hope this article has helped you!

👋 Hey, I'm Alejandro Rodríguez
Hey there! I'm a front end developer from Spain and a web dev teacher at Ironhack. I've been writing for more than 7 years as a side project, and I love to mix both disciplines whenever I can. Besides working, I'm also passionate about travelling (often with my laptop as a digital nomad) and water sports. What could be better than writing about code in a Caribbean beach, or from a coworking space in an european city?

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.