# General Translation Platform: API client
URL: https://generaltranslation.com/en-US/docs/platform/core/reference/api-client.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: Create a typed client for the General Translation API and call generated endpoint helpers. API reference for createApiClient.

Import the TypeScript client from `generaltranslation/api` when you need endpoint-level control without constructing HTTP requests yourself. The module combines an authenticated, versioned, retrying transport with generated endpoint helpers and opt-in utilities for batching and translation-job polling.

`generaltranslation/api` is available in `generaltranslation` 9.2.0 and later. The examples below target `generaltranslation` 9.5.2 and the equivalent standalone `@generaltranslation/api` 0.5.0 package.

The generated helpers reflect the installed package version, which can differ from the current hosted [public OpenAPI contract](/docs/platform/openapi/overview). Use the public reference when checking which endpoints and file formats are live.

## Overview [#overview]

| Export | Description |
| --- | --- |
| [`createApiClient`](#create-client) | Creates an authenticated client with version, retry, and timeout handling. |
| [`ApiClientConfig`](#client-config) | Configures the client transport and shared request headers. |
| [`API_VERSION`](#api-version) | Current API contract version sent by default. |
| [Endpoint helpers](#endpoint-helpers) | Typed functions for the public operations listed below. |
| [`paginate`](#pagination) | Iterate every item of a list operation. |
| [`awaitJobs`](#job-polling) and [`pollJobs`](#job-polling) | Poll translation jobs until they finish or time out. |
| [`processBatches`](#batch-processing) and [`DEFAULT_BATCH_SIZE`](#batch-processing) | Process an input array in configurable batches. |
| [`ApiError`](#api-error) | Error thrown for a failed HTTP response. |
| [Generated types](#types-errors) | Describe endpoint data, responses, errors, and client contracts. |
| [Public OpenAPI specification](#openapi-spec) | Current hosted API contract. |

## `createApiClient` [#create-client]

```ts
function createApiClient(config: ApiClientConfig): Client;
```

The client adds the configured API version, API key, and project ID to every request. Pass it to a generated endpoint helper:

```ts title="project-info.ts"
import { createApiClient, getProjectInfo } from 'generaltranslation/api';

const projectId = process.env.GT_PROJECT_ID!;
const client = createApiClient({
  apiKey: process.env.GT_API_KEY,
  baseUrl: 'https://api.gtx.dev',
  projectId,
});

const result = await getProjectInfo({
  client,
  path: { projectId },
});

if (result.error) {
  throw new Error('Could not load Project information');
}

console.log(result.data);
```

The examples below reuse this configured `client`.

## `ApiClientConfig` [#client-config]

| Option | Description | Type | Optional | Default |
| --- | --- | --- | --- | --- |
| [`apiKey`](#apikey) | API key sent in the `Authorization` header. | `string` | Yes | — |
| [`apiVersion`](#apiversion) | Contract version sent as `gt-api-version`. | `ApiVersion` | Yes | `API_VERSION` |
| [`baseUrl`](#baseurl) | API origin. | `string` | No | — |
| [`fetch`](#fetch) | Custom Fetch API implementation. | `typeof fetch` | Yes | `globalThis.fetch` |
| [`projectId`](#projectid) | project ID sent as `gt-project-id`. | `string` | Yes | — |
| [`retryPolicy`](#retrypolicy) | Retry delay strategy. | `'exponential' \| 'linear' \| 'none'` | Yes | `'exponential'` |
| [`timeoutMs`](#timeoutms) | Per-attempt timeout, or `false` to disable the built-in timeout. | `number \| false` | Yes | `60000` |

### `apiKey`

**Type** `string` · **Optional**

API key sent as `Authorization: Bearer <api-key>`. The client does not read environment variables automatically.

### `apiVersion`

**Type** `ApiVersion` · **Optional** · **Default** `API_VERSION`

API contract version sent in the `gt-api-version` header.

### `baseUrl`

**Type** `string` · **Required**

API origin. Use `https://api.gtx.dev` for the hosted General Translation API.

### `fetch`

**Type** `typeof fetch` · **Optional** · **Default** `globalThis.fetch`

Custom Fetch API implementation. Use this for instrumentation, testing, or a runtime without a global fetch implementation.

### `projectId`

**Type** `string` · **Optional**

Project ID sent in the `gt-project-id` header. Organization keys need this header for project-scoped endpoints that do not carry the project ID in the path.

### `retryPolicy`

**Type** `'exponential' | 'linear' | 'none'` · **Optional** · **Default** `'exponential'`

GET, HEAD, OPTIONS, PUT, and DELETE retry network errors and `5xx` responses up to three times after the first attempt. POST does not retry these failures, even for logically read-only operations. All methods can retry `429` responses. Set this to `'none'` to disable transport retries.

For `429`, the delay comes from `Retry-After` (seconds or an HTTP date), then `RateLimit-Reset` (seconds), then a 60-second fallback. Other exponential delays are 500, 1000, and 2000 ms; linear delays are 500, 1000, and 1500 ms. Retry sleeps are not abort-aware, so cancellation is not guaranteed to interrupt a wait immediately.

Class runtime translation disables these transport retries, including `429`. The generated runtime-translation helper uses the supplied client's retry policy instead.

### `timeoutMs`

**Type** `number | false` · **Optional** · **Default** `60000`

Timeout in milliseconds for each request attempt. Omission selects 60000; `0` is literal zero. Set it to `false` to disable the built-in timer, not caller or custom-fetch cancellation. This is not a whole-operation deadline covering retries and response processing. Fetch implementations must honor the supplied signal.

These settings are not [`GT`](/docs/platform/core/reference/gt-class/constructor) constructor options. (See [Translation configuration](/docs/platform/core/reference/types/translation-config)).

## `API_VERSION` [#api-version]

**Type** `ApiVersion`

The current default contract version is `2026-03-06.v1`. Pass a different supported version through `apiVersion` when maintaining an integration against an older response contract.

## Endpoint helpers [#endpoint-helpers]

Generated helpers accept one object with the shared `client` plus the endpoint's `body`, `headers`, `path`, and `query` fields as applicable. They return `{ data, error, request, response }` by default.

```ts title="project-info.ts"
import { getProjectInfo } from 'generaltranslation/api';

const result = await getProjectInfo({
  client,
  path: { projectId: 'your-project-id' },
  throwOnError: true,
});

console.log(result.data.name);
```

Common generated options include:

| Option | Description | Type | Optional | Default |
| --- | --- | --- | --- | --- |
| `client` | Client returned by `createApiClient`. | `Client` | No | — |
| `body` | Typed JSON request body. | Endpoint-specific | Varies | — |
| `path` | Typed path parameters. | Endpoint-specific | Varies | — |
| `query` | Typed query parameters. | Endpoint-specific | Varies | — |
| `headers` | Per-call headers that override shared client headers. | Endpoint-specific | Yes | — |
| `throwOnError` | Throw for an unsuccessful response instead of returning `error`. | `boolean` | Yes | `false` |
| `responseStyle` | Return all response fields or only parsed data. | `'fields' \| 'data'` | Yes | `'fields'` |
| `signal` | Cancel the request with a Fetch API signal. | `AbortSignal` | Yes | — |
| `meta` | Values exposed to custom client integrations. | `Record<string, unknown>` | Yes | — |

The installed 0.5.0 SDK provides generated helpers for these 24 public operations:

| Function | Operation |
| --- | --- |
| [`listProjects`](/docs/platform/openapi/reference/project/list-projects) | List one page of projects readable by the credentials. |
| [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs) | List the Organization associated with an Organization or project API key. |
| [`createProject`](/docs/platform/openapi/reference/project/create-project) | Create a project in a selected Organization. |
| [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key) | Create a project API key with permissions delegated by the caller. |
| [`uploadSourceFiles`](/docs/platform/openapi/reference/files/upload-source) | Upload source files. |
| [`uploadTranslations`](/docs/platform/openapi/reference/files/upload-translations) | Upload translated files linked to existing source files. |
| `uploadAssets` | Upload project assets. |
| `submitUserEditDiffs` | Submit local translation edits. |
| `generateProjectContext` | Generate project context. |
| `enqueueFileTranslations` | Queue uploaded files for translation. |
| `publishFiles` | Publish or unpublish files. |
| [`downloadFile`](/docs/platform/openapi/reference/files/download) | Download one file. |
| `downloadFiles` | Download multiple files. |
| `getBranchInfo` | Read branch information. |
| `createBranch` | Create a branch. |
| [`createTag`](/docs/platform/openapi/reference/project/upsert-tag) | Create or update a tag. |
| `getProjectInfo` | Read project information. |
| `updateProjectInfo` | Update project information. |
| `getTranslationJobInfo` | Read translation-job status. |
| [`translate`](/docs/platform/openapi/reference/translation/translate-runtime) | Translate content at runtime. |
| `getFileInfo` | Read file metadata. |
| `getTranslationStatus` | Read a file's translation status. |
| `processFileMoves` | Move or rename files. |
| `getOrphanedFiles` | Find orphaned files. |

<Callout type="info">
  **Changed in v0.5.0:** list responses return `items` instead of `projects` or `orgs`, matching the current API. Failed `throwOnError` calls throw [`ApiError`](#api-error) instead of the decoded response body.

  **Changed in v0.3.0:** `encodeBase64`, `decodeBase64`, `encodeFileContent`, and `decodeFileContent` are no longer exported. Encode file content before passing it to a generated upload helper.

  **Changed in v0.2.1:** [`createProject`](/docs/platform/openapi/reference/project/create-project) now requires `path.orgId` and calls `POST /v2/orgs/{orgId}/projects`. This release also added [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key) and removed `shouldGenerateProjectContext` and `getProjectContextGenerationStatus`.
</Callout>

Use `generateProjectContext` with `getTranslationJobInfo` for context jobs. The [`downloadFile`](/docs/platform/openapi/reference/files/download) helper remains deprecated; use `downloadFiles` for batch and single-file downloads.

Use the [public OpenAPI reference](/docs/platform/openapi/overview) for live endpoint permissions, rate limits, schemas, and status codes.

### Discovery and provisioning

Use [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs) to find the Organization associated with your API key. Both Organization and project keys work; no project-creation permission is required for this lookup.

Project discovery returns one page of projects readable by your API key. Use [`paginate`](#pagination) to iterate every project:

```ts title="list-projects.ts"
import { listProjects, paginate } from 'generaltranslation/api';

for await (const project of paginate(listProjects, {
  client,
  query: { limit: 100 },
})) {
  console.log(project.id, project.name);
}
```

Project creation requires an Organization key with `org:projects:create` and takes `path: { orgId }` and `body: { name, defaultLocale, cdnEnabled? }`.

For [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key), select explicit least-privilege `permissions`. Omitting them requests all delegable project permissions held by the caller; you must hold every selected permission. Store the returned secret securely and never log it.

These generated discovery and creation helpers are not methods on [`GT`](/docs/platform/core/reference/gt-class/constructor).

## `paginate` [#pagination]

```ts
function paginate<
  Options extends {
    client?: Client;
    query?: { cursor?: string; limit?: number };
  },
  Item,
>(
  list: (options: Options & { throwOnError: true }) => Promise<{
    data: { items: Item[]; nextCursor: string | null };
  }>,
  options: Options
): AsyncGenerator<Item>;
```

`paginate` yields every item of a list operation such as [`listProjects`](/docs/platform/openapi/reference/project/list-projects) or [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs), passing `options` to each page request. It requests the next page only when iteration reaches it, so breaking out of the loop stops further requests. Pass a saved `nextCursor` as `query.cursor` to resume. A failed page throws like a `throwOnError` call.

Pages are read independently, so items that change during iteration can be missed or repeated.

## Job polling [#job-polling]

[`awaitJobs`](#job-polling) uses a configured client to call `getTranslationJobInfo` until every requested job is complete, failed, unknown, or missing, or until the overall timeout expires.

```ts
function awaitJobs(
  client: Client,
  jobIds: readonly string[],
  options?: AwaitJobsOptions
): Promise<AwaitJobsResult>;
```

| Option | Description | Type | Optional | Default |
| --- | --- | --- | --- | --- |
| `pollingIntervalSeconds` | Delay between status requests. | `number` | Yes | `5` |
| `timeoutSeconds` | Overall polling deadline. | `number` | Yes | `600` |
| `onPoll` | Receives each successful raw status response before terminal bookkeeping. | `(statuses: GetTranslationJobInfoResponse) => void` | Yes | — |

```ts
import {
  awaitJobs,
  enqueueFileTranslations,
} from 'generaltranslation/api';

const result = await enqueueFileTranslations({
  client,
  body: {
    files: [{ fileId: 'homepage', versionId: 'version-1' }],
    sourceLocale: 'en',
    targetLocales: ['es'],
  },
  throwOnError: true,
});

if (!('jobData' in result.data)) {
  throw new Error('Expected the current enqueue response');
}

const jobs = await awaitJobs(client, Object.keys(result.data.jobData));

if (!jobs.complete) {
  console.warn('Translation jobs did not finish before the timeout');
}
```

`AwaitJobsResult` contains `complete`, which is `false` only when polling times out, and `jobs`, which contains the latest result for every requested ID. A missing job receives the `unknown` status. Passing an empty array resolves immediately with `{ complete: true, jobs: [] }`.

An API or status-loader error before the overall deadline rejects the polling promise. If the request fails after the deadline has elapsed, polling returns the latest results with `complete: false`.

`pollJobs` exposes the same polling loop with an injected status loader:

```ts
function pollJobs(
  jobIds: readonly string[],
  getJobStatuses: GetJobStatuses,
  options?: AwaitJobsOptions
): Promise<AwaitJobsResult>;

type GetJobStatuses = (
  jobIds: string[],
  signal: AbortSignal
) => Promise<GetTranslationJobInfoResponse>;
```

Use it when you need custom request or error normalization. Polls are sequential and request only pending IDs. The loader receives an abort signal capped by the remaining overall deadline and a 60-second per-poll limit. Late results are discarded; timeout returns the last accepted statuses, which can still be queued, processing, or initially unknown. A loader that ignores the signal can delay resolution.

`complete: true` means no pending jobs, not that every job succeeded. Inspect each status before using results. Both API polling helpers accept `onPoll`; the class [`awaitJobs`](/docs/platform/core/reference/gt-class-methods/translation/await-jobs) options do not. No polling option exposes a caller signal, and stopping local polling does not cancel remote jobs.

## Batch processing [#batch-processing]

`processBatches` splits an input array into chunks, invokes your processor for each chunk, and flattens the returned arrays in batch order.

```ts
function processBatches<TInput, TOutput>(
  items: readonly TInput[],
  processBatch: (batch: TInput[]) => Promise<TOutput[]>,
  options?: BatchOptions
): Promise<TOutput[]>;
```

| Option | Description | Type | Optional | Default |
| --- | --- | --- | --- | --- |
| `batchSize` | Number of input values in each batch. Supply a value greater than zero. | `number` | Yes | `DEFAULT_BATCH_SIZE` |
| `parallel` | Process all batches concurrently instead of sequentially. | `boolean` | Yes | `true` |

`DEFAULT_BATCH_SIZE` is `100`.

If a batch processor rejects, `processBatches` rejects. With parallel processing, the other batches that already started continue independently.

```ts
import { Buffer } from 'node:buffer';
import {
  processBatches,
  uploadSourceFiles,
} from 'generaltranslation/api';

// Generated endpoint helpers expect file content encoded for transport.
const content = Buffer.from('{"greeting":"Hello"}', 'utf8').toString('base64');
const files = [{
  source: {
    content,
    fileName: 'en.json',
    fileFormat: 'JSON' as const,
    locale: 'en',
  },
}];

const results = await processBatches(files, async (batch) => {
  const result = await uploadSourceFiles({
    client,
    body: { data: batch },
    throwOnError: true,
  });
  return result.data.uploadedFiles;
});
```

## Types and errors [#types-errors]

The module exports `Client`, `Options`, `ApiClientConfig`, `ApiVersion`, `RetryPolicy`, `AwaitJobsOptions`, `AwaitJobsResult`, `GetJobStatuses`, `JobResult`, `BatchOptions`, `RuntimeFileFormat`, and the generated OpenAPI types for the public operations listed above.

For each public operation listed above, the package exports:

- `<Operation>Data` for typed body, headers, path, and query input.
- `<Operation>Errors` for the status-code map of documented errors.
- `<Operation>Error` for the union of documented errors.
- `<Operation>Responses` for the status-code map of documented successful responses.
- `<Operation>Response` for the union of documented successful responses.

With the default `throwOnError: false`, a generated operation returns either `data` or `error` plus the Fetch API `request`. An HTTP response includes `response`; a failure before a response is received leaves it undefined. With `throwOnError: true`, an HTTP error response from a `createApiClient` client throws an [`ApiError`](#api-error). Network and cancellation failures throw their original error; the built-in timeout throws `Error('Request timed out after <timeoutMs>ms')`.

### `ApiError` [#api-error]

With a `createApiClient` client, failed HTTP responses from `throwOnError` calls, [`paginate`](#pagination), [`awaitJobs`](#job-polling), and [`GT`](/docs/platform/core/reference/gt-class/constructor) class methods throw `ApiError`, with `name: 'ApiError'`, the HTTP status as numeric `code`, and `message`. Import it from `generaltranslation/api` or `generaltranslation/errors`. Calls without `throwOnError` still return the decoded response body in `error`. Network, configuration, cancellation, and timeout failures can reject the entire class call; they are not necessarily per-item translation failures.

```ts
import { ApiError } from 'generaltranslation/errors';

export function describeFailure(error: unknown): string {
  return error instanceof ApiError
    ? `${error.code}: ${error.message}`
    : String(error);
}
```

## OpenAPI specification [#openapi-spec]

Use [`/openapi.json`](/openapi.json) for the current hosted public API contract. The [OpenAPI reference](/docs/platform/openapi/overview) documents endpoint permissions, request schemas, and responses.

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
