0
0
Vueframework~5 mins

Why API integration matters in Vue

Choose your learning style9 modes available
Introduction

API integration helps your app talk to other apps or services to get or send data easily.

You want to show weather info from a weather service in your app.
You need to let users log in using Google or Facebook accounts.
Your app should fetch news articles from an online news source.
You want to save user data to a cloud database.
Your app needs to get real-time stock prices from a finance API.
Syntax
Vue
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // use the data here
  })
  .catch(error => {
    // handle errors here
  })
Use fetch to call APIs and get data asynchronously.
Always handle errors to keep your app stable.
Examples
Fetches a list of users and prints it in the console.
Vue
fetch('https://api.example.com/users')
  .then(res => res.json())
  .then(users => console.log(users))
Uses async/await to fetch items and handle errors cleanly.
Vue
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)
  }
}
Sample Program

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.

Vue
<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>
OutputSuccess
Important Notes

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.

Summary

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.