fda-database

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

FDA Database Access

FDA数据库访问

Overview

概述

Access comprehensive FDA regulatory data through openFDA, the FDA's initiative to provide open APIs for public datasets. Query information about drugs, medical devices, foods, animal/veterinary products, and substances using Python with standardized interfaces.
Key capabilities:
  • Query adverse events for drugs, devices, foods, and veterinary products
  • Access product labeling, approvals, and regulatory submissions
  • Monitor recalls and enforcement actions
  • Look up National Drug Codes (NDC) and substance identifiers (UNII)
  • Analyze device classifications and clearances (510k, PMA)
  • Track drug shortages and supply issues
  • Research chemical structures and substance relationships
通过openFDA访问全面的FDA监管数据,openFDA是FDA推出的一项为公共数据集提供开放API的计划。使用Python通过标准化接口查询药品、医疗器械、食品、动物/兽药产品及相关物质的信息。
核心功能:
  • 查询药品、器械、食品及兽药产品的不良事件
  • 访问产品标签、审批信息及监管申报资料
  • 监控召回与执法行动
  • 查找国家药品代码(NDC)与物质标识(UNII)
  • 分析器械分类与许可情况(510k、PMA)
  • 追踪药品短缺与供应问题
  • 研究化学结构与物质关联

When to Use This Skill

适用场景

This skill should be used when working with:
  • Drug research: Safety profiles, adverse events, labeling, approvals, shortages
  • Medical device surveillance: Adverse events, recalls, 510(k) clearances, PMA approvals
  • Food safety: Recalls, allergen tracking, adverse events, dietary supplements
  • Veterinary medicine: Animal drug adverse events by species and breed
  • Chemical/substance data: UNII lookup, CAS number mapping, molecular structures
  • Regulatory analysis: Approval pathways, enforcement actions, compliance tracking
  • Pharmacovigilance: Post-market surveillance, safety signal detection
  • Scientific research: Drug interactions, comparative safety, epidemiological studies
本工具适用于以下工作场景:
  • 药品研究:安全性概况、不良事件、产品标签、审批信息、药品短缺
  • 医疗器械监测:不良事件、召回信息、510(k)许可、PMA审批
  • 食品安全:召回信息、过敏原追踪、不良事件、膳食补充剂
  • 兽医学:按物种和品种划分的动物药品不良事件
  • 化学/物质数据:UNII查询、CAS编号映射、分子结构
  • 监管分析:审批路径、执法行动、合规追踪
  • 药物警戒:上市后监测、安全信号检测
  • 科学研究:药物相互作用、对比安全性、流行病学研究

Quick Start

快速开始

1. Basic Setup

1. 基础设置

python
from scripts.fda_query import FDAQuery
python
from scripts.fda_query import FDAQuery

Initialize (API key optional but recommended)

Initialize (API key optional but recommended)

fda = FDAQuery(api_key="YOUR_API_KEY")
fda = FDAQuery(api_key="YOUR_API_KEY")

Query drug adverse events

Query drug adverse events

events = fda.query_drug_events("aspirin", limit=100)
events = fda.query_drug_events("aspirin", limit=100)

Get drug labeling

Get drug labeling

label = fda.query_drug_label("Lipitor", brand=True)
label = fda.query_drug_label("Lipitor", brand=True)

Search device recalls

Search device recalls

recalls = fda.query("device", "enforcement", search="classification:Class+I", limit=50)
undefined
recalls = fda.query("device", "enforcement", search="classification:Class+I", limit=50)
undefined

2. API Key Setup

2. API密钥设置

While the API works without a key, registering provides higher rate limits:
  • Without key: 240 requests/min, 1,000/day
  • With key: 240 requests/min, 120,000/day
Set as environment variable:
bash
export FDA_API_KEY="your_key_here"
虽然无需密钥即可使用API,但注册后可获得更高的调用限制:
  • 无密钥: 240次请求/分钟,1000次请求/天
  • 有密钥: 240次请求/分钟,120000次请求/天
设置为环境变量:
bash
export FDA_API_KEY="your_key_here"

3. Running Examples

3. 运行示例

bash
undefined
bash
undefined

Run comprehensive examples

Run comprehensive examples

