> ## Documentation Index
> Fetch the complete documentation index at: https://docs.playapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# REST 示例运行环境

> 配置根地址与共享 HTTP 模块，执行新增 REST 示例。

本页用于 Gemini 原生向量、通用任务、Alpha Search 和 Midjourney 状态示例。使用 Node.js 22.18+ 或 24 LTS，在文档目录执行。`API_ROOT_URL` 是网关根地址及可选部署前缀，**不包含 `/v1` 或 `/v1beta`**。`API_KEY` 是网关令牌。

```bash theme={null}
npm ci
export API_ROOT_URL="https://gateway.example.com"
export API_KEY="YOUR_API_KEY"
export API_MODEL="YOUR_MODEL_ID"
```

复制脚本到独立项目时，同时复制 `examples/http-client.mjs`。它只访问配置的网关，通过 Bearer 认证；拒绝重定向、URL 内凭据、query 和 fragment。每次请求含读取响应的超时为 60 秒，JSON 最大 1 MiB，均为示例本地限制；没有自动重试。错误输出不打印响应原文或密钥。

JSON 请求先验证 HTTP、Content-Type 和错误信封，再由各示例校验业务字段。HTTP 200 并不保证完成。二进制下载由任务示例另设 20 MiB 上限。网络异常后，生成类请求应先查询已知任务，不能盲目重发。

此模块不能单独调用模型。现有 Python / SDK 示例继续使用包含 `/v1` 的 `API_BASE_URL`，不要混用这两个环境变量。

```javascript theme={null}
// Shared server-side transport for the additional REST examples.
let root;
try { root = new URL(process.env.API_ROOT_URL || 'invalid:'); }
catch { throw new Error('Set a valid API_ROOT_URL.'); }
const key = process.env.API_KEY;
if (!['http:', 'https:'].includes(root.protocol) || root.username || root.password
  || root.search || root.hash || !key?.trim()) {
  throw new Error('Set HTTP(S) API_ROOT_URL without credentials/query/fragment and API_KEY.');
}
export async function request(path, options = {}) {
  if (!path.startsWith('/') || path.startsWith('//') || /[?#\\]/.test(path)
    || path.split('/').some((part) => ['.', '..'].includes(part))) {
    throw new Error('Invalid gateway path.');
  }
  const response = await fetch(`${root.href.replace(/\/+$/, '')}${path}`, {
    ...options, redirect: 'error', signal: AbortSignal.timeout(60_000),
    headers: { ...options.headers, Authorization: `Bearer ${key}` },
  });
  if (!response.ok) {
    await response.body?.cancel();
    throw new Error(`Request failed (HTTP ${response.status}). No automatic retry.`);
  }
  return response;
}
export async function readBody(response, limit) {
  const reader = response.body?.getReader();
  if (!reader) throw new Error('Missing response body.');
  const chunks = [];
  let size = 0;
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      size += value.length;
      if (size > limit) throw new Error('Example response size limit exceeded.');
      chunks.push(value);
    }
  } finally {
    await reader.cancel();
    reader.releaseLock();
  }
  return Buffer.concat(chunks);
}
export async function requestJSON(path, body) {
  const response = await request(path, body === undefined ? {} : {
    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
  });
  if (!/^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/i.test(response.headers.get('content-type') || '')) {
    await response.body?.cancel();
    throw new Error('Expected a JSON response.');
  }
  const result = JSON.parse((await readBody(response, 1024 * 1024)).toString('utf8'));
  if (!result || typeof result !== 'object' || Array.isArray(result) || result.error || result.success === false) {
    throw new Error('Invalid or unsuccessful JSON response.');
  }
  return result;
}
```

[Read in English](/en/guides/http-runtime)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.