---
title: "Typed client"
summary: "Generate TypeScript types from the OpenAPI document with openapi-typescript and call the API with openapi-fetch, checked by the compiler."
updated: "2026-11-19"
url: "https://taskloader.com/docs/guides/typed-client"
---

> Documentation index: https://taskloader.com/llms.txt

# Typed client

Generate TypeScript types from the OpenAPI document with openapi-typescript and call the API with openapi-fetch, checked by the compiler.

Taskloader publishes its whole API as an [OpenAPI 3.1.1 document](https://taskloader.com/docs/api.md#openapi). From it you can generate a client in most languages. This guide sets up a TypeScript one: types from `openapi-typescript`, and `openapi-fetch` to make the calls. The compiler then checks every path, parameter, request body and response against the real API.

## 1. Install

In a new folder (Node.js 20 or later):

```bash
npm install openapi-fetch@0.17.0
npm install --save-dev openapi-typescript@7.13.0 typescript@5.9.3 @types/node@26.6.5 tsx@4.23.15
npm pkg set type=module
```

`type=module` lets the files below use `import` and top-level `await`. Then save this as `tsconfig.json`:

```json
{
  "compilerOptions": {
    "strict": true,
    "target": "es2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "skipLibCheck": true
  },
  "include": ["src"]
}
```

## 2. Generate the types

```bash
npx openapi-typescript https://taskloader.com/api/v1/openapi.json -o src/taskloader-api.d.ts
```

The file describes every path, its parameters, request body and answers. Generate it again to pick up new endpoints and fields; v1 only grows, so regenerating never breaks code that compiled before.

## 3. Create the client

```ts
// src/taskloader.ts
import createClient from 'openapi-fetch';
import type { paths } from './taskloader-api.js';

export const taskloader = createClient<paths>({
  baseUrl: 'https://taskloader.com/api/v1',
  headers: { Authorization: `Bearer ${process.env.TASKLOADER_API_KEY}` },
  // Taskloader reads lists of values comma-separated: ?status=backlog,progress
  querySerializer: { array: { style: 'form', explode: false } },
});
```

The `querySerializer` line matters: `openapi-fetch` repeats array parameters by default (`?status=backlog&status=progress`), while Taskloader expects them comma-separated.

## 4. Call the API

```ts
// src/main.ts
import { randomUUID } from 'node:crypto';
import { taskloader } from './taskloader.js';

const projectId = 'prj_f88e6947efdde102d9c7a2d045b244b5';

// Search: query parameters are typed, including the allowed status values.
const open = await taskloader.GET('/projects/{projectId}/tasks', {
  params: {
    path: { projectId },
    query: { status: ['backlog', 'progress'], sort: '-updatedAt', limit: 20 },
  },
});
if (open.error) throw new Error(`${open.error.code}: ${open.error.detail}`);
for (const task of open.data.data) console.log(task.key, task.title);

// Create: the body is checked against the schema; Idempotency-Key makes a retry safe.
const created = await taskloader.POST('/projects/{projectId}/tasks', {
  params: { path: { projectId }, header: { 'Idempotency-Key': randomUUID() } },
  body: { title: 'Write launch announcement', priority: 'high', dueDate: '2026-11-20' },
});
if (created.error) throw new Error(`${created.error.code}: ${created.error.detail}`);
const task = created.data;

// Update: send the version you read in If-Match.
const updated = await taskloader.PATCH('/tasks/{taskId}', {
  params: { path: { taskId: task.id }, header: { 'If-Match': `"${task.version}"` } },
  body: { status: 'progress' },
});
if (updated.response.status === 412) {
  // Someone changed it first: the problem carries the task as it is now in `current`.
  console.log('Changed by someone else; now at version', updated.error?.currentVersion);
} else if (updated.error) {
  throw new Error(`${updated.error.code}: ${updated.error.detail}`);
}
```

Check and run it:

```bash
npx tsc --noEmit && npx tsx src/main.ts
```

`tsc` reports any path, parameter or field the API does not have before anything runs.

Every call returns `{ data, error, response }`:

- `data` is the typed answer when the request succeeded;
- `error` is the [problem](https://taskloader.com/docs/api.md#errors) when it did not, with `code`, `detail`, `requestId` and the code's extra members;
- `response` is the raw `Response`, for headers such as `ETag`, `RateLimit` and `Retry-After`.

Branch on `error.code`, never on `detail`.

## Retries and limits

`openapi-fetch` does not retry. Wrap calls that may need it in a small function that applies the [retry policy](https://taskloader.com/docs/guides/conflicts-and-retries.md#a-retry-policy) and gives every attempt the same `Idempotency-Key`:

```ts
// src/with-retries.ts
import { randomUUID } from 'node:crypto';

const MAX_WAIT = 60; // Seconds. A longer Retry-After (a daily cap) is returned, not slept through.
const sleep = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
const backoff = (attempt: number) => Math.min(30, 2 ** attempt) * (0.5 + Math.random() / 2);

/**
 * Sends a request until it succeeds or fails for good. Every attempt gets the same
 * Idempotency-Key, so a write that went through the first time is never done twice.
 */
export async function withRetries<R extends { error?: unknown; response: Response }>(
  send: (idempotencyKey: string) => Promise<R>,
  attempts = 5,
): Promise<R> {
  const idempotencyKey = randomUUID();
  for (let attempt = 1; ; attempt++) {
    let result: R;
    try {
      result = await send(idempotencyKey);
    } catch (error) {
      // No answer at all (a timeout, a dropped connection): safe to send again.
      if (attempt >= attempts) throw error;
      await sleep(backoff(attempt));
      continue;
    }
    const { status, headers } = result.response;
    const code = (result.error as { code?: string } | undefined)?.code;
    const retryAfter = Number(headers.get('Retry-After')) || 0;
    const retryable =
      status === 429 || status === 409
        ? retryAfter > 0 && retryAfter <= MAX_WAIT // Limits, and a request still running.
        : status >= 500 && code !== 'assistant_unavailable';
    if (!retryable || attempt >= attempts) return result;
    await sleep(retryAfter || backoff(attempt));
  }
}
```

```ts
// src/create-task.ts
import { taskloader } from './taskloader.js';
import { withRetries } from './with-retries.js';

const created = await withRetries((idempotencyKey) =>
  taskloader.POST('/projects/{projectId}/tasks', {
    params: {
      path: { projectId: 'prj_f88e6947efdde102d9c7a2d045b244b5' },
      header: { 'Idempotency-Key': idempotencyKey },
    },
    body: { title: 'Write launch announcement' },
  }),
);
if (created.error) throw new Error(`${created.error.code}: ${created.error.detail}`);
console.log(created.data.key);
```

It retries `429` and `409` answers that carry `Retry-After`, after waiting that long, and server errors and lost connections with backoff. Everything else comes back at once as `error`, including a `429` without `Retry-After` (such as `too_many_invitations`, which needs you to act first) and `503 assistant_unavailable`. Reads need no key: `withRetries(() => taskloader.GET(…))`.

## Paging

Lists return `nextCursor`. Pass it back as `cursor`, with the same filters (the [changes feed](https://taskloader.com/docs/api/changes-feed.md) takes it as `after`):

```ts
// src/all-tasks.ts
import { taskloader } from './taskloader.js';

async function* allTasks(projectId: string) {
  let cursor: string | undefined;
  do {
    const page = await taskloader.GET('/projects/{projectId}/tasks', {
      params: { path: { projectId }, query: { limit: 100, cursor } },
    });
    if (page.error) throw new Error(`${page.error.code}: ${page.error.detail}`);
    yield* page.data.data;
    cursor = page.data.nextCursor ?? undefined;
  } while (cursor);
}

for await (const task of allTasks('prj_f88e6947efdde102d9c7a2d045b244b5')) console.log(task.key);
```

## Other languages

The document is standard OpenAPI 3.1.1, so other generators work too. Whatever you use, check two things: arrays in query strings must be comma-separated (`style: form`, `explode: false`), and unknown response fields and enum values must be ignored rather than rejected, because v1 [grows over time](https://taskloader.com/docs/api.md#versioning).