python scripts/fda_examples.py
python scripts/fda_examples.py

This demonstrates:

This demonstrates:

- Drug safety profiles

- Drug safety profiles

- Device surveillance

- Device surveillance

- Food recall monitoring

- Food recall monitoring

- Substance lookup

- Substance lookup

- Comparative drug analysis

- Comparative drug analysis

- Veterinary drug analysis

- Veterinary drug analysis

undefined
undefined

FDA Database Categories

FDA数据库分类

Drugs

药品

Access 6 drug-related endpoints covering the full drug lifecycle from approval to post-market surveillance.
Endpoints:
  1. Adverse Events - Reports of side effects, errors, and therapeutic failures
  2. Product Labeling - Prescribing information, warnings, indications
  3. NDC Directory - National Drug Code product information
  4. Enforcement Reports - Drug recalls and safety actions
  5. Drugs@FDA - Historical approval data since 1939
  6. Drug Shortages - Current and resolved supply issues
Common use cases:
python
undefined
访问6个与药品相关的端点,覆盖从审批到上市后监测的完整药品生命周期。
端点:
  1. 不良事件 - 副作用、失误及治疗失败的报告
  2. 产品标签 - 处方信息、警告、适应症
  3. NDC目录 - 国家药品代码产品信息
  4. 执法报告 - 药品召回与安全行动
  5. Drugs@FDA - 1939年以来的历史审批数据
  6. 药品短缺 - 当前及已解决的供应问题
常见使用场景:
python
undefined

Safety signal detection

Safety signal detection

fda.count_by_field("drug", "event", search="patient.drug.medicinalproduct:metformin", field="patient.reaction.reactionmeddrapt")
fda.count_by_field("drug", "event", search="patient.drug.medicinalproduct:metformin", field="patient.reaction.reactionmeddrapt")

Get prescribing information

Get prescribing information

label = fda.query_drug_label("Keytruda", brand=True)
label = fda.query_drug_label("Keytruda", brand=True)

Check for recalls

Check for recalls

recalls = fda.query_drug_recalls(drug_name="metformin")
recalls = fda.query_drug_recalls(drug_name="metformin")

Monitor shortages

Monitor shortages

shortages = fda.query("drug", "drugshortages", search="status:Currently+in+Shortage")

**Reference:** See `references/drugs.md` for detailed documentation
shortages = fda.query("drug", "drugshortages", search="status:Currently+in+Shortage")

**参考文档:** 详见`references/drugs.md`获取详细文档

Devices

医疗器械

Access 9 device-related endpoints covering medical device safety, approvals, and registrations.
Endpoints:
  1. Adverse Events - Device malfunctions, injuries, deaths
  2. 510(k) Clearances - Premarket notifications
  3. Classification - Device categories and risk classes
  4. Enforcement Reports - Device recalls
  5. Recalls - Detailed recall information
  6. PMA - Premarket approval data for Class III devices
  7. Registrations & Listings - Manufacturing facility data
  8. UDI - Unique Device Identification database
  9. COVID-19 Serology - Antibody test performance data
Common use cases:
python
undefined
访问9个与医疗器械相关的端点,覆盖医疗器械安全、审批及注册信息。
端点:
  1. 不良事件 - 器械故障、伤害、死亡事件
  2. 510(k)许可 - 上市前通知
  3. 分类信息 - 器械类别与风险等级
  4. 执法报告 - 器械召回
  5. 召回信息 - 详细召回数据
  6. PMA - III类器械的上市前审批数据
  7. 注册与备案 - 生产设施数据
  8. UDI - 唯一器械标识数据库
  9. COVID-19血清学 - 抗体检测性能数据
常见使用场景:
python
undefined

Monitor device safety

Monitor device safety

events = fda.query_device_events("pacemaker", limit=100)
events = fda.query_device_events("pacemaker", limit=100)

Look up device classification

Look up device classification

classification = fda.query_device_classification("DQY")
classification = fda.query_device_classification("DQY")

Find 510(k) clearances

Find 510(k) clearances

clearances = fda.query_device_510k(applicant="Medtronic")
clearances = fda.query_device_510k(applicant="Medtronic")

Search by UDI

Search by UDI

