Logo

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

  1. Configure Database: Set up your database first by following the Database Setup Guide.
  2. Verify useApi: The useApi composable is pre-configured in ShipAhead at app/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:

  1. Front-End Example: Import useApi and call getAdminUserStats with 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.

  2. Back-End Example: Define a server API to handle the getAdminUserStats request with authentication:

    server/api/admin/stats.js
    import { 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 useApi composable (app/composables/useApi.js) uses Nuxt’s $fetch to 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 with apiSuccess.
  • Error Handling: useApi returns errors for invalid requests (e.g., 403 for non-admins). Front-end code can handle errors with try/catch and show toast notifications.
  • Authentication: Protected APIs (e.g., admin stats) require a valid user session and role, checked via requireAuth.
  • Database Dependency: APIs like getAdminUserStats require a configured database to fetch data.

For more details on Nuxt API routes, visit Nuxt Server Documentation.