# General Translation Platform: API 客户端
URL: https://generaltranslation.com/zh/docs/platform/core/reference/api-client.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 为 General Translation API 创建类型化客户端，并调用生成的端点辅助函数。createApiClient 的 API 参考。

当你需要端点级别的控制，又不想自己构造 HTTP 请求时，可从 `generaltranslation/api` 导入 TypeScript 客户端。该模块将带认证、带版本、自动重试的传输层与生成的端点辅助函数结合在一起，并提供可选启用的工具，用于批量处理以及翻译 job 的轮询。

`generaltranslation/api` 在 `generaltranslation` 9.2.0 及更高版本中可用。下面的示例针对 `generaltranslation` 9.5.4 以及与之对应的独立 `@generaltranslation/api` 0.5.2 package。

生成的端点辅助函数以已安装的 package 版本为准，可能与当前托管的[公开 OpenAPI 契约](/docs/platform/openapi/overview)存在差异。在确认哪些端点和文件格式已上线时，请以公开参考为准。

## 概览 [#overview]

| 导出                                                                                | 说明                     |
| --------------------------------------------------------------------------------- | ---------------------- |
| [`createApiClient`](#create-client)                                               | 创建已认证的客户端，并处理版本、重试和超时。 |
| [`ApiClientConfig`](#client-config)                                               | 配置客户端传输层与共享的请求 header。 |
| [`API_VERSION`](#api-version)                                                     | 默认发送的当前 API 契约版本。      |
| [端点辅助函数](#endpoint-helpers)                                                       | 对应下列各公共操作的类型化函数。       |
| [`paginate`](#pagination)                                                         | 遍历列表操作返回的所有条目。         |
| [`awaitJobs`](#job-polling) 与 [`pollJobs`](#job-polling)                          | 轮询翻译任务，直至其完成或超时。       |
| [`processBatches`](#batch-processing) 与 [`DEFAULT_BATCH_SIZE`](#batch-processing) | 按可配置的 batch 大小处理输入数组。  |
| [`ApiError`](#api-error)                                                          | HTTP 响应失败时抛出的错误。       |
| [生成的类型](#types-errors)                                                            | 描述端点数据、响应、错误以及客户端契约。   |
| [公共 OpenAPI 规范](#openapi-spec)                                                    | 当前托管的 API 契约。          |

## `createApiClient` [#create-client]

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

该客户端会为每个请求自动添加已配置的 API 版本、API Key 和项目 ID。将其传入生成的端点辅助函数：

```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);
```

以下示例均复用这个已配置的 `client`。

## `ApiClientConfig` [#client-config]

| 选项                            | 描述                                     | 类型                                    | 可选 | 默认值                |
| ----------------------------- | -------------------------------------- | ------------------------------------- | -- | ------------------ |
| [`apiKey`](#apikey)           | 通过 `Authorization` header 发送的 API Key。 | `string`                              | 是  | —                  |
| [`apiVersion`](#apiversion)   | 通过 `gt-api-version` 发送的契约版本。           | `ApiVersion`                          | 是  | `API_VERSION`      |
| [`baseUrl`](#baseurl)         | API 源地址。                               | `string`                              | 否  | —                  |
| [`fetch`](#fetch)             | 自定义的 Fetch API 实现。                     | `typeof fetch`                        | 是  | `globalThis.fetch` |
| [`projectId`](#projectid)     | 通过 `gt-project-id` 发送的项目 ID。           | `string`                              | 是  | —                  |
| [`retryPolicy`](#retrypolicy) | 重试延迟策略。                                | `'exponential' \| 'linear' \| 'none'` | 是  | `'exponential'`    |
| [`timeoutMs`](#timeoutms)     | 单次尝试的超时时间；设为 `false` 可禁用内置超时。          | `number \| false`                     | 是  | `60000`            |

### `apiKey`

**Type** `string` · **可选**

以 `Authorization: Bearer <api-key>` 形式发送的 API Key。客户端不会自动读取环境变量。

### `apiVersion`

**类型** `ApiVersion` · **可选** · **默认值** `API_VERSION`

通过 `gt-api-version` header 发送的 API 契约版本。

### `baseUrl`

**类型** `string` · **必填**

API 源地址。使用托管的 General Translation API 时，请填写 `https://api.gtx.dev`。

### `fetch`

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

自定义 Fetch API 实现。可用于插桩、测试，或在没有全局 fetch 实现的运行时环境中使用。

### `projectId`

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

通过 `gt-project-id` header 发送的项目 ID。Organization keys 在调用路径中不包含项目 ID 的项目层级端点时需要该 header。

### `retryPolicy`

**类型** `'exponential' | 'linear' | 'none'` · **可选** · **默认值** `'exponential'`

GET、HEAD、OPTIONS、PUT 和 DELETE 请求遇到网络错误或 `5xx` 响应时，会在首次尝试后最多重试三次。POST 请求遇到这类失败时不会重试，即使是逻辑上只读的操作也是如此。所有方法都可以对 `429` 响应进行重试。将此项设为 `'none'` 可禁用传输层重试。

对于 `429`，延迟时间优先取自 `Retry-After` (秒数或 HTTP 日期) ，其次取自 `RateLimit-Reset` (秒数) ，若均不可用则回退为 60 秒。其他情况下，指数退避的延迟依次为 500、1000 和 2000 毫秒；线性退避的延迟依次为 500、1000 和 1500 毫秒。重试等待期间不会响应中止信号，因此取消操作不一定能立即中断等待。

类的运行时翻译会禁用这些传输层重试，包括 `429` 重试。生成的运行时翻译 helper 则改为沿用所传入客户端的重试策略。

### `timeoutMs`

**类型** `number | false` · **可选** · **默认值** `60000`

每次请求尝试的超时时间 (毫秒) 。省略时默认为 60000；`0` 表示真正的零。设置为 `false` 会禁用内置计时器，但不影响调用方或自定义 fetch 的取消机制。该值并非覆盖重试和响应处理在内的整个操作的截止时间。Fetch 实现必须响应传入的 signal。

这些设置不属于 [`GT`](/docs/platform/core/reference/gt-class/constructor) 构造函数的选项。 (参见[翻译配置](/docs/platform/core/reference/types/translation-config)。)

## `API_VERSION` [#api-version]

**类型** `ApiVersion`

当前默认的契约版本为 `2026-03-06.v1`。如果集成需要沿用较旧的响应契约，请通过 `apiVersion` 传入其他受支持的版本。

## 端点辅助函数 [#endpoint-helpers]

生成的端点辅助函数接受一个对象作为参数，其中包含共享的 `client`，以及该端点适用的 `body`、`headers`、`path` 和 `query` 字段。默认情况下，它们返回 `{ data, error, request, response }`。

```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);
```

常见的生成选项包括：

| 选项              | 描述                             | 类型                        | 可选    | 默认值        |
| --------------- | ------------------------------ | ------------------------- | ----- | ---------- |
| `client`        | `createApiClient` 返回的客户端。      | `Client`                  | 否     | —          |
| `body`          | 带类型的 JSON 请求体。                 | 因端点而异                     | 视情况而定 | —          |
| `path`          | 带类型的路径参数。                      | 因端点而异                     | 视情况而定 | —          |
| `query`         | 带类型的查询参数。                      | 因端点而异                     | 视情况而定 | —          |
| `headers`       | 单次调用的 header，会覆盖客户端共享的 header。 | 因端点而异                     | 是     | —          |
| `throwOnError`  | 响应失败时抛出异常，而不是返回 `error`。       | `boolean`                 | 是     | `false`    |
| `responseStyle` | 返回全部响应字段，或仅返回解析后的数据。           | `'fields' \| 'data'`      | 是     | `'fields'` |
| `signal`        | 使用 Fetch API 的 signal 取消请求。    | `AbortSignal`             | 是     | —          |
| `meta`          | 向自定义客户端集成暴露的值。                 | `Record<string, unknown>` | 是     | —          |

已安装的 0.5.2 SDK 为以下 48 个公开操作提供了生成的端点辅助函数：

| 函数                                                                                                                    | 操作                                             |
| --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| [`listProjects`](/docs/platform/openapi/reference/project/list-projects)                                              | 列出 API Key 绑定所选定的项目 (单页) 。                     |
| [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs)                                                      | 列出与 Organization 或项目 API Key 关联的 Organization。 |
| [`createProject`](/docs/platform/openapi/reference/project/create-project)                                            | 在选定的 Organization 中创建项目。                       |
| [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key)                                      | 创建项目 API Key，其权限由调用方委派。                        |
| [`uploadSourceFiles`](/docs/platform/openapi/reference/files/upload-source)                                           | 上传源文件。                                         |
| [`uploadTranslations`](/docs/platform/openapi/reference/files/upload-translations)                                    | 上传与现有源文件关联的翻译后的文件。                             |
| `uploadAssets`                                                                                                        | 上传项目资源。                                        |
| `submitUserEditDiffs`                                                                                                 | 提交本地翻译修改。                                      |
| `generateProjectContext`                                                                                              | 生成项目上下文。                                       |
| `enqueueFileTranslations`                                                                                             | 将已上传的文件加入翻译队列。                                 |
| `publishFiles`                                                                                                        | 发布或取消发布文件。                                     |
| [`downloadFile`](/docs/platform/openapi/reference/files/download)                                                     | 下载单个文件。                                        |
| `downloadFiles`                                                                                                       | 下载多个文件。                                        |
| `getBranchInfo`                                                                                                       | 读取 branch 信息。                                  |
| `createBranch`                                                                                                        | 创建 branch。                                     |
| [`createTag`](/docs/platform/openapi/reference/project/upsert-tag)                                                    | 创建或更新标签。                                       |
| `getProjectInfo`                                                                                                      | 读取项目信息。                                        |
| `updateProjectInfo`                                                                                                   | 更新项目信息。                                        |
| `getTranslationJobInfo`                                                                                               | 读取翻译任务的状态。                                     |
| [`translate`](/docs/platform/openapi/reference/translation/translate-runtime)                                         | 在运行时翻译内容。                                      |
| `getFileInfo`                                                                                                         | 读取文件元数据。                                       |
| `getTranslationStatus`                                                                                                | 读取文件的翻译状态。                                     |
| `processFileMoves`                                                                                                    | 移动或重命名文件。                                      |
| `getOrphanedFiles`                                                                                                    | 查找孤立文件。                                        |
| [`listContextGroups`](/docs/platform/openapi/reference/context-management/list-groups)                                | 列出 Organization 中的 Context Group。              |
| [`createContextGroup`](/docs/platform/openapi/reference/context-management/create-group)                              | 创建 Context Group。                              |
| [`getContextGroup`](/docs/platform/openapi/reference/context-management/get-group)                                    | 读取 Context Group。                              |
| [`updateContextGroup`](/docs/platform/openapi/reference/context-management/update-group)                              | 更新 Context Group。                              |
| [`deleteContextGroup`](/docs/platform/openapi/reference/context-management/delete-group)                              | 删除 Context Group。                              |
| [`listProjectContextGroups`](/docs/platform/openapi/reference/context-management/list-project-groups)                 | 列出分配给项目的 Context Group。                        |
| [`getProjectContextGroup`](/docs/platform/openapi/reference/context-management/get-project-group)                     | 读取单个已分配的 Context Group。                        |
| [`assignContextGroup`](/docs/platform/openapi/reference/context-management/assign-group)                              | 将 Context Group 分配给项目。                         |
| [`unassignContextGroup`](/docs/platform/openapi/reference/context-management/unassign-group)                          | 取消项目的 Context Group 分配。                        |
| [`reorderContextGroup`](/docs/platform/openapi/reference/context-management/reorder-group)                            | 更改已分配 Context Group 的优先级。                      |
| [`listContextGlossary`](/docs/platform/openapi/reference/context-management/list-glossary)                            | 列出 Context Group 中的词汇表术语。                      |
| [`upsertContextGlossary`](/docs/platform/openapi/reference/context-management/upsert-glossary)                        | 创建或更新词汇表术语。                                    |
| [`getContextGlossaryEntry`](/docs/platform/openapi/reference/context-management/get-glossary-entry)                   | 读取单个词汇表术语。                                     |
| [`updateContextGlossaryEntry`](/docs/platform/openapi/reference/context-management/update-glossary-entry)             | 更新单个词汇表术语。                                     |
| [`deleteContextGlossaryEntry`](/docs/platform/openapi/reference/context-management/delete-glossary-entry)             | 删除单个词汇表术语。                                     |
| [`listContextGlossaryTranslations`](/docs/platform/openapi/reference/context-management/list-glossary-translations)   | 列出词汇表术语的译文。                                    |
| [`setContextGlossaryTranslation`](/docs/platform/openapi/reference/context-management/set-glossary-translation)       | 设置词汇表术语的译文。                                    |
| [`deleteContextGlossaryTranslation`](/docs/platform/openapi/reference/context-management/delete-glossary-translation) | 删除词汇表术语的译文。                                    |
| [`listContextCustomPrompts`](/docs/platform/openapi/reference/context-management/list-custom-prompts)                 | 列出 Context Group 中的自定义提示词。                     |
| [`upsertContextCustomPrompts`](/docs/platform/openapi/reference/context-management/upsert-custom-prompts)             | 创建或更新自定义提示词。                                   |
| [`updateContextCustomPrompt`](/docs/platform/openapi/reference/context-management/update-custom-prompt)               | 更新单个自定义提示词。                                    |
| [`deleteContextCustomPrompt`](/docs/platform/openapi/reference/context-management/delete-custom-prompt)               | 删除单个自定义提示词。                                    |
| [`importContextContent`](/docs/platform/openapi/reference/context-management/import-content)                          | 导入词汇表术语和自定义提示词。                                |
| [`exportContextContent`](/docs/platform/openapi/reference/context-management/export-content)                          | 导出词汇表术语和自定义提示词。                                |

<Callout type="info">
  &#42;&#42;v0.5.2 中的变更：&#42;&#42;生成的客户端新增了上下文管理端点辅助函数，涵盖上下文组、分配、词汇表术语、自定义提示词以及导入和导出。

  &#42;&#42;v0.5.0 中的变更：&#42;&#42;列表响应现在返回 `items`，不再返回 `projects` 或 `orgs`，以与当前 API 保持一致。`throwOnError` 调用失败时会抛出 [`ApiError`](#api-error)，而不再抛出解码后的响应体。

  **v0.3.0 中的变更：**`encodeBase64`、`decodeBase64`、`encodeFileContent` 和 `decodeFileContent` 不再导出。请在将文件内容传入生成的上传端点辅助函数之前先自行编码。

  **v0.2.1 中的变更：**[`createProject`](/docs/platform/openapi/reference/project/create-project) 现在需要 `path.orgId`，并调用 `POST /v2/orgs/{orgId}/projects`。此版本还新增了 [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key)，并移除了 `shouldGenerateProjectContext` 和 `getProjectContextGenerationStatus`。
</Callout>

处理上下文 job 时，请将 `generateProjectContext` 与 `getTranslationJobInfo` 搭配使用。[`downloadFile`](/docs/platform/openapi/reference/files/download) 端点辅助函数仍处于已弃用状态；无论批量下载还是单文件下载，请改用 `downloadFiles`。

如需查看实时的端点 Permission、速率限制、schema 和状态码，请参阅[公开 OpenAPI 参考](/docs/platform/openapi/overview)。

### 发现与预配

使用 [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs) 查找与你的 API Key 关联的组织。组织密钥和项目键均可使用；此查找操作无需创建项目的 Permission。

项目发现会根据 API Key 所绑定的范围返回一页结果：项目密钥返回其所属项目，组织密钥则返回该组织下的项目。此操作无需任何资源 Permission。使用 [`paginate`](#pagination) 可遍历所有项目：

```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);
}
```

创建项目需要具有 `org:projects:create` Permission 的组织 key，参数为 `path: { orgId }` 和 `body: { name, defaultLocale, cdnEnabled? }`。

调用 [`createProjectApiKey`](/docs/platform/openapi/reference/project/create-api-key) 时，请按最小 Permission 原则明确指定 `permissions`。如果省略该参数，则会请求调用方所持有的全部可委派项目 Permission；所选的每一项 Permission 都必须是你已持有的。请安全存储返回的 secret，切勿将其写入日志。

这些自动生成的发现与创建端点辅助函数并非 [`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` 会逐一产出列表操作 (例如 [`listProjects`](/docs/platform/openapi/reference/project/list-projects) 或 [`listOrgs`](/docs/platform/openapi/reference/project/list-orgs)) 返回的每一项，并将 `options` 传给每个分页请求。只有当迭代进行到下一页时，它才会请求该页，因此跳出循环即可停止后续请求。如需从中断处继续，请将之前保存的 `nextCursor` 作为 `query.cursor` 传入。若某一页请求失败，会像 `throwOnError` 调用一样抛出异常。

由于各页是独立读取的，迭代期间发生变化的项可能会被遗漏或重复返回。

## Job 轮询 [#job-polling]

[`awaitJobs`](#job-polling) 会使用已配置的客户端反复调用 `getTranslationJobInfo`，直到所请求的每个 job 都变为完成、失败、未知或缺失状态，或者整体 timeout 到期为止。

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

| 选项                       | 描述                           | 类型                                                  | 可选 | 默认值   |
| ------------------------ | ---------------------------- | --------------------------------------------------- | -- | ----- |
| `pollingIntervalSeconds` | 两次状态请求之间的间隔。                 | `number`                                            | 是  | `5`   |
| `timeoutSeconds`         | 轮询的总超时时间。                    | `number`                                            | 是  | `600` |
| `onPoll`                 | 在执行终态记录处理之前，接收每次成功返回的原始状态响应。 | `(statuses: GetTranslationJobInfoResponse) => void` | 是  | —     |

```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` 包含 `complete` (仅当轮询超时时才为 `false`) 和 `jobs` (包含每个所请求 ID 的最新结果) 。若某个 job 不存在，则其 status 为 `unknown`。传入空 array 时会立即以 `{ complete: true, jobs: [] }` resolve。

若在总体截止时间之前出现 API 或状态加载器错误，轮询的 Promise 会被拒绝。若 request 在截止时间过后才失败，轮询会返回最新结果，并将 `complete` 置为 `false`。

`pollJobs` 提供了同样的轮询循环，但允许注入自定义的状态加载器：

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

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

当你需要自定义请求或错误归一化处理时，可以使用它。轮询按顺序执行，每次只请求仍处于待处理状态的 ID。加载器会接收一个中止信号，该信号受剩余总截止时间和每次轮询 60 秒上限的共同约束。迟到的结果会被丢弃；超时时会返回最后一次被接受的状态，这些状态可能仍为排队中、处理中或初始的未知状态。如果加载器忽略该信号，可能会推迟 Promise 的 resolve。

`complete: true` 仅表示已没有待处理的 job，并不代表每个 job 都已成功。使用结果前，请逐一检查各个 status。两个 API 轮询端点辅助函数都接受 `onPoll`，但类方法 [`awaitJobs`](/docs/platform/core/reference/gt-class-methods/translation/await-jobs) 的选项不支持该参数。所有轮询选项都不提供调用方信号，且停止本地轮询并不会取消远程 job。

## 批量处理 [#batch-processing]

`processBatches` 会将输入 array 拆分成多个分块，对每个分块调用你的处理函数，并按 batch 顺序将返回的 arrays 展平。

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

| 选项          | 描述                     | 类型        | 可选 | 默认值                  |
| ----------- | ---------------------- | --------- | -- | -------------------- |
| `batchSize` | 每个 batch 中的输入值数量，需大于零。 | `number`  | 是  | `DEFAULT_BATCH_SIZE` |
| `parallel`  | 并发处理所有 batch，而非依次处理。   | `boolean` | 是  | `true`               |

`DEFAULT_BATCH_SIZE` 为 `100`。

若某个 batch 处理器 reject，则 `processBatches` 也会 reject。在并发模式下，其他已启动的 batch 会继续独立执行。

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

// 生成的端点辅助函数要求文件内容已编码为可传输的形式。
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-errors]

该模块导出 `Client`、`Options`、`ApiClientConfig`、`ApiVersion`、`RetryPolicy`、`AwaitJobsOptions`、`AwaitJobsResult`、`GetJobStatuses`、`JobResult`、`BatchOptions`、`RuntimeFileFormat`，以及为上文列出的公开操作生成的 OpenAPI 类型。

对于上文列出的每一个公开操作，该 package 都会导出：

* `<Operation>Data`：用于类型化的 body、headers、path 和 query 输入。
* `<Operation>Errors`：文档中已声明错误的状态码映射。
* `<Operation>Error`：文档中已声明错误的 union。
* `<Operation>Responses`：文档中已声明成功响应的状态码映射。
* `<Operation>Response`：文档中已声明成功响应的 union。

在默认的 `throwOnError: false` 下，生成的操作会返回 `data` 或 `error`，并附带 Fetch API 的 `request`。若收到了 HTTP 响应，结果中会包含 `response`；如果在收到响应之前就失败，该字段为 undefined。当 `throwOnError: true` 时，`createApiClient` 客户端收到 HTTP 错误响应会 throw 一个 [`ApiError`](#api-error)。网络故障和取消操作导致的失败会直接 throw 原始错误；内置超时则会 throw `Error('Request timed out after <timeoutMs>ms')`。

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

使用 `createApiClient` 客户端时，`throwOnError` 调用、[`paginate`](#pagination)、[`awaitJobs`](#job-polling) 以及 [`GT`](/docs/platform/core/reference/gt-class/constructor) 类方法在 HTTP 响应失败时会抛出 `ApiError`，其中包含 `name: 'ApiError'`、`code` (数字形式的 HTTP 状态码) 以及 `message`。可从 `generaltranslation/api` 或 `generaltranslation/errors` 导入该类。未使用 `throwOnError` 的调用仍会在 `error` 中返回解码后的响应体。网络、配置、取消和超时等失败可能导致整个类方法调用被 reject；这类失败不一定是单个条目的翻译失败。

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

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

## OpenAPI 规范 [#openapi-spec]

如需获取当前托管的公开 API 契约，请使用 [`/openapi.json`](/openapi.json)。[OpenAPI 参考](/docs/platform/openapi/overview)介绍了各端点所需的权限、请求 schema 和响应。

## Sitemap

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