Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Making API Requests in Vue 3 with Axios

2 min read .
Making API Requests in Vue 3 with Axios

HTTP APIs are a core part of modern web applications. In Vue 3, Axios is a popular HTTP client that provides a convenient API for making requests, configuring defaults, and handling responses and errors.

This tutorial demonstrates common CRUD-style requests against the public DummyJSON example API.

1. Install and Configure Axios

Install Axios:

npm install axios

You can configure a reusable Axios instance instead of modifying global defaults:

// lib/api.js
import axios from 'axios';

export const api = axios.create({
  baseURL: 'https://dummyjson.com',
  timeout: 10000,
});

This makes the base URL and other request settings explicit and easy to reuse.

2. Fetch a Product List

<template>
  <div>
    <h1>Product List</h1>
    <ul>
      <li v-for="product in products" :key="product.id">{{ product.title }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { api } from './lib/api';

const products = ref([]);

onMounted(async () => {
  try {
    const response = await api.get('/products');
    products.value = response.data.products;
  } catch (error) {
    console.error('Error fetching products:', error);
  }
});
</script>

3. Fetch One Product

<script setup>
import { ref, onMounted } from 'vue';
import { api } from './lib/api';

const product = ref(null);
const productId = 1;

onMounted(async () => {
  try {
    const response = await api.get(`/products/${productId}`);
    product.value = response.data;
  } catch (error) {
    console.error('Error fetching product:', error);
  }
});
</script>

4. Search for Products

Pass query parameters through Axios’s params option so values are encoded correctly:

const searchQuery = 'phone';
const response = await api.get('/products/search', {
  params: { q: searchQuery },
});

products.value = response.data.products;

5. Add a Product

Send JSON with POST:

async function addProduct() {
  try {
    const response = await api.post('/products/add', {
      title: 'BMW Pencil',
      description: 'A stylish pencil from BMW.',
      price: 10,
    });

    console.log('Product added:', response.data);
  } catch (error) {
    console.error('Error adding product:', error);
  }
}

6. Update a Product

Use PUT or PATCH according to the API contract:

async function updateProduct() {
  try {
    const response = await api.put('/products/1', {
      title: 'Updated Product',
    });

    console.log('Product updated:', response.data);
  } catch (error) {
    console.error('Error updating product:', error);
  }
}

7. Delete a Product

async function deleteProduct() {
  try {
    const response = await api.delete('/products/1');
    console.log('Product deleted:', response.data);
  } catch (error) {
    console.error('Error deleting product:', error);
  }
}

DummyJSON simulates write operations for demonstration purposes; these examples do not modify a persistent production database.

8. Practical Guidelines

  • Track loading and error state: give users feedback while requests are in progress or fail.
  • Use a reusable Axios instance: centralize baseURL, timeouts, headers, and interceptors.
  • Cancel stale requests: for live search or route changes, avoid letting older requests overwrite newer state.
  • Keep credentials out of frontend code: browser applications cannot safely store secrets.
  • Validate API data: do not assume every response always has the expected shape.

Conclusion

Axios works well with Vue 3 for both simple requests and larger applications that need shared HTTP configuration. Combine it with Vue’s reactive state and lifecycle hooks, and keep request, loading, cancellation, and error behavior explicit as your application grows.

Related Posts

chevron-up