# 使用 cURL 调用 Grok API

使用 cURL 测试 Grok API Dev 密钥、复现 HTTP 错误并查看流式响应。所有示例都调用兼容 OpenAI 的 Responses API。

## 准备 API 密钥

```bash
curl --version
```

```bash
export GROK_API_DEV_KEY="sk-lg-YOUR_API_KEY"
```

## 调用 Responses API

```bash
curl --fail-with-body https://api.llm-gate.tech/v1/responses \
  -H "Authorization: Bearer $GROK_API_DEV_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.5",
    "input": "Explain HTTP in two sentences"
  }'
```

## 读取 JSON 响应

```json
{
  "id": "resp_01abc",
  "status": "completed",
  "output": [
    {
      "type": "message",
      "role": "assistant",
      "content": [
        { "type": "output_text", "text": "HTTP is..." }
      ]
    }
  ],
  "usage": {
    "input_tokens": 12,
    "output_tokens": 34,
    "total_tokens": 46
  }
}
```

## 使用 cURL 查看 SSE 流

```bash
curl -N --fail-with-body https://api.llm-gate.tech/v1/responses \
  -H "Authorization: Bearer $GROK_API_DEV_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.5",
    "input": "Write a short example",
    "stream": true
  }'
```

## 检查 HTTP 错误

从短 input 和最小 JSON 开始排查。需要同时查看响应头时添加 -i。

```bash
curl -i --fail-with-body https://api.llm-gate.tech/v1/responses \
  -H "Authorization: Bearer $GROK_API_DEV_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.5",
    "input": "Test request"
  }'
```

- 401：检查 Bearer 请求头和 GROK_API_DEV_KEY。
- 404：检查 /v1/responses 路径和 grok-4.5 模型 ID。
- 429：如果有 Retry-After，请按其等待并降低请求频率。
- DNS 或 TLS 故障没有 HTTP 状态，应先检查网络和主机名。

[完整 API 错误参考](https://grok-api.dev/zh/docs/errors)

## 相关页面

- [Messages API](https://grok-api.dev/zh/docs/messages)
- [Streaming API](https://grok-api.dev/zh/docs/streaming)
- [Python](https://grok-api.dev/zh/docs/python)
- [TypeScript](https://grok-api.dev/zh/docs/typescript)
