如何在 API 请求中传递 X-API-Key 请求头 (2026)
通过 Header 进行 API key 身份验证的实用指南
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
如何在 API 请求中传递 X-API-Key Header (2026)
X-API-Key 请求头是 REST API 最常用的身份验证方法之一。它具有简洁、支持广泛以及易于在各种编程语言中实现的特点。本指南将向您展示如何在主流编程语言和工具中传递 X-API-Key 标头,并提供安全最佳实践。
什么是 X-API-Key Header?
X-API-Key 是一个自定义 HTTP header,用于随请求发送 API 密钥。API 服务器通过检查此密钥来对调用者进行身份验证和授权。
一个典型的请求如下所示:
GET /api/v1/users HTTP/1.1
Host: api.example.com
X-API-Key: sk_live_abc123def456
Content-Type: application/json
尽管 RFC 6648 已弃用此约定,但在历史上 X- 前缀表示非标准 header。尽管如此,X-API-Key 仍然是 API 密钥标头中使用最广泛的名称。
X-API-Key 与其他身份验证方法的对比
| 方法 | Header | 使用场景 | 安全级别 |
|---|---|---|---|
| X-API-Key | X-API-Key: <key> |
服务间通信、公共 API | 中 |
| Bearer Token | Authorization: Bearer <token> |
用户认证、OAuth | 高 |
| Basic Auth | Authorization: Basic <base64> |
简单的用户名/密码 | 低 |
| Query Parameter | ?api_key=<key> |
遗留 API (应避免使用) | 低 |
如何在 cURL 中传递 X-API-Key
cURL 是从命令行测试 API 密钥身份验证最快的方法:
# 使用 X-API-Key 发送 GET 请求
curl -H "X-API-Key: sk_live_abc123def456" \
https://api.example.com/v1/users
# 使用 X-API-Key 和 JSON 正文发送 POST 请求
curl -X POST \
-H "X-API-Key: sk_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}' \
https://api.example.com/v1/users
# 使用环境变量(推荐)
export API_KEY="sk_live_abc123def456"
curl -H "X-API-Key: $API_KEY" \
https://api.example.com/v1/users
如何在 Python 中传递 X-API-Key
使用 `requests` 库
import os
import requests
api_key = os.environ["API_KEY"]
# GET 请求
response = requests.get(
"https://api.example.com/v1/users",
headers={"X-API-Key": api_key}
)
print(response.json())
# POST 请求
response = requests.post(
"https://api.example.com/v1/users",
headers={"X-API-Key": api_key},
json={"name": "John", "email": "john@example.com"}
)
print(response.status_code)
使用 Session 处理多个请求
如果您对同一个 API 发起多个请求,请使用 Session 以避免重复设置 header:
import os
import requests
session = requests.Session()
session.headers.update({
"X-API-Key": os.environ["API_KEY"],
"Content-Type": "application/json"
})
# 此 session 中的所有请求都将包含 API 密钥
users = session.get("https://api.example.com/v1/users").json()
posts = session.get("https://api.example.com/v1/posts").json()
使用 `httpx` (异步)
import os
import httpx
async def fetch_users():
async with httpx.AsyncClient(
headers={"X-API-Key": os.environ["API_KEY"]}
) as client:
response = await client.get("https://api.example.com/v1/users")
return response.json()
如何在 JavaScript 中传递 X-API-Key
使用 Fetch API (浏览器与 Node.js)
const apiKey = process.env.API_KEY;
// GET 请求
const response = await fetch("https://api.example.com/v1/users", {
headers: {
"X-API-Key": apiKey,
},
});
const data = await response.json();
// POST 请求
const postResponse = await fetch("https://api.example.com/v1/users", {
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "John",
email: "john@example.com",
}),
});
使用 Axios
import axios from "axios";
// 创建带有默认 headers 的 axios 实例
const api = axios.create({
baseURL: "https://api.example.com/v1",
headers: {
"X-API-Key": process.env.API_KEY,
},
});
// 所有请求都将自动包含 API 密钥
const users = await api.get("/users");
const newUser = await api.post("/users", {
name: "John",
email: "john@example.com",
});
如何在 Go 中传递 X-API-Key
package main
import (
"fmt"
"net/http"
"os"
"io"
)
func main() {
apiKey := os.Getenv("API_KEY")
req, err := http.NewRequest("GET", "https://api.example.com/v1/users", nil)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
如何在 PHP 中传递 X-API-Key
<?php
$apiKey = getenv('API_KEY');
// 使用 cURL
$ch = curl_init('https://api.example.com/v1/users');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-API-Key: $apiKey",
"Content-Type: application/json",
],
]);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
// 使用 Guzzle
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://api.example.com/v1/',
'headers' => [
'X-API-Key' => $apiKey,
],
]);
$response = $client->get('users');
$data = json_decode($response->getBody(), true);
如何在 API 测试工具中传递 X-API-Key
Postman
- 在 Postman 中打开您的请求
- 点击 Headers 选项卡
- 添加一个新的 header:
- Key:
X-API-Key - Value:
{{api_key}}(建议使用 Postman 变量)
- Key:
- 在您的 Postman 环境中设置该变量以便复用
HTTPie
# HTTPie 使用简洁的 header 语法
http GET https://api.example.com/v1/users \
X-API-Key:sk_live_abc123def456
# 发送带有 JSON 正文的 POST 请求
http POST https://api.example.com/v1/users \
X-API-Key:sk_live_abc123def456 \
name=John email=john@example.com
安全最佳实践
1. 永不硬编码 API 密钥
# 错误写法 - 密钥留在源代码中
headers = {"X-API-Key": "sk_live_abc123def456"}
# 正确写法 - 密钥从环境变量中读取
headers = {"X-API-Key": os.environ["API_KEY"]}
2. 使用环境变量或密钥管理器
# .env 文件 (切勿提交此文件)
API_KEY=sk_live_abc123def456
# 在应用程序中使用 dotenv 加载
将 .env 添加到您的 .gitignore:
# .gitignore
.env
.env.local
.env.production
3. 始终使用 HTTPS
通过 HTTP 发送的 API 密钥以明文形式传输。请始终使用 HTTPS 端点:
# 错误写法 - 密钥对网络中的任何人可见
curl -H "X-API-Key: sk_live_abc123" http://api.example.com/v1/users
# 正确写法 - 使用 TLS 加密
curl -H "X-API-Key: sk_live_abc123" https://api.example.com/v1/users
4. 定期轮换密钥
大多数 API 提供商允许您创建多个密钥。请分别为开发和生产环境使用不同的密钥,并定期进行轮换。
5. 限制密钥权限
如果您的 API 提供商支持,请将密钥的作用域限制在特定操作中:
| 密钥 | 权限 | 环境 |
|---|---|---|
sk_dev_xxx |
只读 | 开发环境 |
sk_staging_xxx |
读/写 | 测试环境 |
sk_prod_xxx |
读/写 (限制 IP) | 生产环境 |
错误处理
API 密钥身份验证失败时常见的 HTTP 响应:
| 状态码 | 含义 | 可能原因 |
|---|---|---|
| 401 Unauthorized | 缺失或无效的密钥 | 密钥拼写错误、密钥已过期 |
| 403 Forbidden | 密钥有效,但权限不足 | 密钥缺少所需的 scope (范围) |
| 429 Too Many Requests | 超出频率限制 | 每分钟请求次数过多 |
response = requests.get(url, headers={"X-API-Key": api_key})
if response.status_code == 401:
print("API 密钥无效。请检查您的凭据。")
elif response.status_code == 403:
print("您的 API 密钥没有访问此端点的权限。")
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After", 60)
print(f"触发频率限制。请在 {retry_after} 秒后重试。")
总结
在任何语言或工具中传递 X-API-Key 标头都非常直接。核心要点是永远不要硬编码您的 API 密钥,始终使用 HTTPS,并将密钥存储在环境变量或密钥管理器中。
如果您正在寻找使用 X-API-Key 身份验证的媒体生成 API,Hypereal AI 提供了基于 API 密钥的简便访问方式,支持 AI 图像生成、视频创建等功能——所有这些都遵循本指南中展示的模式。
