# API Clients

A widget built from the canonical template has a single HTTP client, configured with Axios in `src/shared/http/client.ts`. Only the `api/` layer of a feature uses it. The `api/` layer also decides whether to return mock data or call the network.

Feature structure and the import graph: `modyo://docs/widgets/patterns-features`.

---

## The client: `src/shared/http/client.ts`

```ts
import axios from 'axios';
import { API_BASE_URL } from '@/config/widgetConfig';

export const api = axios.create({
  baseURL: API_BASE_URL || import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

api.interceptors.response.use(
  (response) => {
    if (import.meta.env.DEV) {
      console.log(`[API] ${response.config.method?.toUpperCase()} ${response.config.url}`, response.data);
    }
    return response;
  },
  (error) => {
    if (import.meta.env.DEV) {
      console.error('[API Error]', error.response?.data || error.message);
    }
    return Promise.reject(error);
  },
);
```

- The base URL comes from the Liquid variable `vars.api-base-url`, read once in `src/config/widgetConfig.ts`:

  ```ts
  export const API_BASE_URL = requireVariable('vars.api-base-url', liquidParser.parse('{{vars.api-base-url}}'));
  export const USE_MOCKS = liquidParser.parse('{{vars.use-mocks}}') === 'true';
  ```

  `vars.api-base-url` is a required variable: when it arrives unresolved, the widget shows the missing-variables screen instead of calling an empty URL. See `modyo://docs/widgets/reference-architecture` (Required variables).
- Add authentication headers or other interceptors to this client; do not create a second Axios instance per feature.

### Who may import it

| From | Allowed |
|------|---------|
| `src/features/<name>/api/` | Yes |
| `hooks/`, `service/`, `ui/`, `model/` of a feature | No — data reaches them through `api/` |
| `src/app/`, `src/pages/` | No — they use a feature's hooks |
| A feature's `index.ts` | No — it never re-exports the client |

ESLint rejects imports of `src/shared/http/` from `src/app/`, `src/pages/`, a feature's `index.ts` and every feature layer other than `api/`.

---

## The `api/` layer

One function per endpoint. Each function receives an optional `AbortSignal` (TanStack Query passes its own, so the request is cancelled when the query is no longer used) and returns domain types: the DTO never leaves `api/`. From `src/features/entities/api/entityApi.ts`:

```ts
import { USE_MOCKS } from '@/config/widgetConfig';
import { api } from '@/shared/http/client';

import { toEntity } from '../model/entity.mapper';
import type { CreateEntityData, Entity, EntityFilters } from '../model/entity';

import type { ApiEntity } from './entity.dto';
import { mockEntities } from './entity.mock';

const MOCK_DELAY = 500; // ms

/**
 * GET /entities
 */
export async function getEntities(
  filters: EntityFilters = {},
  signal?: AbortSignal,
): Promise<Entity[]> {
  if (USE_MOCKS) {
    await wait(MOCK_DELAY, signal);
    const search = filters.search?.trim().toLowerCase();
    return mockEntities
      .filter((entity) => !search || entity.name.toLowerCase().includes(search))
      .map(toEntity);
  }

  const response = await api.get<ApiEntity[]>('/entities', {
    params: filters.search ? { search: filters.search } : undefined,
    signal,
  });
  return response.data.map(toEntity);
}

/**
 * POST /entities
 */
export async function createEntity(
  data: CreateEntityData,
  signal?: AbortSignal,
): Promise<Entity> {
  if (USE_MOCKS) {
    await wait(MOCK_DELAY, signal);
    const created: ApiEntity = {
      id: `mock-${mockEntities.length + 1}`,
      name: data.name,
      created_at: new Date().toISOString(),
    };
    mockEntities.push(created);
    return toEntity(created);
  }

  const response = await api.post<ApiEntity>('/entities', data, { signal });
  return toEntity(response.data);
}

function wait(ms: number, signal?: AbortSignal): Promise<void> {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });
}
```

Both branches return through the same mapper (`toEntity`), so mock mode exercises the same translation as the real response.

---

## Mocks

- Mock data lives next to the API functions, in `api/<entity>.mock.ts`, with the **DTO** shape (not the domain shape).
- Only `api/` imports `*.mock.ts`; ESLint rejects the import anywhere else.
- `api/` chooses between mock data and the network with `USE_MOCKS`, which is `true` when the Liquid variable `vars.use-mocks` is `"true"`.
- In development, `src/config/liquid.json` sets `"use-mocks": "true"`, so `npm run dev` works without a backend. With mocks active, no required variable is enforced.

```ts
// src/features/entities/api/entity.mock.ts
import type { ApiEntity } from './entity.dto';

export const mockEntities: ApiEntity[] = [
  {
    id: '1',
    name: 'First Entity',
    created_at: '2024-01-15T10:30:00Z',
    updated_at: '2024-02-20T14:45:00Z',
  },
  // ...
];
```

On a Modyo site, set `vars.use-mocks` and `vars.api-base-url` as site variables. Liquid handling and local values: `modyo://docs/widgets/patterns-liquid-environment`.

---

## See also

- `modyo://docs/widgets/patterns-features` — feature layers and import graph
- `modyo://docs/widgets/patterns-tanstack-query` — hooks that call `api/`
- `modyo://docs/widgets/reference-architecture` — required variables and the configuration gate
