认证
New API 使用 API Key 进行认证,所有请求都需要在 Header 中携带有效的 API Key。
获取 API Key
- 登录 New API 管理后台
- 进入「个人中心」→「API Key」
- 点击「创建 Key」
- 复制生成的 Key(只显示一次)
使用 API Key
在请求头中添加 Authorization:
http
Authorization: Bearer sk-newapi-xxxxxxxxxxxxxxxx示例
cURL
bash
curl https://your-domain.com/v1/chat/completions \
-H "Authorization: Bearer sk-newapi-xxxxxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello!"}]
}'Python
python
import requests
headers = {
"Authorization": "Bearer sk-newapi-xxxxxxxxxxxxxxxx",
"Content-Type": "application/json"
}
response = requests.post(
"https://your-domain.com/v1/chat/completions",
headers=headers,
json={
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello!"}]
}
)JavaScript
javascript
const response = await fetch('https://your-domain.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-newapi-xxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello!' }]
})
});安全建议
- 保密存储:不要在代码中硬编码 API Key,使用环境变量
- 定期轮换:定期更换 API Key,降低泄露风险
- 权限控制:为不同用途创建不同的 Key,便于管理
- 监控使用:定期检查 Key 的使用情况,发现异常及时处理
错误响应
401 Unauthorized
json
{
"error": {
"message": "Invalid API key",
"type": "authentication_error"
}
}403 Forbidden
json
{
"error": {
"message": "Insufficient quota",
"type": "quota_exceeded"
}
}