useApi
A composable that provides a comprehensive API client for making HTTP requests with various utilities for caching, form handling, file uploads, and downloads.
Usage
ts
import { useApi } from '#imports'
// Create API client instance
const api = useApi()
// Basic requests
const getData = async () => {
// Standard response contains data wrapped in { data: ... } object
const response = await api.get('/users')
// Use $ prefix methods to get just the data property
const users = await api.$get('/users')
}
// Post data
const createUser = async (userData) => {
return api.$post('/users', userData)
}
// Form submissions
const submitForm = async (formData) => {
return api.$postForm('/users', formData)
}
// File uploads
const uploadUserAvatar = async (file) => {
return api.uploadFile(file)
}
// Download files
const downloadReport = async () => {
return api.download('/reports/monthly', 'monthly-report.pdf')
}
// Cache control
api.$getLazyInvalidate('users') // Invalidate cached requests containing "users"
Return Value
useApi()
returns an instance with the following methods:
Basic Request Methods
Method | Parameters | Description |
---|---|---|
request<T> | (options) | Generic request method |
get<T> | (url, options?) | GET request |
post<T> | (url, body?, options?) | POST request |
put<T> | (url, body?, options?) | PUT request |
patch<T> | (url, body?, options?) | PATCH request |
delete<T> | (url, body?, options?) | DELETE request |
Direct Data Access Methods
All methods prefixed with $
return the data directly instead of the complete response:
Method | Parameters | Description |
---|---|---|
$get<T> | (url, options?) | GET request returning just the data |
$post<T> | (url, body?, options?) | POST request returning just the data |
$put<T> | (url, body?, options?) | PUT request returning just the data |
$patch<T> | (url, body?, options?) | PATCH request returning just the data |
$delete<T> | (url, body?, options?) | DELETE request returning just the data |
Form Handling Methods
Method | Parameters | Description |
---|---|---|
postForm<T> | (url, data?, options?) | POST form data |
putForm<T> | (url, data?, options?) | PUT form data (emulated via POST) |
patchForm<T> | (url, data?, options?) | PATCH form data (emulated via POST) |
$postForm<T> | (url, data?, options?) | POST form data returning just the data |
$putForm<T> | (url, data?, options?) | PUT form data returning just the data |
$patchForm<T> | (url, data?, options?) | PATCH form data returning just the data |
buildFormData | (data?, options?) | Convert object to FormData |
Caching Methods
Method | Parameters | Description |
---|---|---|
getLazy<T> | (url, options?) | GET with caching |
$getLazyInvalidate | (key) | Invalidate cached entries containing key |
File Operations
Method | Parameters | Description |
---|---|---|
getSignedURL | (file, options?) | Get a signed URL for file upload |
uploadFile | (file, options?) | Upload a file |
download | (url, filename?, options?) | Download a file |
URL Management
Method | Parameters | Description |
---|---|---|
changeBaseUrl | (baseURL) | Change the base URL for API calls |
API Hooks
The API client integrates with Nuxt's hooks system to provide two lifecycle hooks that allow you to customize request behavior and error handling:
Hook | Parameters | Description |
---|---|---|
we-api:onRequest | (request) | Called before each request is sent |
we-api:onResponseError | (error) | Called when a response error occurs |
Registering Hook Handlers
You can register handlers for these hooks in your plugins:
ts
// plugins/api-hooks.ts
export default defineNuxtPlugin((nuxtApp) => {
// Add a request interceptor
nuxtApp.hooks.hook('we-api:onRequest', (request) => {
// Add custom headers
request.options.headers.append('X-Custom-Header', 'CustomValue')
// Log outgoing requests
console.log(`[API Request] ${request.method} ${request.url}`)
})
// Add a response error handler
nuxtApp.hooks.hook('we-api:onResponseError', (error) => {
// Custom error tracking
if (error.response?.status === 500) {
trackError({
type: 'API_ERROR',
url: error.request?.url,
status: error.response.status,
data: error.response._data
})
}
})
})
Examples
Fetching Data with Automatic Caching
ts
const api = useApi()
// First call fetches and caches data
const page1 = await api.getLazy('/users', { query: { page: 1 } })
// Subsequent calls with the same URL and options use cached data
const cachedPage1 = await api.getLazy('/users', { query: { page: 1 } })
// Clear cache for specific endpoints
api.$getLazyInvalidate('users')
Working with Forms and File Uploads
ts
const api = useApi()
async function submitUserForm(userData, avatarFile) {
// Upload avatar first
const fileData = await api.uploadFile(avatarFile)
// Then create user with avatar reference
return api.$postForm('/users', {
...userData,
avatar_id: fileData.id
})
}
Downloading Files
ts
const api = useApi()
function downloadUserReport(userId) {
return api.download(`/users/${userId}/report`, `user-${userId}-report.pdf`)
}