device_info = fda.query("device", "udi", search="identifiers.id:00884838003019")

**Reference:** See `references/devices.md` for detailed documentation
device_info = fda.query("device", "udi", search="identifiers.id:00884838003019")

**参考文档:** 详见`references/devices.md`获取详细文档

Foods

食品

Access 2 food-related endpoints for safety monitoring and recalls.
Endpoints:
  1. Adverse Events - Food, dietary supplement, and cosmetic events
  2. Enforcement Reports - Food product recalls
Common use cases:
python
undefined
访问2个与食品相关的端点,用于安全监测与召回信息查询。
端点:
  1. 不良事件 - 食品、膳食补充剂及化妆品事件
  2. 执法报告 - 食品召回
常见使用场景:
python
undefined

Monitor allergen recalls

Monitor allergen recalls

recalls = fda.query_food_recalls(reason="undeclared peanut")
recalls = fda.query_food_recalls(reason="undeclared peanut")

Track dietary supplement events

Track dietary supplement events

events = fda.query_food_events( industry="Dietary Supplements")
events = fda.query_food_events( industry="Dietary Supplements")

Find contamination recalls

Find contamination recalls

listeria = fda.query_food_recalls( reason="listeria", classification="I")

**Reference:** See `references/foods.md` for detailed documentation
listeria = fda.query_food_recalls( reason="listeria", classification="I")

**参考文档:** 详见`references/foods.md`获取详细文档

Animal & Veterinary

动物与兽药

Access veterinary drug adverse event data with species-specific information.
Endpoint:
  1. Adverse Events - Animal drug side effects by species, breed, and product
Common use cases:
python
undefined
访问带有物种特定信息的兽药不良事件数据。
端点:
  1. 不良事件 - 按物种、品种及产品划分的动物药品副作用
常见使用场景:
python
undefined

Species-specific events

Species-specific events

dog_events = fda.query_animal_events( species="Dog", drug_name="flea collar")
dog_events = fda.query_animal_events( species="Dog", drug_name="flea collar")

Breed predisposition analysis

Breed predisposition analysis

breed_query = fda.query("animalandveterinary", "event", search="reaction.veddra_term_name:seizure+AND+" "animal.breed.breed_component:Labrador")

**Reference:** See `references/animal_veterinary.md` for detailed documentation
breed_query = fda.query("animalandveterinary", "event", search="reaction.veddra_term_name:seizure+AND+" "animal.breed.breed_component:Labrador")

**参考文档:** 详见`references/animal_veterinary.md`获取详细文档

Substances & Other

物质及其他

Access molecular-level substance data with UNII codes, chemical structures, and relationships.
Endpoints:
  1. Substance Data - UNII, CAS, chemical structures, relationships
  2. NSDE - Historical substance data (legacy)
Common use cases:
python
undefined
访问分子层面的物质数据,包括UNII代码、化学结构及关联信息。
端点:
  1. 物质数据 - UNII、CAS、化学结构、关联关系
  2. NSDE - 历史物质数据(遗留系统)
常见使用场景:
python
undefined

UNII to CAS mapping

UNII to CAS mapping

substance = fda.query_substance_by_unii("R16CO5Y76E")
substance = fda.query_substance_by_unii("R16CO5Y76E")

Search by name

Search by name

results = fda.query_substance_by_name("acetaminophen")
results = fda.query_substance_by_name("acetaminophen")

Get chemical structure

Get chemical structure

structure = fda.query("other", "substance", search="names.name:ibuprofen+AND+substanceClass:chemical")

**Reference:** See `references/other.md` for detailed documentation
structure = fda.query("other", "substance", search="names.name:ibuprofen+AND+substanceClass:chemical")

**参考文档:** 详见`references/other.md`获取详细文档

Common Query Patterns

常见查询模式

Pattern 1: Safety Profile Analysis

模式1:安全性概况分析

