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

# 发出请求

> 了解如何正确发出 API 请求

> 更新日期：2026-06-14

## 请求格式

所有 API 请求使用 HTTPS 协议，请求体使用 JSON 格式。

<Note>
  默认优先使用 `https://api.crazyrouter.com/v1`。如果你在某个工具里不确定该填根域名还是 `/v1`，先参考 [API Endpoint 说明](https://docs.crazyrouter.com/en/api-endpoint)。
</Note>

### 必需的请求头

| Header          | 值                     | 说明       |
| --------------- | --------------------- | -------- |
| `Authorization` | `Bearer YOUR_API_KEY` | API 认证密钥 |
| `Content-Type`  | `application/json`    | 请求体格式    |

### 可选请求头

| Header             | 值                  | 说明                  |
| ------------------ | ------------------ | ------------------- |
| `Accept`           | `application/json` | 响应格式                |
| `Content-Encoding` | `gzip`             | 可选。请求体使用 gzip 压缩时设置 |

## 请求示例

```bash theme={null}
curl https://api.crazyrouter.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -d '{
    "model": "gpt-5.5",
    "messages": [{"role": "user", "content": "Hello"}],
    "stream": false
  }'
```

## 使用 gzip 发送请求体

如果你的请求体很大，例如每次都上传长上下文、长文档或大量消息历史，可以把原始 JSON 请求体 gzip 压缩后发送。

开启 gzip 只改变传输方式，不改变请求语义。服务端会在解析 JSON 前自动解压。

需要增加请求头：

```http theme={null}
Content-Type: application/json
Content-Encoding: gzip
```

<Note>
  `Content-Encoding: gzip` 表示“请求体已经 gzip 压缩”。它和 `Accept-Encoding: gzip` 不同，后者通常用于响应压缩。
</Note>

### Python

```python theme={null}
import gzip
import json
import requests

payload = {
    "model": "gpt-5.5",
    "messages": [
        {"role": "user", "content": "这里放很长的上下文或文档内容..."}
    ],
    "stream": False
}

raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
compressed = gzip.compress(raw)

resp = requests.post(
    "https://api.crazyrouter.com/v1/chat/completions",
    headers={
        "Authorization": "Bearer sk-xxxxxxxx",
        "Content-Type": "application/json",
        "Content-Encoding": "gzip",
    },
    data=compressed,
    timeout=120,
)

print(resp.status_code, resp.text)
```

### Node.js

```js theme={null}
import zlib from "node:zlib";

const payload = {
  model: "gpt-5.5",
  messages: [
    { role: "user", content: "这里放很长的上下文或文档内容..." },
  ],
  stream: false,
};

const raw = Buffer.from(JSON.stringify(payload));
const compressed = zlib.gzipSync(raw);

const resp = await fetch("https://api.crazyrouter.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer sk-xxxxxxxx",
    "Content-Type": "application/json",
    "Content-Encoding": "gzip",
  },
  body: compressed,
});

console.log(resp.status, await resp.text());
```

### cURL

```bash theme={null}
cat > body.json <<'JSON'
{
  "model": "gpt-5.5",
  "messages": [
    {
      "role": "user",
      "content": "这里放很长的上下文或文档内容..."
    }
  ],
  "stream": false
}
JSON

gzip -c body.json > body.json.gz

curl https://api.crazyrouter.com/v1/chat/completions \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "Content-Encoding: gzip" \
  --data-binary @body.json.gz
```

### 自动按大小启用 gzip

如果你的系统是一个工作流，通常不需要在业务逻辑里手工区分“哪些请求压缩、哪些不压缩”。建议在统一的 HTTP 客户端封装层判断 JSON body 大小，超过阈值再自动 gzip。

推荐阈值：

```text theme={null}
body >= 128KB：启用 gzip
body < 128KB：保持原样发送
```

如果你的请求经常是 MB 级，也可以把阈值设为 `256KB`。小请求不建议强制 gzip，因为压缩开销和 gzip 头部可能让体积反而变大。

Python 封装示例：

```python theme={null}
import gzip
import json
import requests

def post_json(url, payload, api_key, gzip_threshold=128 * 1024):
    raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }

    if len(raw) >= gzip_threshold:
        body = gzip.compress(raw)
        headers["Content-Encoding"] = "gzip"
    else:
        body = raw

    return requests.post(url, headers=headers, data=body, timeout=120)
```

Node.js 封装示例：

```js theme={null}
import zlib from "node:zlib";

async function postJson(url, payload, apiKey, gzipThreshold = 128 * 1024) {
  const raw = Buffer.from(JSON.stringify(payload));
  const headers = {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  };

  const body =
    raw.length >= gzipThreshold
      ? (() => {
          headers["Content-Encoding"] = "gzip";
          return zlib.gzipSync(raw);
        })()
      : raw;

  return fetch(url, {
    method: "POST",
    headers,
    body,
  });
}
```

适用场景：

* 单次请求体通常超过 1MB
* 重复上传长上下文或长文档
* 客户端可以直接控制 HTTP body 和请求头

## 流式请求

设置 `stream: true` 启用 SSE 流式输出：

```bash theme={null}
curl https://api.crazyrouter.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -d '{
    "model": "gpt-5.5",
    "messages": [{"role": "user", "content": "Hello"}],
    "stream": true
  }'
```

流式响应格式为 Server-Sent Events (SSE)，每个事件以 `data: ` 开头，最后以 `data: [DONE]` 结束。

## 在线调试

你可以使用以下方式在线调试 API：

1. **Crazyrouter Playground** - 登录后访问 [crazyrouter.com/console/playground](https://crazyrouter.com/console/playground) 直接在浏览器中测试
2. **cURL** - 使用命令行工具发送请求
3. **Postman / Apifox** - 使用 API 调试工具
