009_API参考与接口规范
API参考与接口规范
目录
- API访问
- 认证机制
- 请求格式
- 响应格式
- 核心接口
- 错误处理
- SDK使用
API访问
基础信息
- API基础URL:
https://api.anthropic.com
- 协议:HTTPS
- 数据格式:JSON
- 访问方式:RESTful API
访问入口
- Anthropic Console:console.anthropic.com
- API密钥管理:控制台账户设置中生成
- Workbench测试:在浏览器中测试API调用
系统状态
- 服务状态页面:实时查看Anthropic服务状态
- 可用性监控:监控API可用性和性能
- 维护通知:提前通知计划维护
认证机制
API密钥认证
所有API请求必须包含认证信息:
请求头设置:
x-api-key: your-api-key-here
content-type: application/json
安全要求:
- API密钥不得在客户端代码中暴露
- 建议使用环境变量存储密钥
- 定期轮换API密钥
- 监控API密钥使用情况
组织ID
- 响应头包含:
anthropic-organization-id
- 用途:标识请求所属组织
- 计费关联:与组织计费账户关联
请求格式
通用请求头
POST /v1/messages
Host: api.anthropic.com
Content-Type: application/json
x-api-key: your-api-key
Accept: application/json
请求体结构
所有请求使用JSON格式:
{"model": "claude-opus-4-20250514","max_tokens": 1024,"messages": [{"role": "user","content": "Hello, Claude"}]
}
通用参数
模型参数
- model (必需):指定要使用的Claude模型
claude-opus-4-20250514
:最强大模型claude-sonnet-4-20250514
:平衡性能模型claude-haiku-3-20240307
:快速响应模型
输出控制
- max_tokens (必需):最大生成token数量
- temperature (可选):控制输出随机性 (0.0-1.0)
- top_p (可选):核采样参数 (0.0-1.0)
- stop_sequences (可选):停止序列数组
系统参数
- system (可选):系统提示词
- metadata (可选):请求元数据
- stream (可选):是否启用流式输出
响应格式
成功响应
{"id": "msg_01234567890","type": "message","role": "assistant","content": [{"type": "text","text": "Hello! How can I help you today?"}],"model": "claude-opus-4-20250514","stop_reason": "end_turn","stop_sequence": null,"usage": {"input_tokens": 12,"output_tokens": 25}
}
响应头信息
HTTP/1.1 200 OK
Content-Type: application/json
request-id: req_01234567890
anthropic-organization-id: org_01234567890
流式响应
启用stream: true
时:
data: {"type": "message_start", "message": {...}}
data: {"type": "content_block_start", "index": 0, "content_block": {...}}
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
data: {"type": "content_block_stop", "index": 0}
data: {"type": "message_stop"}
核心接口
Messages API
创建消息
端点: POST /v1/messages
基础示例:
import anthropicclient = anthropic.Anthropic(api_key="your-api-key")message = client.messages.create(model="claude-opus-4-20250514",max_tokens=1024,messages=[{"role": "user", "content": "解释量子计算的基本原理"}]
)print(message.content)
多轮对话:
messages = [{"role": "user", "content": "什么是机器学习?"},{"role": "assistant", "content": "机器学习是人工智能的一个分支..."},{"role": "user", "content": "它有哪些主要类型?"}
]response = client.messages.create(model="claude-sonnet-4-20250514",max_tokens=1500,messages=messages
)
系统提示
response = client.messages.create(model="claude-opus-4-20250514",max_tokens=1024,system="你是一个专业的技术文档编写助手,请用清晰简洁的语言回答。",messages=[{"role": "user", "content": "解释RESTful API的设计原则"}]
)
Batch API
批处理请求
端点: POST /v1/messages/batches
优势:
- 50%的token使用折扣
- 适合大量非实时处理
- 24小时内完成处理
示例:
batch_request = {"requests": [{"custom_id": "request-1","params": {"model": "claude-sonnet-4-20250514","max_tokens": 1024,"messages": [{"role": "user", "content": "分析这篇文章的情感倾向..."}]}},{"custom_id": "request-2", "params": {"model": "claude-sonnet-4-20250514","max_tokens": 1024,"messages": [{"role": "user", "content": "总结这个产品的特点..."}]}}]
}batch = client.batches.create(**batch_request)
Files API (Beta)
文件上传
端点: POST /v1/files
支持格式:
- 文档:PDF, DOCX, TXT
- 图片:JPG, PNG, GIF
- 数据:CSV, JSON
示例:
# 上传文件
with open("document.pdf", "rb") as file:uploaded_file = client.files.create(file=file,purpose="vision")# 在消息中使用文件
message = client.messages.create(model="claude-opus-4-20250514",max_tokens=1024,messages=[{"role": "user","content": [{"type": "text", "text": "分析这个文档的内容"},{"type": "file", "file": {"id": uploaded_file.id}}]}]
)
错误处理
常见错误码
4xx 客户端错误
{"error": {"type": "invalid_request_error","message": "max_tokens is required"}
}
错误类型:
400 Bad Request
:请求格式错误401 Unauthorized
:API密钥无效403 Forbidden
:权限不足404 Not Found
:资源不存在422 Unprocessable Entity
:参数验证失败429 Too Many Requests
:请求频率限制
5xx 服务器错误
{"error": {"type": "api_error","message": "Internal server error"}
}
错误类型:
500 Internal Server Error
:服务器内部错误502 Bad Gateway
:网关错误503 Service Unavailable
:服务不可用
错误处理最佳实践
重试策略
import time
import randomdef api_call_with_retry(client, max_retries=3):for attempt in range(max_retries):try:response = client.messages.create(model="claude-sonnet-4-20250514",max_tokens=1024,messages=[{"role": "user", "content": "Hello"}])return responseexcept anthropic.RateLimitError:if attempt == max_retries - 1:raise# 指数退避wait_time = (2 ** attempt) + random.uniform(0, 1)time.sleep(wait_time)except anthropic.APIError as e:if attempt == max_retries - 1:raisetime.sleep(1)
异常处理
try:message = client.messages.create(model="claude-opus-4-20250514",max_tokens=1024,messages=[{"role": "user", "content": "Hello"}])
except anthropic.APIConnectionError:# 网络连接错误print("网络连接失败,请检查网络设置")
except anthropic.RateLimitError:# 频率限制print("请求频率过高,请稍后重试")
except anthropic.APIError as e:# 其他API错误print(f"API错误:{e}")
SDK使用
Python SDK
安装
pip install anthropic
基础配置
import anthropic# 方式1:直接传递API密钥
client = anthropic.Anthropic(api_key="your-api-key")# 方式2:使用环境变量
# export ANTHROPIC_API_KEY="your-api-key"
client = anthropic.Anthropic()# 方式3:自定义配置
client = anthropic.Anthropic(api_key="your-api-key",base_url="https://api.anthropic.com",max_retries=3,timeout=60.0
)
TypeScript/JavaScript SDK
安装
npm install @anthropic-ai/sdk
基础使用
import Anthropic from '@anthropic-ai/sdk';const anthropic = new Anthropic({apiKey: 'your-api-key'
});const message = await anthropic.messages.create({model: 'claude-opus-4-20250514',max_tokens: 1024,messages: [{ role: 'user', content: 'Hello, Claude' }]
});console.log(message.content);
高级配置
自定义客户端
import httpx
import anthropic# 自定义HTTP客户端
custom_client = httpx.Client(timeout=120.0,limits=httpx.Limits(max_connections=10)
)client = anthropic.Anthropic(api_key="your-api-key",http_client=custom_client
)
代理设置
client = anthropic.Anthropic(api_key="your-api-key",proxies={"https://": "https://proxy.example.com:8080"}
)
最佳实践
性能优化
- 合理设置
max_tokens
避免浪费 - 使用批处理API处理大量请求
- 实现智能缓存减少重复调用
- 监控API使用量和成本
安全建议
- 使用环境变量存储API密钥
- 实施请求频率限制
- 记录API使用日志
- 定期轮换API密钥
通过合理使用Anthropic API,开发者可以构建强大的AI应用,充分发挥Claude的智能能力。