# 身份验证

> URL: https://foura.ai/zh/docs/getting-started/authentication
> Updated: 2026-10-29
> Index: https://foura.ai/llms.txt

对 FourA API 的每个 request 均需进行身份验证。本页介绍如何获取、使用和管理您的 API key。

## 获取您的 API Key

1. 登录 [FourA 控制台](https://foura.ai/dashboard)
2. 进入 **API Keys** 页面
3. 点击 **Create Key**
4. 从确认对话框中复制密钥

您的 API key 格式如下：`pk_live_a1b2c3d4e5f6...`

当前创建的密钥支持重新查看：后续点击密钥所在行的眼睛图标，即可按需查看完整密钥（有关查看流程与权限，请参阅 [管理 API Keys](https://foura.ai/docs/dashboard/api-keys)）。在支持该功能之前创建的历史密钥无法重新查看，且会显示锁定图标；重新生成一次即可切换至新格式。

## 使用您的 API Key

在每个 request 的 `X-API-Key` header 中包含您的 API key：

```bash
curl -X POST https://eu.api.foura.ai/api/single/ \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"method": "GET", "url": "https://example.com"}'
```

Python 示例：

```python
import requests

response = requests.post(
    "https://eu.api.foura.ai/api/single/",
    headers={
        "X-API-Key": "YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    json={"method": "GET", "url": "https://example.com"}
)
```

在 Node.js 中：

```javascript
const response = await fetch('https://eu.api.foura.ai/api/single/', {
  method: 'POST',
  headers: {
    'X-API-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ method: 'GET', url: 'https://example.com' })
});
```

## API Key 安全性

请像对待密码一样妥善保管您的 API key：

- **切勿提交至版本控制系统。** 请改用环境变量。
- **切勿在客户端代码中暴露。** 仅在服务端应用程序中使用。
- **发生泄露时立即轮换。** 可在控制台中重新生成 key。旧凭证将在 1 分钟内失效，且每次查看 key 均有审计日志记录，便于事后排查凭证被盗情况。

### 使用环境变量

将您的 key 存储在环境变量中：

```bash
export FOURA_API_KEY="pk_live_a1b2c3d4e5f6..."
```

然后在代码中引用它：

```python
import os
api_key = os.environ["FOURA_API_KEY"]
```

```javascript
const apiKey = process.env.FOURA_API_KEY;
```

## 常见身份验证错误

所有身份验证失败均返回 `401 Unauthorized` 状态码。

| 错误 | 消息 | 原因 | 解决方法 |
|-------|---------|-------|-----|
| 401 | Missing API key. Include X-API-Key header. | request 中缺少 `X-API-Key` header | 添加 `X-API-Key` header |
| 401 | Invalid API key | 错误的 key、包含多余空格或 key 已停用 | 核对 key、去除空格，或在 Dashboard 中创建新 key |

如果 FourA 暂时无法验证 key（例如数据库切换期间），将返回 `503` 以及 `API key check temporarily unavailable` 和 `Retry-After: 5`，绝不会返回 `401`。在该等待时间后重试即可，您的 key 没有问题。

无论是成功还是失败，每个 response 都会包含 `X-Foura-Request-Id` header，除非 FourA 完全无法读取请求体（如 JSON 格式错误或请求体超过 100 KB），此类请求会在分配 ID 之前被拒绝。请在您的端记录该 ID，以便技术支持后续排查特定请求。

## 后续步骤

- [快速入门](https://foura.ai/docs/getting-started/quick-start)：发送您的第一个 request
- [管理 API Key](https://foura.ai/docs/dashboard/api-keys)：查看、修改、重新生成和删除 key
- [API 端点](https://foura.ai/docs/api/endpoints)：完整的 endpoint 参考
- [错误处理](https://foura.ai/docs/api/errors)：优雅处理身份验证错误
