跳转到正文Skip to content

5 分钟 Quickstart

1. 准备环境变量

在用户中心创建 API Key,把它注入本地环境。不要把 Key 写进源码、终端历史、日志或截图。

bash
export API_KEY="从安全环境注入"
export API_BASE_URL="数据 API 地址"
export MODEL="从 /v1/models 返回结果中选择"

数据 API 使用 Authorization: Bearer $API_KEY。先调用 /v1/models 确认当前套餐权益允许的模型,再运行以下任一片段。

2. 发起请求

cURL

bash
#!/usr/bin/env bash
set -euo pipefail

: "${API_KEY:?Set API_KEY in your environment}"
: "${API_BASE_URL:?Set API_BASE_URL to the data API origin}"
: "${MODEL:?Set MODEL to a model listed by /v1/models}"

curl --fail-with-body --silent --show-error \
  "${API_BASE_URL}/v1/chat/completions" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  --data "{\"model\":\"${MODEL}\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with one short greeting.\"}]}"

Python(标准库)

python
import json
import os
import urllib.request

api_key = os.environ["API_KEY"]
base_url = os.environ["API_BASE_URL"].rstrip("/")
model = os.environ["MODEL"]
body = json.dumps({
    "model": model,
    "messages": [{"role": "user", "content": "Reply with one short greeting."}],
}).encode()
request = urllib.request.Request(
    f"{base_url}/v1/chat/completions",
    data=body,
    headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
    method="POST",
)

with urllib.request.urlopen(request, timeout=30) as response:
    print(response.read().decode())

Node.js 18+

js
const apiKey = process.env.API_KEY
const baseURL = process.env.API_BASE_URL?.replace(/\/$/, '')
const model = process.env.MODEL

if (!apiKey || !baseURL || !model) {
  throw new Error('Set API_KEY, API_BASE_URL, and MODEL in the environment')
}

const response = await fetch(`${baseURL}/v1/chat/completions`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model,
    messages: [{ role: 'user', content: 'Reply with one short greeting.' }],
  }),
  signal: AbortSignal.timeout(30_000),
})

if (!response.ok) throw new Error(`Request failed with HTTP ${response.status}`)
console.log(await response.json())

3. 检查结果

保存响应头 X-Request-Id 用于排查,但不要记录请求正文或响应正文。可通过 /v1/balance 查看可用余额,通过 /v1/usage 查看当前凭据范围内的汇总用量。

下一步:认证与 Key 安全 · 错误处理