Create comprehensive safety profiles combining multiple data sources:
python
def drug_safety_profile(fda, drug_name):
    """Generate complete safety profile."""

    # 1. Total adverse events
    events = fda.query_drug_events(drug_name, limit=1)
    total = events["meta"]["results"]["total"]

    # 2. Most common reactions
    reactions = fda.count_by_field(
        "drug", "event",
        search=f"patient.drug.medicinalproduct:*{drug_name}*",
        field="patient.reaction.reactionmeddrapt",
        exact=True
    )

    # 3. Serious events
    serious = fda.query("drug", "event",
        search=f"patient.drug.medicinalproduct:*{drug_name}*+AND+serious:1",
        limit=1)

    # 4. Recent recalls
    recalls = fda.query_drug_recalls(drug_name=drug_name)

    return {
        "total_events": total,
        "top_reactions": reactions["results"][:10],
        "serious_events": serious["meta"]["results"]["total"],
        "recalls": recalls["results"]
    }
结合多个数据源创建全面的安全性概况:
python
def drug_safety_profile(fda, drug_name):
    """Generate complete safety profile."""

    # 1. Total adverse events
    events = fda.query_drug_events(drug_name, limit=1)
    total = events["meta"]["results"]["total"]

    # 2. Most common reactions
    reactions = fda.count_by_field(
        "drug", "event",
        search=f"patient.drug.medicinalproduct:*{drug_name}*",
        field="patient.reaction.reactionmeddrapt",
        exact=True
    )

    # 3. Serious events
    serious = fda.query("drug", "event",
        search=f"patient.drug.medicinalproduct:*{drug_name}*+AND+serious:1",
        limit=1)

    # 4. Recent recalls
    recalls = fda.query_drug_recalls(drug_name=drug_name)

    return {
        "total_events": total,
        "top_reactions": reactions["results"][:10],
        "serious_events": serious["meta"]["results"]["total"],
        "recalls": recalls["results"]
    }

Pattern 2: Temporal Trend Analysis

模式2:时间趋势分析

Analyze trends over time using date ranges:
python
from datetime import datetime, timedelta

def get_monthly_trends(fda, drug_name, months=12):
    """Get monthly adverse event trends."""
    trends = []

    for i in range(months):
        end = datetime.now() - timedelta(days=30*i)
        start = end - timedelta(days=30)

        date_range = f"[{start.strftime('%Y%m%d')}+TO+{end.strftime('%Y%m%d')}]"
        search = f"patient.drug.medicinalproduct:*{drug_name}*+AND+receivedate:{date_range}"

        result = fda.query("drug", "event", search=search, limit=1)
        count = result["meta"]["results"]["total"] if "meta" in result else 0

        trends.append({
            "month": start.strftime("%Y-%m"),
            "events": count
        })

    return trends
使用日期范围分析随时间变化的趋势:
python
from datetime import datetime, timedelta

def get_monthly_trends(fda, drug_name, months=12):
    """Get monthly adverse event trends."""
    trends = []

    for i in range(months):
        end = datetime.now() - timedelta(days=30*i)
        start = end - timedelta(days=30)

        date_range = f"[{start.strftime('%Y%m%d')}+TO+{end.strftime('%Y%m%d')}]"
        search = f"patient.drug.medicinalproduct:*{drug_name}*+AND+receivedate:{date_range}"

        result = fda.query("drug", "event", search=search, limit=1)
        count = result["meta"]["results"]["total"] if "meta" in result else 0

        trends.append({
            "month": start.strftime("%Y-%m"),
            "events": count
        })

    return trends

Pattern 3: Comparative Analysis

模式3:对比分析

Compare multiple products side-by-side:
python
def compare_drugs(fda, drug_list):
    """Compare safety profiles of multiple drugs."""
    comparison = {}

    for drug in drug_list:
        # Total events
        events = fda.query_drug_events(drug, limit=1)
        total = events["meta"]["results"]["total"] if "meta" in events else 0

        # Serious events
        serious = fda.query("drug", "event",
            search=f"patient.drug.medicinalproduct:*{drug}*+AND+serious:1",
            limit=1)
        serious_count = serious["meta"]["results"]["total"] if "meta" in serious else 0

        comparison[drug] = {
            "total_events": total,
            "serious_events": serious_count,
            "serious_rate": (serious_count/total*100) if total > 0 else 0
        }

    return comparison
