名称: 临床试验数据库 描述: “通过API v2查询ClinicalTrials.gov。按条件、药物、位置、状态或阶段搜索试验。通过NCT ID检索试验详情,导出数据,用于临床研究和患者匹配。”
ClinicalTrials.gov 数据库
概述
ClinicalTrials.gov 是一个全球临床研究的综合注册库,由美国国家医学图书馆维护。访问API v2以搜索试验、检索详细研究信息、按各种标准筛选并导出数据进行分析。该API是公开的(无需认证),速率限制约为每分钟50个请求,支持JSON和CSV格式。
何时使用此技能
此技能应在处理临床试验数据的场景中使用,例如:
- 患者匹配 - 为特定条件或患者群体寻找招募中的试验
- 研究分析 - 分析临床试验趋势、结果或研究设计
- 药物/干预研究 - 识别测试特定药物或干预的试验
- 地理搜索 - 在特定位置或地区定位试验
- 赞助商/组织追踪 - 查找特定机构进行的试验
- 数据导出 - 提取临床试验数据以供进一步分析或报告
- 试验监控 - 跟踪特定试验的状态更新或结果
- 资格筛查 - 审查试验的纳入/排除标准
快速入门
基本搜索查询
使用辅助脚本搜索临床试验:
cd scientific-databases/clinicaltrials-database/scripts
python3 query_clinicaltrials.py
或直接使用Python的requests库:
import requests
url = "https://clinicaltrials.gov/api/v2/studies"
params = {
"query.cond": "乳腺癌",
"filter.overallStatus": "RECRUITING",
"pageSize": 10
}
response = requests.get(url, params=params)
data = response.json()
print(f"找到 {data['totalCount']} 个试验")
检索特定试验
使用NCT ID获取试验的详细信息:
import requests
nct_id = "NCT04852770"
url = f"https://clinicaltrials.gov/api/v2/studies/{nct_id}"
response = requests.get(url)
study = response.json()
# 访问特定模块
title = study['protocolSection']['identificationModule']['briefTitle']
status = study['protocolSection']['statusModule']['overallStatus']
核心功能
1. 按条件/疾病搜索
使用query.cond参数查找研究特定医疗条件或疾病的试验。
示例:查找招募中的糖尿病试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="2型糖尿病",
status="RECRUITING",
page_size=20,
sort="LastUpdatePostDate:desc"
)
print(f"找到 {results['totalCount']} 个招募中的糖尿病试验")
for study in results['studies']:
protocol = study['protocolSection']
nct_id = protocol['identificationModule']['nctId']
title = protocol['identificationModule']['briefTitle']
print(f"{nct_id}: {title}")
常见用例:
- 寻找罕见疾病的试验
- 识别共病条件的试验
- 跟踪特定诊断的试验可用性
2. 按干预/药物搜索
使用query.intr参数搜索测试特定干预、药物、设备或程序的试验。
示例:查找测试Pembrolizumab的第三阶段试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
intervention="Pembrolizumab",
status=["RECRUITING", "ACTIVE_NOT_RECRUITING"],
page_size=50
)
# 在结果中按阶段筛选
phase3_trials = [
study for study in results['studies']
if 'PHASE3' in study['protocolSection'].get('designModule', {}).get('phases', [])
]
常见用例:
- 药物开发跟踪
- 制药公司的竞争情报
- 临床医生的治疗选择研究
3. 地理搜索
使用query.locn参数在特定位置查找试验。
示例:查找纽约的癌症试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="癌症",
location="纽约",
status="RECRUITING",
page_size=100
)
# 提取位置详情
for study in results['studies']:
locations_module = study['protocolSection'].get('contactsLocationsModule', {})
locations = locations_module.get('locations', [])
for loc in locations:
if '纽约' in loc.get('city', ''):
print(f"{loc['facility']}: {loc['city']}, {loc.get('state', '')}")
常见用例:
- 患者转诊至本地试验
- 地理试验分布分析
- 新试验的站点选择
4. 按赞助商/组织搜索
使用query.spons参数查找特定组织进行的试验。
示例:查找由国家癌症研究所赞助的试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
sponsor="国家癌症研究所",
page_size=100
)
# 提取赞助商信息
for study in results['studies']:
sponsor_module = study['protocolSection']['sponsorCollaboratorsModule']
lead_sponsor = sponsor_module['leadSponsor']['name']
collaborators = sponsor_module.get('collaborators', [])
print(f"主要赞助商: {lead_sponsor}")
if collaborators:
print(f" 合作者: {', '.join([c['name'] for c in collaborators])}")
常见用例:
- 跟踪机构研究组合
- 分析资助组织优先级
- 识别合作机会
5. 按研究状态筛选
使用filter.overallStatus参数按招募或完成状态筛选试验。
有效状态值:
RECRUITING- 当前正在招募参与者NOT_YET_RECRUITING- 尚未开放招募ENROLLING_BY_INVITATION- 仅通过邀请招募ACTIVE_NOT_RECRUITING- 活跃但不再招募SUSPENDED- 暂时停止TERMINATED- 提前终止COMPLETED- 研究已结束WITHDRAWN- 在注册前撤回
示例:查找最近完成且有结果的试验
from scripts.query_clinicaltrials import search_studies
results = search_studies(
condition="阿尔茨海默病",
status="COMPLETED",
sort="LastUpdatePostDate:desc",
page_size=50
)
# 筛选有结果的试验
trials_with_results = [
study for study in results['studies']
if study.get('hasResults', False)
]
print(f"找到 {len(trials_with_results)} 个完成且有结果的试验")
6. 检索详细研究信息
获取特定试验的综合信息,包括资格标准、结果、联系人和位置。
示例:提取资格标准
from scripts.query_clinicaltrials import get_study_details
study = get_study_details("NCT04852770")
eligibility = study['protocolSection']['eligibilityModule']
print(f"合格年龄: {eligibility.get('minimumAge')} - {eligibility.get('maximumAge')}")
print(f"合格性别: {eligibility.get('sex')}")
print(f"
纳入标准:")
print(eligibility.get('eligibilityCriteria'))
示例:提取联系信息
from scripts.query_clinicaltrials import get_study_details
study = get_study_details("NCT04852770")
contacts_module = study['protocolSection']['contactsLocationsModule']
# 总体联系人
if 'centralContacts' in contacts_module:
for contact in contacts_module['centralContacts']:
print(f"联系人: {contact.get('name')}")
print(f"电话: {contact.get('phone')}")
print(f"邮箱: {contact.get('email')}")
# 研究位置
if 'locations' in contacts_module:
for location in contacts_module['locations']:
print(f"
设施: {location.get('facility')}")
print(f"城市: {location.get('city')}, {location.get('state')}")
if location.get('status'):
print(f"状态: {location['status']}")
7. 分页和批量数据检索
使用分页高效处理大型结果集。
示例:检索所有匹配的试验
from scripts.query_clinicaltrials import search_with_all_results
# 获取所有试验(自动处理分页)
all_trials = search_with_all_results(
condition="罕见疾病",
status="RECRUITING"
)
print(f"检索到 {len(all_trials)} 个总试验")
示例:手动分页控制
from scripts.query_clinicaltrials import search_studies
all_studies = []
page_token = None
max_pages = 10 # 限制以避免过多请求
for page in range(max_pages):
results = search_studies(
condition="癌症",
page_size=1000, # 最大页面大小
page_token=page_token
)
all_studies.extend(results['studies'])
# 检查下一页
page_token = results.get('pageToken')
if not page_token:
break
print(f"在 {page + 1} 页中检索到 {len(all_studies)} 个研究")
8. 数据导出为CSV
将试验数据导出为CSV格式,以便在电子表格软件或数据分析工具中使用。
示例:导出到CSV文件
from scripts.query_clinicaltrials import search_studies
# 请求CSV格式
results = search_studies(
condition="心脏病",
status="RECRUITING",
format="csv",
page_size=1000
)
# 保存到文件
with open("heart_disease_trials.csv", "w") as f:
f.write(results)
print("数据已导出到 heart_disease_trials.csv")
注意: CSV格式返回字符串而非JSON字典。
9. 提取和总结研究信息
提取关键信息以供快速概览或报告。
示例:创建试验摘要
from scripts.query_clinicaltrials import get_study_details, extract_study_summary
# 获取详情并提取摘要
study = get_study_details("NCT04852770")
summary = extract_study_summary(study)
print(f"NCT ID: {summary['nct_id']}")
print(f"标题: {summary['title']}")
print(f"状态: {summary['status']}")
print(f"阶段: {', '.join(summary['phase'])}")
print(f"注册人数: {summary['enrollment']}")
print(f"最后更新: {summary['last_update']}")
print(f"
简要总结:
{summary['brief_summary']}")
10. 组合查询策略
结合多个筛选器进行针对性搜索。
示例:多标准搜索
from scripts.query_clinicaltrials import search_studies
# 查找加利福尼亚州针对肺癌的免疫疗法第二阶段/第三阶段试验
results = search_studies(
condition="肺癌",
intervention="免疫疗法",
location="加利福尼亚",
status=["RECRUITING", "NOT_YET_RECRUITING"],
page_size=100
)
# 进一步按阶段筛选
phase2_3_trials = [
study for study in results['studies']
if any(phase in ['PHASE2', 'PHASE3']
for phase in study['protocolSection'].get('designModule', {}).get('phases', []))
]
print(f"找到 {len(phase2_3_trials)} 个第二阶段/第三阶段免疫疗法试验")
资源
scripts/query_clinicaltrials.py
提供常见查询模式的Python辅助函数:
search_studies()- 使用各种筛选器搜索试验get_study_details()- 检索特定试验的完整信息search_with_all_results()- 自动分页遍历所有结果extract_study_summary()- 提取快速概览的关键信息
直接运行脚本以查看示例用法:
python3 scripts/query_clinicaltrials.py
references/api_reference.md
详细API文档,包括:
- 完整端点规范
- 所有查询参数和有效值
- 响应数据结构和模块
- 常见用例代码示例
- 错误处理和最佳实践
- 数据标准(ISO 8601日期、CommonMark标记语言)
处理不熟悉的API功能或故障排除时加载此参考。
最佳实践
速率限制管理
API的速率限制约为每分钟50个请求。对于批量数据检索:
- 使用最大页面大小(1000)以减少请求
- 对速率限制错误(429状态)实现指数退避
- 在大规模数据收集时在请求之间添加延迟
import time
import requests
def search_with_rate_limit(params):
try:
response = requests.get("https://clinicaltrials.gov/api/v2/studies", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
print("速率受限。等待60秒...")
time.sleep(60)
return search_with_rate_limit(params) # 重试
raise
数据结构导航
API响应具有嵌套结构。常见信息的关键路径:
- NCT ID:
study['protocolSection']['identificationModule']['nctId'] - 标题:
study['protocolSection']['identificationModule']['briefTitle'] - 状态:
study['protocolSection']['statusModule']['overallStatus'] - 阶段:
study['protocolSection']['designModule']['phases'] - 资格:
study['protocolSection']['eligibilityModule'] - 位置:
study['protocolSection']['contactsLocationsModule']['locations'] - 干预:
study['protocolSection']['armsInterventionsModule']['interventions']
错误处理
始终为网络请求实现适当的错误处理:
import requests
try:
response = requests.get(url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP错误: {e.response.status_code}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
except ValueError as e:
print(f"JSON解码错误: {e}")
处理缺失数据
并非所有试验都有完整信息。始终检查字段是否存在:
# 使用.get()进行安全导航
phases = study['protocolSection'].get('designModule', {}).get('phases', [])
enrollment = study['protocolSection'].get('designModule', {}).get('enrollmentInfo', {}).get('count', 'N/A')
# 在访问前检查
if 'resultsSection' in study:
# 处理结果
pass
技术规范
- 基础URL:
https://clinicaltrials.gov/api/v2 - 认证: 不需要(公共API)
- 速率限制: 每分钟约50个请求(按IP)
- 响应格式: JSON(默认)、CSV
- 最大页面大小: 每个请求1000个研究
- 日期格式: ISO 8601
- 文本格式: 富文本字段使用CommonMark标记语言
- API版本: 2.0(2024年3月发布)
- API规范: OpenAPI 3.0
完整技术细节,请见references/api_reference.md。