[ PROMPT_NODE_26578 ]
api_basics
[ SKILL_DOCUMENTATION ]
# OpenFDA API 基础知识
本参考指南提供了有关使用 openFDA API 的全面信息,包括身份验证、速率限制、查询语法和最佳实践。
## 入门
### 基础 URL
所有 openFDA API 端点遵循此结构:
https://api.fda.gov/{category}/{endpoint}.json
示例:
- `https://api.fda.gov/drug/event.json`
- `https://api.fda.gov/device/510k.json`
- `https://api.fda.gov/food/enforcement.json`
### 必须使用 HTTPS
**所有请求必须使用 HTTPS**。HTTP 请求不被接受且会失败。
## 身份验证
### API 密钥注册
虽然 openFDA 可以在没有 API 密钥的情况下使用,但强烈建议注册免费的 API 密钥以获得更高的速率限制。
**注册**:访问 https://open.fda.gov/apis/authentication/ 进行注册
**API 密钥的好处**:
- 更高的速率限制(240 次请求/分钟,120,000 次请求/天)
- 更适合生产环境应用
- 无额外费用
### 使用 API 密钥
通过以下两种方法之一在请求中包含您的 API 密钥:
**方法 1:查询参数(推荐)**
python
import requests
api_key = "YOUR_API_KEY_HERE"
url = "https://api.fda.gov/drug/event.json"
params = {
"api_key": api_key,
"search": "patient.drug.medicinalproduct:aspirin",
"limit": 10
}
response = requests.get(url, params=params)
**方法 2:基本身份验证**
python
import requests
api_key = "YOUR_API_KEY_HERE"
url = "https://api.fda.gov/drug/event.json"
params = {
"search": "patient.drug.medicinalproduct:aspirin",
"limit": 10
}
response = requests.get(url, params=params, auth=(api_key, ''))
## 速率限制
### 当前限制
| 状态 | 每分钟请求数 | 每天请求数 |
|--------|-------------------|------------------|
| **无 API 密钥** | 每个 IP 地址 240 次 | 每个 IP 地址 1,000 次 |
| **有 API 密钥** | 每个密钥 240 次 | 每个密钥 120,000 次 |
### 速率限制响应头
API 在响应头中返回速率限制信息:
python
response = requests.get(url, params=params)
print(f"Rate limit: {response.headers.get('X-RateLimit-Limit')}")
print(f"Remaining: {response.headers.get('X-RateLimit-Remaining')}")
print(f"Reset time: {response.headers.get('X-RateLimit-Reset')}")
### 处理速率限制
当您超过速率限制时,API 会返回:
- **状态码**:`429 Too Many Requests`
- **错误消息**:指示已超过速率限制
**最佳实践**:实现指数退避策略:
python
import requests
import time
def query_with_rate_lim