Introduction
API integration helps your app talk to other apps or services to get or send data easily.
API integration helps your app talk to other apps or services to get or send data easily.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { // use the data here }) .catch(error => { // handle errors here })
fetch to call APIs and get data asynchronously.fetch('https://api.example.com/users') .then(res => res.json()) .then(users => console.log(users))
async function getData() { try { const res = await fetch('https://api.example.com/items') const items = await res.json() console.log(items) } catch (e) { console.error('Error:', e) } }
This Vue component fetches a random joke from an API and shows it. It handles loading and error states so the user knows what is happening.
<template>
<main>
<h1>Random Joke</h1>
<p v-if="loading">Loading joke...</p>
<p v-else-if="error">Error loading joke.</p>
<p v-else>{{ joke }}</p>
<button @click="fetchJoke">Get New Joke</button>
</main>
</template>
<script setup>
import { ref } from 'vue'
const joke = ref('')
const loading = ref(false)
const error = ref(false)
async function fetchJoke() {
loading.value = true
error.value = false
try {
const res = await fetch('https://official-joke-api.appspot.com/random_joke')
if (!res.ok) throw new Error('Network error')
const data = await res.json()
joke.value = `${data.setup} - ${data.punchline}`
} catch {
error.value = true
} finally {
loading.value = false
}
}
fetchJoke()
</script>APIs let your app get fresh data without needing to build everything yourself.
Always show users when data is loading or if there was an error.
Test your API calls in browser DevTools Network tab to see what data you get.
API integration connects your app to outside data and services.
It helps keep your app updated and useful.
Handling loading and errors improves user experience.
onMounted?data.value, which is correct for Vue refs.message after mounting?const message = ref('');
onMounted(async () => {
try {
const res = await fetch('/api/greet');
const data = await res.json();
message.value = data.text;
} catch {
message.value = 'Error loading';
}
});{ "text": "Hello Vue!" } successfully.data.text is "Hello Vue!".message.value is set to "Hello Vue!".const data = ref(null);
onMounted(() => {
const res = fetch('/api/items');
data.value = res.json();
});res.json() without awaiting means data.value gets a Promise, not actual data.Pass the test and this pattern moves unknown