并列对比多个产品:
python
def compare_drugs(fda, drug_list):
    """Compare safety profiles of multiple drugs."""
    comparison = {}

    for drug in drug_list:
        # Total events
        events = fda.query_drug_events(drug, limit=1)
        total = events["meta"]["results"]["total"] if "meta" in events else 0

        # Serious events
        serious = fda.query("drug", "event",
            search=f"patient.drug.medicinalproduct:*{drug}*+AND+serious:1",
            limit=1)
        serious_count = serious["meta"]["results"]["total"] if "meta" in serious else 0

        comparison[drug] = {
            "total_events": total,
            "serious_events": serious_count,
            "serious_rate": (serious_count/total*100) if total > 0 else 0
        }

    return comparison

Pattern 4: Cross-Database Lookup

模式4:跨数据库查询

Link data across multiple endpoints:
python
def comprehensive_device_lookup(fda, device_name):
    """Look up device across all relevant databases."""

    return {
        "adverse_events": fda.query_device_events(device_name, limit=10),
        "510k_clearances": fda.query_device_510k(device_name=device_name),
        "recalls": fda.query("device", "enforcement",
                           search=f"product_description:*{device_name}*"),
        "udi_info": fda.query("device", "udi",
                            search=f"brand_name:*{device_name}*")
    }
跨多个端点关联数据:
python
def comprehensive_device_lookup(fda, device_name):
    """Look up device across all relevant databases."""

    return {
        "adverse_events": fda.query_device_events(device_name, limit=10),
        "510k_clearances": fda.query_device_510k(device_name=device_name),
        "recalls": fda.query("device", "enforcement",
                           search=f"product_description:*{device_name}*"),
        "udi_info": fda.query("device", "udi",
                            search=f"brand_name:*{device_name}*")
    }

Working with Results

结果处理

Response Structure

响应结构

All API responses follow this structure:
python
{
    "meta": {
        "disclaimer": "...",
        "results": {
            "skip": 0,
            "limit": 100,
            "total": 15234
        }
    },
    "results": [
        # Array of result objects
    ]
}
所有API响应遵循以下结构:
python
{
    "meta": {
        "disclaimer": "...",
        "results": {
            "skip": 0,
            "limit": 100,
            "total": 15234
        }
    },
    "results": [
        # Array of result objects
    ]
}

Error Handling

错误处理

Always handle potential errors:
python
result = fda.query_drug_events("aspirin", limit=10)

if "error" in result:
    print(f"Error: {result['error']}")
elif "results" not in result or len(result["results"]) == 0:
    print("No results found")
else:
    # Process results
    for event in result["results"]:
        # Handle event data
        pass
始终处理潜在错误:
python
result = fda.query_drug_events("aspirin", limit=10)

if "error" in result:
    print(f"Error: {result['error']}")
elif "results" not in result or len(result["results"]) == 0:
    print("No results found")
else:
    # Process results
    for event in result["results"]:
        # Handle event data
        pass

Pagination

分页

For large result sets, use pagination:
python
undefined
对于大型结果集,使用分页:
python
undefined

Automatic pagination

Automatic pagination

all_results = fda.query_all( "drug", "event", search="patient.drug.medicinalproduct:aspirin", max_results=5000 )
all_results = fda.query_all( "drug", "event", search="patient.drug.medicinalproduct:aspirin", max_results=5000 )

Manual pagination

Manual pagination

for skip in range(0, 1000, 100): batch = fda.query("drug", "event", search="...", limit=100, skip=skip) # Process batch
undefined
for skip in range(0, 1000, 100): batch = fda.query("drug", "event", search="...", limit=100, skip=skip) # Process batch
undefined

Best Practices

最佳实践

1. Use Specific Searches

1. 使用精准搜索

DO:
python
undefined
推荐:
python
undefined

Specific field search

Specific field search

search="patient.drug.medicinalproduct:aspirin"

**DON'T:**
```python
search="patient.drug.medicinalproduct:aspirin"

**不推荐:**
```python

Overly broad wildcard

Overly broad wildcard

search="aspirin"
undefined
search="aspirin"
undefined

2. Implement Rate Limiting

2. 实现调用限制

The
FDAQuery
class handles rate limiting automatically, but be aware of limits:
  • 240 requests per minute
  • 120,000 requests per day (with API key)
FDAQuery
类会自动处理调用限制,但请注意以下限制:
  • 240次请求/分钟
  • 120000次请求/天(使用API密钥)

