Vue HTTP & API Interaction
Estimated reading: 4 minutes 276 views

Vue HTTP Requests – Interacting with APIs in Vue 3 (2025 Guide)


Introduction – Why Are HTTP Requests Important in Vue?

In modern Vue applications, HTTP requests are essential for fetching data from APIs, sending form submissions, and integrating with backend services. Vue doesn’t ship with an HTTP client, but it’s commonly paired with libraries like Axios or the Fetch API to perform these operations.

In this guide, you’ll learn:

  • How to make GET, POST, PUT, DELETE requests in Vue
  • The difference between Fetch API and Axios
  • How to manage API responses, errors, and loading states
  • Real-world examples with full code and output

Popular HTTP Clients in Vue

ClientDescriptionVue Compatibility
AxiosPromise-based, supports interceptors Recommended
Fetch APIBuilt-in browser API Supported

Installing Axios (Optional)

npm install axios

Then import it in your component:

import axios from 'axios';

Example 1 – Basic GET Request (Axios)

Fetching Posts from an API

<template>
  <div>
    <h2>Posts</h2>
    <ul v-if="posts.length">
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
    <p v-else>Loading...</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return { posts: [] };
  },
  created() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        this.posts = response.data.slice(0, 5); // limit to 5
      })
      .catch(error => {
        console.error('Error fetching posts:', error);
      });
  }
}
</script>

This component loads data when created and updates the view.


Example 2 – POST Request (Axios)

Submitting a Form

<template>
  <form @submit.prevent="submitForm">
    <input v-model="title" placeholder="Title" />
    <button type="submit">Submit</button>
  </form>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return { title: '' };
  },
  methods: {
    submitForm() {
      axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: this.title,
        body: 'Sample Body',
        userId: 1
      })
      .then(res => console.log('Post created:', res.data))
      .catch(err => console.error('Error:', err));
    }
  }
}
</script>

@submit.prevent prevents page reload and sends the POST request.


PUT / DELETE Requests

Update (PUT)

axios.put('/api/item/1', {
  title: 'Updated Title'
});

Delete

axios.delete('/api/item/1');

Handling Errors & Loading State

Pattern:

data() {
  return {
    posts: [],
    loading: false,
    error: null
  }
},
created() {
  this.loading = true;
  axios.get('/api/posts')
    .then(res => this.posts = res.data)
    .catch(err => this.error = err.message)
    .finally(() => this.loading = false);
}

This improves UX by showing loaders or errors based on request states.


Using Fetch API Instead of Axios

Example:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => this.posts = data)
  .catch(error => console.error(error));

Fetch is native and lightweight but lacks interceptors and automatic JSON parsing for errors.


Real-World Use Case – Auth Token in Header

Using Axios Interceptors:

axios.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  return config;
});

Summary – Recap & Next Steps

Vue apps often rely on HTTP requests to interact with backend services. With Axios or Fetch, Vue makes it easy to integrate APIs for data-driven UIs.

Key Takeaways:

  • Use Axios for robust HTTP features like interceptors
  • Use Fetch for native support and simplicity
  • Handle loading and error states properly
  • Use lifecycle hooks like created() to trigger API calls

Real-World Relevance:
Essential for SPAs that rely on APIs—e.g., dashboards, forms, content feeds, admin panels.


FAQ Section

How do I send a GET request in Vue?

Use Axios or Fetch in lifecycle hooks:

axios.get('/api/posts')

Should I use Axios or Fetch in Vue?

Axios is preferred for complex apps. Fetch is fine for basic use cases.


How do I handle request errors in Vue?

Use .catch() or try...catch with async/await.


Where should I call the API in a Vue component?

Inside created() or mounted() lifecycle hooks.


How do I show loading while the request is in progress?

Track loading in data() and use conditional rendering.


Share Now :
Share

Vue HTTP Requests

Or Copy Link

CONTENTS
Scroll to Top