API Requests in Vue 3 with Axios

3 min read .

APIs are the backbone of modern web applications, enabling data fetching, creation, updating, and deletion. In Vue 3, Axios is a popular library that provides a simple and effective way to interact with APIs. In this guide, we’ll cover how to use Axios in Vue 3 to perform common CRUD operations (Create, Read, Update, Delete) using a dummy API endpoint. By the end of this tutorial, you’ll have a solid understanding of how to manage data in your Vue 3 applications using Axios.

1. Setting Up Axios in Vue 3:

Provide a brief overview of Axios and how to set it up in a Vue 3 project. Include instructions on installing Axios via npm and configuring it for use.

Example:

npm install axios
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';

const app = createApp(App);

// Optionally set up global axios defaults
axios.defaults.baseURL = 'https://dummyjson.com';

app.config.globalProperties.$axios = axios;
app.mount('#app');

2. Fetching Data from an API:

Show how to fetch a list of products using Axios. Explain how to handle the response and update the component state.

Example:

<!-- FetchProducts.vue -->
<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 axios from 'axios';

const products = ref([]);

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

3. Fetching a Specific Product:

Explain how to fetch a specific product using its ID and display the product details.

Example:

<!-- FetchProduct.vue -->
<template>
  <div v-if="product">
    <h1>{{ product.title }}</h1>
    <p>{{ product.description }}</p>
  </div>
</template>

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

const product = ref(null);
const productId = 1; // Example product ID

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

4. Searching for Products:

Show how to search for products using a query parameter.

Example:

<!-- SearchProducts.vue -->
<template>
  <div>
    <h1>Search Results</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 axios from 'axios';

const products = ref([]);
const searchQuery = 'phone'; // Example search query

onMounted(async () => {
  try {
    const response = await axios.get(`/products/search?q=${searchQuery}`);
    products.value = response.data.products;
  } catch (error) {
    console.error('Error searching for products:', error);
  }
});
</script>

5. Adding a New Product:

Guide users through adding a new product using a POST request with Axios.

Example:

<!-- AddProduct.vue -->
<template>
  <div>
    <button @click="addProduct">Add Product</button>
  </div>
</template>

<script setup>
import axios from 'axios';

async function addProduct() {
  try {
    const response = await axios.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);
  }
}
</script>

6. Updating an Existing Product:

Explain how to update an existing product’s details using PUT or PATCH requests.

Example:

<!-- UpdateProduct.vue -->
<template>
  <div>
    <button @click="updateProduct">Update Product</button>
  </div>
</template>

<script setup>
import axios from 'axios';

async function updateProduct() {
  try {
    const response = await axios.put('/products/1', {
      title: 'iPhone Galaxy +1',
    });
    console.log('Product updated:', response.data);
  } catch (error) {
    console.error('Error updating product:', error);
  }
}
</script>

7. Deleting a Product:

Demonstrate how to delete a product using a DELETE request.

Example:

<!-- DeleteProduct.vue -->
<template>
  <div>
    <button @click="deleteProduct">Delete Product</button>
  </div>
</template>

<script setup>
import axios from 'axios';

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

8. Best Practices for Using Axios in Vue 3:

Share best practices, such as:

  • Error Handling: Use try-catch blocks to handle errors gracefully and provide feedback to the user.
  • Reusable Axios Instances: Create reusable Axios instances to manage base URLs, headers, and interceptors.
  • State Management: Use Vue 3’s reactive properties effectively for managing and displaying data.

9. Conclusion:

Summarize the key points covered in the blog, emphasizing the ease and flexibility of using Axios for API interactions in Vue 3. Encourage readers to apply these techniques in their projects.

Tags:
Vue

See Also

chevron-up