Internal API client for making HTTP requests to the Mosaia API

This class provides a centralized HTTP client for all API communication with the Mosaia platform. It handles authentication, request formatting, response processing, and error handling in a consistent manner.

Features:

  • Automatic authentication header management
  • Token refresh handling
  • Request/response standardization
  • Error handling and formatting
  • Query parameter building
  • Content type management

The APIClient uses the ConfigurationManager for settings and automatically handles token refresh when needed. It supports all standard HTTP methods and provides type-safe responses through generics.

Basic usage:

const client = new APIClient();

// GET request
const users = await client.GET<UserInterface[]>('/user');

// POST request
const newUser = await client.POST<UserInterface>('/user', {
name: 'John Doe',
email: 'john@example.com'
});

// PUT request
const updatedUser = await client.PUT<UserInterface>('/user/123', {
name: 'John Smith'
});

// DELETE request
await client.DELETE('/user/123');

With query parameters:

// GET with query parameters
const filteredUsers = await client.GET<UserInterface[]>('/user', {
limit: 10,
offset: 0,
search: 'john',
active: true
});

// DELETE with parameters
await client.DELETE('/user/123', {
force: true,
reason: 'account_deletion'
});

Error handling:

try {
const user = await client.GET<UserInterface>('/user/123');
console.log('User:', user.data);
} catch (error) {
console.error('API Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
}

Constructors

  • Creates a new API client instance

    Initializes the API client with configuration from the ConfigurationManager. The client automatically handles authentication and token refresh.

    Parameters

    • Optionalconfig: MosaiaConfig

      Optional configuration object (if not provided, uses ConfigurationManager)

    • skipTokenRefresh: boolean = false

      Skip token refresh check to prevent circular dependencies

    Returns APIClient

    Basic initialization:

    const client = new APIClient();
    

    With custom config:

    const client = new APIClient({
    apiKey: 'your-api-key',
    apiURL: 'https://api.mosaia.ai',
    version: '1'
    });

    Skip token refresh (for auth flows):

    const client = new APIClient(config, true);
    

Methods

  • Makes a GET request to the API

    Retrieves data from the specified API endpoint. Supports query parameters for filtering, pagination, and other request options.

    Type Parameters

    • T

      The expected response data type

    Parameters

    • path: string

      API endpoint path (e.g., '/user', '/org', '/agent')

    • Optionalparams: object

      Optional query parameters for filtering and pagination

    Returns Promise<any>

    Promise that resolves to the API response data

    Basic GET request:

    const users = await client.GET<UserInterface[]>('/user');
    const user = await client.GET<UserInterface>('/user/123');

    With query parameters:

    const filteredUsers = await client.GET<UserInterface[]>('/user', {
    limit: 10,
    offset: 0,
    search: 'john',
    active: true
    });

    const userAgents = await client.GET<AgentInterface[]>('/agent', {
    user: 'user-123',
    tags: ['support', 'ai']
    });

    Error handling:

    try {
    const user = await client.GET<UserInterface>('/user/123');
    console.log('User data:', user.data);
    } catch (error) {
    console.error('Failed to fetch user:', error.message);
    }
  • Makes an authenticated GET request that captures a redirect URL instead of following it. Returns the Location header from a 3xx response.

    Parameters

    • path: string

      API endpoint path

    Returns Promise<null | string>

    The redirect URL, or null if the response is not a redirect

  • Returns the full authenticated URL and headers for a given API path. Useful for endpoints that stream content (e.g. folder ZIP downloads) where the client needs to fetch directly with auth.

    Parameters

    • path: string

      API endpoint path

    Returns Promise<{ url: string; headers: Record<string, string> }>

    Object with url and headers

  • Makes a POST request to the API

    Creates new resources or performs actions that require data submission. The request body is automatically serialized as JSON.

    Type Parameters

    • T

      The expected response data type

    Parameters

    • path: string

      API endpoint path (e.g., '/user', '/org', '/agent')

    • Optionaldata: object

      Request body data to be sent

    • Optionalparams: object

      Optional query parameters to append to the URL

    Returns Promise<any>

    Promise that resolves to the API response data

    Create a new user:

    const newUser = await client.POST<UserInterface>('/user', {
    email: 'user@example.com',
    first_name: 'John',
    last_name: 'Doe'
    });

    Create an AI agent:

    const agent = await client.POST<AgentInterface>('/agent', {
    name: 'support-assistant',
    description: 'Customer support triage assistant.',
    model: ['65f0c3d2a4b5c6d7e8f90123'],
    temperature: 0.7,
    system_message: 'You are a helpful support agent.'
    });

    Perform an action with query parameters:

    const result = await client.POST<ChatCompletionResponse>('/agent/123/chat', {
    messages: [
    { role: 'user', content: 'Hello, how can you help me?' }
    ],
    temperature: 0.7
    }, { stream: true, timeout: 30000 });
  • Makes a PUT request to the API

    Updates existing resources with new data. The request body is automatically serialized as JSON and sent to the specified endpoint.

    Type Parameters

    • T

      The expected response data type

    Parameters

    • path: string

      API endpoint path (e.g., '/user/123', '/org/456', '/agent/789')

    • Optionaldata: object

      Request body data for updates

    • Optionalparams: object

    Returns Promise<any>

    Promise that resolves to the API response data

    Update user profile:

    const updatedUser = await client.PUT<UserInterface>('/user/123', {
    first_name: 'Jane',
    last_name: 'Smith',
    email: 'jane.smith@example.com'
    });

    Update agent configuration:

    const updatedAgent = await client.PUT<AgentInterface>('/agent/789', {
    temperature: 0.5,
    system_message: 'You are a technical support specialist.',
    tags: ['support', 'technical']
    });

    Update organization settings:

    const updatedOrg = await client.PUT<OrganizationInterface>('/org/456', {
    name: 'Updated Corp Name',
    description: 'Updated description',
    active: true
    });
  • Makes a DELETE request to the API

    Removes resources from the system. Supports optional query parameters for additional deletion options like force deletion or soft deletion. Also supports request body for endpoints that require it.

    Type Parameters

    • T

      The expected response data type

    Parameters

    • path: string

      API endpoint path (e.g., '/user/123', '/org/456', '/agent/789')

    • OptionalbodyOrParams: object

      Request body data (for endpoints that require it) OR query parameters (for backward compatibility)

    • Optionalparams: object

      Optional query parameters (only used when bodyOrParams is a body object)

    Returns Promise<any>

    Promise that resolves to the API response data

    Basic deletion:

    await client.DELETE<void>('/user/123');
    await client.DELETE<void>('/agent/789');

    Force deletion with query parameters (backward compatible):

    await client.DELETE<void>('/org/456', { force: true });
    await client.DELETE<void>('/user/123', {
    force: true,
    reason: 'account_deletion'
    });

    DELETE with request body:

    await client.DELETE<RevokeAccessResponse>('/drive/123/access', {
    accessor: { org_user: 'orguser123' }
    });

    DELETE with body and query parameters:

    await client.DELETE<void>('/agent/789', { 
    soft: true
    }, {
    archive: true
    });