3. Cache Frequently Accessed Data

3. 缓存频繁访问的数据

The
FDAQuery
class includes built-in caching (enabled by default):
python
undefined
FDAQuery
类包含内置缓存(默认启用):
python
undefined

Caching is automatic

Caching is automatic

fda = FDAQuery(api_key=api_key, use_cache=True, cache_ttl=3600)
undefined
fda = FDAQuery(api_key=api_key, use_cache=True, cache_ttl=3600)
undefined

4. Use Exact Matching for Counting

4. 计数时使用精确匹配

When counting/aggregating, use
.exact
suffix:
python
undefined
进行计数/聚合时,使用
.exact
后缀:
python
undefined

Count exact phrases

Count exact phrases

fda.count_by_field("drug", "event", search="...", field="patient.reaction.reactionmeddrapt", exact=True) # Adds .exact automatically
undefined
fda.count_by_field("drug", "event", search="...", field="patient.reaction.reactionmeddrapt", exact=True) # Adds .exact automatically
undefined

5. Validate Input Data

5. 验证输入数据

Clean and validate search terms:
python
def clean_drug_name(name):
    """Clean drug name for query."""
    return name.strip().replace('"', '\\"')

drug_name = clean_drug_name(user_input)
清理并验证搜索词:
python
def clean_drug_name(name):
    """Clean drug name for query."""
    return name.strip().replace('"', '\\"')

drug_name = clean_drug_name(user_input)

API Reference

API参考

For detailed information about:
  • Authentication and rate limits → See
    references/api_basics.md
  • Drug databases → See
    references/drugs.md
  • Device databases → See
    references/devices.md
  • Food databases → See
    references/foods.md
  • Animal/veterinary databases → See
    references/animal_veterinary.md
  • Substance databases → See
    references/other.md
如需以下详细信息:
  • 认证与调用限制 → 详见
    references/api_basics.md
  • 药品数据库 → 详见
    references/drugs.md
  • 医疗器械数据库 → 详见
    references/devices.md
  • 食品数据库 → 详见
    references/foods.md
  • 动物/兽药数据库 → 详见
    references/animal_veterinary.md
  • 物质数据库 → 详见
    references/other.md

Scripts

脚本说明

scripts/fda_query.py

scripts/fda_query.py

Main query module with
FDAQuery
class providing:
  • Unified interface to all FDA endpoints
  • Automatic rate limiting and caching
  • Error handling and retry logic
  • Common query patterns
主要查询模块,包含
FDAQuery
类,提供:
  • 所有FDA端点的统一接口
  • 自动调用限制与缓存
  • 错误处理与重试逻辑
  • 常见查询模式

scripts/fda_examples.py

scripts/fda_examples.py

Comprehensive examples demonstrating:
  • Drug safety profile analysis
  • Device surveillance monitoring
  • Food recall tracking
  • Substance lookup
  • Comparative drug analysis
  • Veterinary drug analysis
Run examples:
bash
python scripts/fda_examples.py
综合示例,展示:
  • 药品安全性概况分析
  • 医疗器械监测
  • 食品召回追踪
  • 物质查询
  • 药品对比分析
  • 兽药分析
运行示例:
bash
python scripts/fda_examples.py

Additional Resources

额外资源

Support and Troubleshooting

支持与故障排除

Common Issues

常见问题

Issue: Rate limit exceeded
  • Solution: Use API key, implement delays, or reduce request frequency
Issue: No results found
  • Solution: Try broader search terms, check spelling, use wildcards
Issue: Invalid query syntax
  • Solution: Review query syntax in
    references/api_basics.md
Issue: Missing fields in results
  • Solution: Not all records contain all fields; always check field existence
问题: 调用限制超出
  • 解决方案: 使用API密钥,实现延迟,或降低请求频率
问题: 未找到结果
  • 解决方案: 尝试更宽泛的搜索词,检查拼写,使用通配符
问题: 查询语法无效
  • 解决方案: 查看
    references/api_basics.md
    中的查询语法
问题: 结果中缺少字段
  • 解决方案: 并非所有记录都包含所有字段;始终检查字段是否存在

Getting Help

获取帮助