# 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 客户端。该模块将带认证、带版本、自动重试的传输层与生成的端点辅助函数结合在一起，并提供可选启用的工具，用于批量处理以及翻译任务的轮询。

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

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

## 概览 [#overview]

| 导出                                                                                | 说明                            |
| --------------------------------------------------------------------------------- | ----------------------------- |
| [`createApiClient`](#create-client)                                               | 创建已认证的客户端，并处理版本、重试和超时。        |
| [`ApiClientConfig`](#client-config)                                               | 配置客户端传输层与共享的请求 header。        |
| [`API_VERSION`](#api-version)                                                     | 默认发送的当前 API 契约版本。             |
| [端点辅助函数](#endpoint-helpers)                                                       | 为内置 OpenAPI 快照中的每个操作生成的类型化函数。 |
| [`awaitJobs`](#job-polling) 与 [`pollJobs`](#job-polling)                          | 轮询翻译任务，直至其完成或超时。              |
| [`processBatches`](#batch-processing) 与 [`DEFAULT_BATCH_SIZE`](#batch-processing) | 按可配置的 batch 大小处理输入数组。         |
| [生成的类型](#types-errors)                                                            | 描述端点数据、响应、错误以及客户端契约。          |
| [内置 OpenAPI 规范](#openapi-spec)                                                    | 用于生成已安装 package 的 JSON 快照。    |

## `createApiClient` [#create-client]

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

该客户端会为每个请求自动添加已配置的 API 版本、bearer 令牌和项目 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 或 OAuth 用户访问令牌。 | `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 <credential>` 形式发送的 API Key 或 OAuth 2.1 用户访问令牌。客户端不会自动读取环境变量。

### `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 和 OAuth 用户访问令牌在调用路径中不包含项目 ID 的项目层级端点时需要该 header。

### `retryPolicy`

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

幂等请求在遇到网络错误、`429` 响应和 `5xx` 响应时最多重试三次。非幂等请求仅对 `429` 响应重试，不会重试网络错误或 `5xx` 响应。若由调用方自行负责重试，请将其设置为 `'none'`。

### `timeoutMs`

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

每次请求尝试的超时时间 (毫秒) 。如果由自定义 `fetch` 实现来控制请求超时，请将其设置为 `false`。

## `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.3.0 SDK 为以下公开操作提供了生成的端点辅助函数：

| 函数                                                                                 | 操作                       |
| ---------------------------------------------------------------------------------- | ------------------------ |
| [`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`                                                                 | 查找孤立文件。                  |

<Callout type="info">
  **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`。

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

## 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` |

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

当你需要自定义请求或错误归一化处理时，可以使用它。加载器会接收一个中止信号，该信号受剩余总截止时间和每次轮询 60 秒上限的共同约束。

## 批量处理 [#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` 时，API、网络、取消和超时等失败都会 throw。

## OpenAPI 规范 [#openapi-spec]

导入用于生成已安装客户端的快照：

```ts
import openApiSpec from 'generaltranslation/api/openapi.json' with {
  type: 'json',
};
```

独立的 `@generaltranslation/api` package 提供相同的 SDK，并在 `@generaltranslation/api/spec/openapi.json` 发布其快照。[`gt api --spec`](/docs/cli/reference/commands/api) 命令会输出随该 CLI 已安装的 Core 依赖一并打包的快照。如需查看当前托管的接口契约，请使用 [`/openapi.json`](/openapi.json)。

## Sitemap

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