How to Create API Service in Vue: Simple Guide
To create an
API service in Vue, define a separate JavaScript module that uses axios to handle HTTP requests. Import this service into your Vue components to keep your code organized and reusable.Syntax
An API service in Vue is usually a JavaScript file exporting functions that use axios to make HTTP calls. Each function corresponds to an API endpoint.
import axios from 'axios': imports axios library.const apiClient = axios.create({ baseURL }): creates an axios instance with a base URL.export function getItems() { return apiClient.get('/items') }: defines a function to fetch data.
javascript
import axios from 'axios' const apiClient = axios.create({ baseURL: 'https://api.example.com', headers: { 'Content-Type': 'application/json' } }) export function getItems() { return apiClient.get('/items') }
Example
This example shows a simple API service file and how to use it inside a Vue component with the setup function and async/await. It fetches a list of items and displays them.
vue
// src/services/apiService.js import axios from 'axios' const apiClient = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', headers: { 'Content-Type': 'application/json' } }) export async function getPosts() { return apiClient.get('/posts') } // src/components/PostList.vue <template> <div> <h2>Posts</h2> <ul> <li v-for="post in posts" :key="post.id">{{ post.title }}</li> </ul> </div> </template> <script setup> import { ref, onMounted } from 'vue' import { getPosts } from '../services/apiService' const posts = ref([]) onMounted(async () => { try { const response = await getPosts() posts.value = response.data } catch (error) { console.error('Failed to fetch posts:', error) } }) </script>
Output
A list of post titles fetched from the API displayed as bullet points on the page.
Common Pitfalls
Common mistakes when creating API services in Vue include:
- Not creating a separate service file, which leads to repeated code in components.
- Forgetting to handle errors with
try/catchor.catch(). - Not using
async/awaitproperly, causing unresolved promises. - Hardcoding URLs inside components instead of using a base URL in the service.
javascript
/* Wrong: API call directly in component without error handling */ // inside component fetch('https://api.example.com/items') .then(res => res.json()) .then(data => { /* use data */ }) /* Right: Use service with axios and error handling */ import { getItems } from './apiService' async function fetchData() { try { const response = await getItems() // use response.data } catch (error) { console.error('API error:', error) } } fetchData();
Quick Reference
Tips for creating API services in Vue:
- Use
axios.create()to set a base URL and headers once. - Export functions for each API endpoint.
- Import and call these functions in components using
async/await. - Always handle errors to avoid app crashes.
- Keep API logic separate from UI code for clarity and reuse.
Key Takeaways
Create a separate JavaScript file to define your API service using axios.
Use axios.create() to set a base URL and common headers for all requests.
Call API service functions inside Vue components with async/await and handle errors.
Keep API logic separate from component UI code for better organization and reuse.
Avoid hardcoding URLs or repeating HTTP logic inside components.