API Calls
Learn how to make and manage API calls in ShipAhead efficiently, connecting your app to external services with ease.
Tools Used
- Nuxt: Provides server-side APIs and client-side composables for seamless API integration.
Setup & Configuration
- Configure Database: Set up your database first by following the Database Setup Guide.
- Verify useApi: The
useApicomposable is pre-configured in ShipAhead atapp/composables/useApi.js. No additional setup is needed unless adding custom API endpoints.
Usage
Use the useApi composable in your Nuxt components to call server APIs. Below are front-end and back-end examples:
Front-End Example: Import
useApiand callgetAdminUserStatswith error handling and loading state:pages/admin/stats.vue<script setup> const { getAdminUserStats } = useApi(); const { t } = useI18n(); const stats = ref({ totalUsers: 0, admins: 0, members: 0, signUps7d: 0 }); const loading = ref(false); const fetchStats = async () => { try { loading.value = true; const response = await getAdminUserStats(); if (response.success && response.data) { Object.assign(stats.value, response.data); } else { useToast(t('error.somethingWrong'), enums.toastAlertType.error); } } catch { useToast(t('error.somethingWrong'), enums.toastAlertType.error); } finally { loading.value = false; } }; onMounted(fetchStats); </script>This fetches admin stats, shows a loading state, and displays a toast notification (pop-up message) on error.
Back-End Example: Define a server API to handle the
getAdminUserStatsrequest with authentication:server/api/admin/stats.jsimport { apiSuccess } from '~~/server/utils/apiResponse'; import { requireAuth } from '~~/server/auth'; import { getUserStats } from '~~/server/services/admin/stats'; export default defineEventHandler(async (event) => { const user = await requireAuth(event); if (user.role !== 'admin') { throw createError({ statusCode: 403, statusMessage: 'Forbidden' }); } const stats = await getUserStats(); return apiSuccess(stats); });This checks if the user is an admin, fetches stats, and returns a formatted response.
How It Works
- Client-Side: The
useApicomposable (app/composables/useApi.js) uses Nuxt’s$fetchto call server APIs, handling methods like GET, POST, and DELETE. - Server-Side: APIs in
server/api/(e.g.,admin/stats.js) use services (e.g.,server/services/admin/stats.js) for logic and return formatted responses withapiSuccess. - Error Handling:
useApireturns errors for invalid requests (e.g., 403 for non-admins). Front-end code can handle errors withtry/catchand show toast notifications. - Authentication: Protected APIs (e.g., admin stats) require a valid user session and role, checked via
requireAuth. - Database Dependency: APIs like
getAdminUserStatsrequire a configured database to fetch data.
For more details on Nuxt API routes, visit Nuxt Server Documentation.