Published: February 01 2023

Vue 3 - HTTP GET Request Examples

Tutorial built with Vue 3.2.45

Below is a quick set of examples to show how to send HTTP GET requests from Vue 3 to a backend API using fetch() which comes built into all modern browsers.

Other Vue 3 HTTP examples: POST, PUT, PATCH, DELETE.

Tutorial contents


Simple HTTP GET request

This sends an HTTP GET request to the Test JSON API which is a fake online REST API that includes a product details route (/products/{id}), the returned product includes an id and name.

After the JSON data is fetched from the API it is assigned to the product ref variable and rendered in the component template.

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

const product = ref(null);

// Simple GET request using fetch
fetch('https://testapi.jasonwatmore.com/products/1')
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">Simple GET Request</h5>
        <div class="card-body">Product name: {{product?.name}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-get-request-examples?file=src%2FGetRequest.vue


HTTP GET request with async/await

This sends the same GET request from Vue 3 using fetch, but this version uses a couple of top-level await expressions in the <script setup> block to wait for the promises to return (instead of using the promise then() method as above). The top-level await results in the setup function being compiled as async setup().

NOTE: async components must be wrapped with the Vue 3 <Suspense> component in order to render. Suspense is still an experimental feature at the time I'm writing this so the way it works may change in future. For more info see https://vuejs.org/guide/built-ins/suspense.html.

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

const product = ref(null);

// GET request using fetch with async/await
const response = await fetch('https://testapi.jasonwatmore.com/products/2');
const data = await response.json();
product.value = data;
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">GET Request with Async/Await</h5>
        <div class="card-body">Product name: {{product?.name}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-get-request-examples?file=src%2FGetRequestAsyncAwait.vue


GET request with HTTP headers set

This sends the same GET request again from Vue 3 using fetch with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

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

const product = ref(null);

// GET request using fetch with set headers
const headers = {
    'Authorization': 'Bearer my-token',
    'My-Custom-Header': 'foobar'
};
fetch('https://testapi.jasonwatmore.com/products/3', { headers })
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">GET Request with Set Headers</h5>
        <div class="card-body">Product name: {{product?.name}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-get-request-examples?file=src%2FGetRequestSetHeaders.vue


HTTP GET request with error handling

This sends a GET request from Vue 3 to an invalid url on the API then assigns the error to the errorMessage ref variable and logs the error to the console.

Error handling with the Fetch API

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block. For more info see Fetch - Error Handling for Failed HTTP Responses and Network Errors.

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

const product = ref(null);
const errorMessage = ref(null);

// GET request using fetch with error handling
fetch("https://testapi.jasonwatmore.com/invalid-url")
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson && await response.json();

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        product.value = data;
    })
    .catch(error => {
        errorMessage.value = error;
        console.error("There was an error!", error);
    });
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">GET Request with Error Handling</h5>
        <div class="card-body">Error message: {{errorMessage}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-get-request-examples?file=src%2FGetRequestErrorHandling.vue

 


Need Some Vue 3 Help?

Search fiverr for freelance Vue 3 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by