
Fda Database
- 38 installs
- 16 repo stars
- Updated November 20, 2025
- jackspace/claudeskillz
Query the openFDA API for drugs, devices, adverse events, recalls, and regulatory submissions (510k, PMA) plus NDC and UNII lookups.
About
Provides Python access to openFDA, the FDA's open data APIs for drugs, devices, foods, and substances. A developer uses it for adverse-event queries, recall monitoring, labeling/approvals, and regulatory data analysis.
- Query adverse events, recalls, labeling, and device clearances
- NDC and UNII lookups plus drug shortage tracking
Fda Database by the numbers
- 38 all-time installs (skills.sh)
- Ranked #1,015 of 2,065 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/jackspace/claudeskillz --skill fda-databaseAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 38 |
|---|---|
| repo stars | ★ 16 |
| Last updated | November 20, 2025 |
| Repository | jackspace/claudeskillz ↗ |
What it does
Query the openFDA API for drugs, devices, adverse events, recalls, and regulatory submissions (510k, PMA) plus NDC and UNII lookups.
Files
FDA Database Access
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
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
Quick Start
1. Basic Setup
from scripts.fda_query import FDAQuery
# Initialize (API key optional but recommended)
fda = FDAQuery(api_key="YOUR_API_KEY")
# Query drug adverse events
events = fda.query_drug_events("aspirin", limit=100)
# Get drug labeling
label = fda.query_drug_label("Lipitor", brand=True)
# Search device recalls
recalls = fda.query("device", "enforcement",
search="classification:Class+I",
limit=50)2. API Key Setup
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
Register at: https://open.fda.gov/apis/authentication/
Set as environment variable:
export FDA_API_KEY="your_key_here"3. Running Examples
# Run comprehensive examples
python scripts/fda_examples.py
# This demonstrates:
# - Drug safety profiles
# - Device surveillance
# - Food recall monitoring
# - Substance lookup
# - Comparative drug analysis
# - Veterinary drug analysisFDA Database Categories
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:
# Safety signal detection
fda.count_by_field("drug", "event",
search="patient.drug.medicinalproduct:metformin",
field="patient.reaction.reactionmeddrapt")
# Get prescribing information
label = fda.query_drug_label("Keytruda", brand=True)
# Check for recalls
recalls = fda.query_drug_recalls(drug_name="metformin")
# Monitor shortages
shortages = fda.query("drug", "drugshortages",
search="status:Currently+in+Shortage")Reference: See references/drugs.md for detailed documentation
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:
# Monitor device safety
events = fda.query_device_events("pacemaker", limit=100)
# Look up device classification
classification = fda.query_device_classification("DQY")
# Find 510(k) clearances
clearances = fda.query_device_510k(applicant="Medtronic")
# Search by UDI
device_info = fda.query("device", "udi",
search="identifiers.id:00884838003019")Reference: See references/devices.md for detailed documentation
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:
# Monitor allergen recalls
recalls = fda.query_food_recalls(reason="undeclared peanut")
# Track dietary supplement events
events = fda.query_food_events(
industry="Dietary Supplements")
# Find contamination recalls
listeria = fda.query_food_recalls(
reason="listeria",
classification="I")Reference: See references/foods.md for detailed documentation
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:
# Species-specific events
dog_events = fda.query_animal_events(
species="Dog",
drug_name="flea collar")
# 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
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:
# UNII to CAS mapping
substance = fda.query_substance_by_unii("R16CO5Y76E")
# Search by name
results = fda.query_substance_by_name("acetaminophen")
# Get chemical structure
structure = fda.query("other", "substance",
search="names.name:ibuprofen+AND+substanceClass:chemical")Reference: See references/other.md for detailed documentation
Common Query Patterns
Pattern 1: Safety Profile Analysis
Create comprehensive safety profiles combining multiple data sources:
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
Analyze trends over time using date ranges:
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 trendsPattern 3: Comparative Analysis
Compare multiple products side-by-side:
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 comparisonPattern 4: Cross-Database Lookup
Link data across multiple endpoints:
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:
{
"meta": {
"disclaimer": "...",
"results": {
"skip": 0,
"limit": 100,
"total": 15234
}
},
"results": [
# Array of result objects
]
}Error Handling
Always handle potential errors:
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
passPagination
For large result sets, use pagination:
# Automatic pagination
all_results = fda.query_all(
"drug", "event",
search="patient.drug.medicinalproduct:aspirin",
max_results=5000
)
# Manual pagination
for skip in range(0, 1000, 100):
batch = fda.query("drug", "event",
search="...",
limit=100,
skip=skip)
# Process batchBest Practices
1. Use Specific Searches
DO:
# Specific field search
search="patient.drug.medicinalproduct:aspirin"DON'T:
# Overly broad wildcard
search="*aspirin*"2. Implement Rate Limiting
The FDAQuery class handles rate limiting automatically, but be aware of limits:
- 240 requests per minute
- 120,000 requests per day (with API key)
3. Cache Frequently Accessed Data
The FDAQuery class includes built-in caching (enabled by default):
# Caching is automatic
fda = FDAQuery(api_key=api_key, use_cache=True, cache_ttl=3600)4. Use Exact Matching for Counting
When counting/aggregating, use .exact suffix:
# Count exact phrases
fda.count_by_field("drug", "event",
search="...",
field="patient.reaction.reactionmeddrapt",
exact=True) # Adds .exact automatically5. Validate Input Data
Clean and validate search terms:
def clean_drug_name(name):
"""Clean drug name for query."""
return name.strip().replace('"', '\\"')
drug_name = clean_drug_name(user_input)API Reference
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
Scripts
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
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:
python scripts/fda_examples.pyAdditional Resources
- openFDA Homepage: https://open.fda.gov/
- API Documentation: https://open.fda.gov/apis/
- Interactive API Explorer: https://open.fda.gov/apis/try-the-api/
- GitHub Repository: https://github.com/FDA/openfda
- Terms of Service: https://open.fda.gov/terms/
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
Getting Help
- GitHub Issues: https://github.com/FDA/openfda/issues
- Email: open-fda@fda.hhs.gov
{
"description": "\"Query openFDA API for drugs, devices, adverse events, recalls, regulatory submissions (510k, PMA), substance identification (UNII), for FDA regulatory data analysis and safety research.\"",
"references": {
"files": [
"references/animal_veterinary.md",
"references/api_basics.md",
"references/devices.md",
"references/drugs.md",
"references/foods.md",
"references/other.md"
]
},
"content": "### 1. Basic Setup\r\n\r\n```python\r\nfrom scripts.fda_query import FDAQuery\r\n\r\nfda = FDAQuery(api_key=\"YOUR_API_KEY\")\r\n\r\nevents = fda.query_drug_events(\"aspirin\", limit=100)\r\n\r\nlabel = fda.query_drug_label(\"Lipitor\", brand=True)\r\n\r\nrecalls = fda.query(\"device\", \"enforcement\",\r\n search=\"classification:Class+I\",\r\n limit=50)\r\n```\r\n\r\n### 2. API Key Setup\r\n\r\nWhile the API works without a key, registering provides higher rate limits:\r\n- **Without key**: 240 requests/min, 1,000/day\r\n- **With key**: 240 requests/min, 120,000/day\r\n\r\nRegister at: https://open.fda.gov/apis/authentication/\r\n\r\nSet as environment variable:\r\n```bash\r\nexport FDA_API_KEY=\"your_key_here\"\r\n```\r\n\r\n### 3. Running Examples\r\n\r\n```bash\r\npython scripts/fda_examples.py\r\n\r\n\r\n### Drugs\r\n\r\nAccess 6 drug-related endpoints covering the full drug lifecycle from approval to post-market surveillance.\r\n\r\n**Endpoints:**\r\n1. **Adverse Events** - Reports of side effects, errors, and therapeutic failures\r\n2. **Product Labeling** - Prescribing information, warnings, indications\r\n3. **NDC Directory** - National Drug Code product information\r\n4. **Enforcement Reports** - Drug recalls and safety actions\r\n5. **Drugs@FDA** - Historical approval data since 1939\r\n6. **Drug Shortages** - Current and resolved supply issues\r\n\r\n**Common use cases:**\r\n```python\r\nfda.count_by_field(\"drug\", \"event\",\r\n search=\"patient.drug.medicinalproduct:metformin\",\r\n field=\"patient.reaction.reactionmeddrapt\")\r\n\r\nlabel = fda.query_drug_label(\"Keytruda\", brand=True)\r\n\r\nrecalls = fda.query_drug_recalls(drug_name=\"metformin\")\r\n\r\nshortages = fda.query(\"drug\", \"drugshortages\",\r\n search=\"status:Currently+in+Shortage\")\r\n```\r\n\r\n**Reference:** See `references/drugs.md` for detailed documentation\r\n\r\n### Devices\r\n\r\nAccess 9 device-related endpoints covering medical device safety, approvals, and registrations.\r\n\r\n**Endpoints:**\r\n1. **Adverse Events** - Device malfunctions, injuries, deaths\r\n2. **510(k) Clearances** - Premarket notifications\r\n3. **Classification** - Device categories and risk classes\r\n4. **Enforcement Reports** - Device recalls\r\n5. **Recalls** - Detailed recall information\r\n6. **PMA** - Premarket approval data for Class III devices\r\n7. **Registrations & Listings** - Manufacturing facility data\r\n8. **UDI** - Unique Device Identification database\r\n9. **COVID-19 Serology** - Antibody test performance data\r\n\r\n**Common use cases:**\r\n```python\r\nevents = fda.query_device_events(\"pacemaker\", limit=100)\r\n\r\nclassification = fda.query_device_classification(\"DQY\")\r\n\r\nclearances = fda.query_device_510k(applicant=\"Medtronic\")\r\n\r\ndevice_info = fda.query(\"device\", \"udi\",\r\n search=\"identifiers.id:00884838003019\")\r\n```\r\n\r\n**Reference:** See `references/devices.md` for detailed documentation\r\n\r\n### Foods\r\n\r\nAccess 2 food-related endpoints for safety monitoring and recalls.\r\n\r\n**Endpoints:**\r\n1. **Adverse Events** - Food, dietary supplement, and cosmetic events\r\n2. **Enforcement Reports** - Food product recalls\r\n\r\n**Common use cases:**\r\n```python\r\nrecalls = fda.query_food_recalls(reason=\"undeclared peanut\")\r\n\r\nevents = fda.query_food_events(\r\n industry=\"Dietary Supplements\")\r\n\r\nlisteria = fda.query_food_recalls(\r\n reason=\"listeria\",\r\n classification=\"I\")\r\n```\r\n\r\n**Reference:** See `references/foods.md` for detailed documentation\r\n\r\n### Animal & Veterinary\r\n\r\nAccess veterinary drug adverse event data with species-specific information.\r\n\r\n**Endpoint:**\r\n1. **Adverse Events** - Animal drug side effects by species, breed, and product\r\n\r\n**Common use cases:**\r\n```python\r\ndog_events = fda.query_animal_events(\r\n species=\"Dog\",\r\n drug_name=\"flea collar\")\r\n\r\nbreed_query = fda.query(\"animalandveterinary\", \"event\",\r\n search=\"reaction.veddra_term_name:*seizure*+AND+\"\r\n \"animal.breed.breed_component:*Labrador*\")\r\n```\r\n\r\n**Reference:** See `references/animal_veterinary.md` for detailed documentation\r\n\r\n### Substances & Other\r\n\r\nAccess molecular-level substance data with UNII codes, chemical structures, and relationships.\r\n\r\n**Endpoints:**\r\n1. **Substance Data** - UNII, CAS, chemical structures, relationships\r\n2. **NSDE** - Historical substance data (legacy)\r\n\r\n**Common use cases:**\r\n```python\r\nsubstance = fda.query_substance_by_unii(\"R16CO5Y76E\")\r\n\r\nresults = fda.query_substance_by_name(\"acetaminophen\")\r\n\r\n\r\n### Response Structure\r\n\r\nAll API responses follow this structure:\r\n\r\n```python\r\n{\r\n \"meta\": {\r\n \"disclaimer\": \"...\",\r\n \"results\": {\r\n \"skip\": 0,\r\n \"limit\": 100,\r\n \"total\": 15234\r\n }\r\n },\r\n \"results\": [\r\n # Array of result objects\r\n ]\r\n}\r\n```\r\n\r\n### Error Handling\r\n\r\nAlways handle potential errors:\r\n\r\n```python\r\nresult = fda.query_drug_events(\"aspirin\", limit=10)\r\n\r\nif \"error\" in result:\r\n print(f\"Error: {result['error']}\")\r\nelif \"results\" not in result or len(result[\"results\"]) == 0:\r\n print(\"No results found\")\r\nelse:\r\n # Process results\r\n for event in result[\"results\"]:\r\n # Handle event data\r\n pass\r\n```\r\n\r\n### Pagination\r\n\r\nFor large result sets, use pagination:\r\n\r\n```python\r\nall_results = fda.query_all(\r\n \"drug\", \"event\",\r\n search=\"patient.drug.medicinalproduct:aspirin\",\r\n max_results=5000\r\n)\r\n\r\n\r\n### 1. Use Specific Searches\r\n\r\n**DO:**\r\n```python\r\nsearch=\"patient.drug.medicinalproduct:aspirin\"\r\n```\r\n\r\n**DON'T:**\r\n```python\r\nsearch=\"*aspirin*\"\r\n```\r\n\r\n### 2. Implement Rate Limiting\r\n\r\nThe `FDAQuery` class handles rate limiting automatically, but be aware of limits:\r\n- 240 requests per minute\r\n- 120,000 requests per day (with API key)\r\n\r\n### 3. Cache Frequently Accessed Data\r\n\r\nThe `FDAQuery` class includes built-in caching (enabled by default):\r\n\r\n```python\r\nfda = FDAQuery(api_key=api_key, use_cache=True, cache_ttl=3600)\r\n```\r\n\r\n### 4. Use Exact Matching for Counting\r\n\r\nWhen counting/aggregating, use `.exact` suffix:\r\n\r\n```python",
"name": "fda-database",
"id": "scientific-db-fda-database",
"sections": {
"Quick Start": "```",
"Best Practices": "fda.count_by_field(\"drug\", \"event\",\r\n search=\"...\",\r\n field=\"patient.reaction.reactionmeddrapt\",\r\n exact=True) # Adds .exact automatically\r\n```\r\n\r\n### 5. Validate Input Data\r\n\r\nClean and validate search terms:\r\n\r\n```python\r\ndef clean_drug_name(name):\r\n \"\"\"Clean drug name for query.\"\"\"\r\n return name.strip().replace('\"', '\\\\\"')\r\n\r\ndrug_name = clean_drug_name(user_input)\r\n```",
"Additional Resources": "- **openFDA Homepage**: https://open.fda.gov/\r\n- **API Documentation**: https://open.fda.gov/apis/\r\n- **Interactive API Explorer**: https://open.fda.gov/apis/try-the-api/\r\n- **GitHub Repository**: https://github.com/FDA/openfda\r\n- **Terms of Service**: https://open.fda.gov/terms/",
"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.\r\n\r\n**Key capabilities:**\r\n- Query adverse events for drugs, devices, foods, and veterinary products\r\n- Access product labeling, approvals, and regulatory submissions\r\n- Monitor recalls and enforcement actions\r\n- Look up National Drug Codes (NDC) and substance identifiers (UNII)\r\n- Analyze device classifications and clearances (510k, PMA)\r\n- Track drug shortages and supply issues\r\n- Research chemical structures and substance relationships",
"FDA Database Categories": "structure = fda.query(\"other\", \"substance\",\r\n search=\"names.name:ibuprofen+AND+substanceClass:chemical\")\r\n```\r\n\r\n**Reference:** See `references/other.md` for detailed documentation",
"Working with Results": "for skip in range(0, 1000, 100):\r\n batch = fda.query(\"drug\", \"event\",\r\n search=\"...\",\r\n limit=100,\r\n skip=skip)\r\n # Process batch\r\n```",
"When to Use This Skill": "This skill should be used when working with:\r\n- **Drug research**: Safety profiles, adverse events, labeling, approvals, shortages\r\n- **Medical device surveillance**: Adverse events, recalls, 510(k) clearances, PMA approvals\r\n- **Food safety**: Recalls, allergen tracking, adverse events, dietary supplements\r\n- **Veterinary medicine**: Animal drug adverse events by species and breed\r\n- **Chemical/substance data**: UNII lookup, CAS number mapping, molecular structures\r\n- **Regulatory analysis**: Approval pathways, enforcement actions, compliance tracking\r\n- **Pharmacovigilance**: Post-market surveillance, safety signal detection\r\n- **Scientific research**: Drug interactions, comparative safety, epidemiological studies",
"Support and Troubleshooting": "### Common Issues\r\n\r\n**Issue**: Rate limit exceeded\r\n- **Solution**: Use API key, implement delays, or reduce request frequency\r\n\r\n**Issue**: No results found\r\n- **Solution**: Try broader search terms, check spelling, use wildcards\r\n\r\n**Issue**: Invalid query syntax\r\n- **Solution**: Review query syntax in `references/api_basics.md`\r\n\r\n**Issue**: Missing fields in results\r\n- **Solution**: Not all records contain all fields; always check field existence\r\n\r\n### Getting Help\r\n\r\n- **GitHub Issues**: https://github.com/FDA/openfda/issues\r\n- **Email**: open-fda@fda.hhs.gov",
"API Reference": "For detailed information about:\r\n- **Authentication and rate limits** → See `references/api_basics.md`\r\n- **Drug databases** → See `references/drugs.md`\r\n- **Device databases** → See `references/devices.md`\r\n- **Food databases** → See `references/foods.md`\r\n- **Animal/veterinary databases** → See `references/animal_veterinary.md`\r\n- **Substance databases** → See `references/other.md`",
"Common Query Patterns": "### Pattern 1: Safety Profile Analysis\r\n\r\nCreate comprehensive safety profiles combining multiple data sources:\r\n\r\n```python\r\ndef drug_safety_profile(fda, drug_name):\r\n \"\"\"Generate complete safety profile.\"\"\"\r\n\r\n # 1. Total adverse events\r\n events = fda.query_drug_events(drug_name, limit=1)\r\n total = events[\"meta\"][\"results\"][\"total\"]\r\n\r\n # 2. Most common reactions\r\n reactions = fda.count_by_field(\r\n \"drug\", \"event\",\r\n search=f\"patient.drug.medicinalproduct:*{drug_name}*\",\r\n field=\"patient.reaction.reactionmeddrapt\",\r\n exact=True\r\n )\r\n\r\n # 3. Serious events\r\n serious = fda.query(\"drug\", \"event\",\r\n search=f\"patient.drug.medicinalproduct:*{drug_name}*+AND+serious:1\",\r\n limit=1)\r\n\r\n # 4. Recent recalls\r\n recalls = fda.query_drug_recalls(drug_name=drug_name)\r\n\r\n return {\r\n \"total_events\": total,\r\n \"top_reactions\": reactions[\"results\"][:10],\r\n \"serious_events\": serious[\"meta\"][\"results\"][\"total\"],\r\n \"recalls\": recalls[\"results\"]\r\n }\r\n```\r\n\r\n### Pattern 2: Temporal Trend Analysis\r\n\r\nAnalyze trends over time using date ranges:\r\n\r\n```python\r\nfrom datetime import datetime, timedelta\r\n\r\ndef get_monthly_trends(fda, drug_name, months=12):\r\n \"\"\"Get monthly adverse event trends.\"\"\"\r\n trends = []\r\n\r\n for i in range(months):\r\n end = datetime.now() - timedelta(days=30*i)\r\n start = end - timedelta(days=30)\r\n\r\n date_range = f\"[{start.strftime('%Y%m%d')}+TO+{end.strftime('%Y%m%d')}]\"\r\n search = f\"patient.drug.medicinalproduct:*{drug_name}*+AND+receivedate:{date_range}\"\r\n\r\n result = fda.query(\"drug\", \"event\", search=search, limit=1)\r\n count = result[\"meta\"][\"results\"][\"total\"] if \"meta\" in result else 0\r\n\r\n trends.append({\r\n \"month\": start.strftime(\"%Y-%m\"),\r\n \"events\": count\r\n })\r\n\r\n return trends\r\n```\r\n\r\n### Pattern 3: Comparative Analysis\r\n\r\nCompare multiple products side-by-side:\r\n\r\n```python\r\ndef compare_drugs(fda, drug_list):\r\n \"\"\"Compare safety profiles of multiple drugs.\"\"\"\r\n comparison = {}\r\n\r\n for drug in drug_list:\r\n # Total events\r\n events = fda.query_drug_events(drug, limit=1)\r\n total = events[\"meta\"][\"results\"][\"total\"] if \"meta\" in events else 0\r\n\r\n # Serious events\r\n serious = fda.query(\"drug\", \"event\",\r\n search=f\"patient.drug.medicinalproduct:*{drug}*+AND+serious:1\",\r\n limit=1)\r\n serious_count = serious[\"meta\"][\"results\"][\"total\"] if \"meta\" in serious else 0\r\n\r\n comparison[drug] = {\r\n \"total_events\": total,\r\n \"serious_events\": serious_count,\r\n \"serious_rate\": (serious_count/total*100) if total > 0 else 0\r\n }\r\n\r\n return comparison\r\n```\r\n\r\n### Pattern 4: Cross-Database Lookup\r\n\r\nLink data across multiple endpoints:\r\n\r\n```python\r\ndef comprehensive_device_lookup(fda, device_name):\r\n \"\"\"Look up device across all relevant databases.\"\"\"\r\n\r\n return {\r\n \"adverse_events\": fda.query_device_events(device_name, limit=10),\r\n \"510k_clearances\": fda.query_device_510k(device_name=device_name),\r\n \"recalls\": fda.query(\"device\", \"enforcement\",\r\n search=f\"product_description:*{device_name}*\"),\r\n \"udi_info\": fda.query(\"device\", \"udi\",\r\n search=f\"brand_name:*{device_name}*\")\r\n }\r\n```",
"Scripts": "### `scripts/fda_query.py`\r\n\r\nMain query module with `FDAQuery` class providing:\r\n- Unified interface to all FDA endpoints\r\n- Automatic rate limiting and caching\r\n- Error handling and retry logic\r\n- Common query patterns\r\n\r\n### `scripts/fda_examples.py`\r\n\r\nComprehensive examples demonstrating:\r\n- Drug safety profile analysis\r\n- Device surveillance monitoring\r\n- Food recall tracking\r\n- Substance lookup\r\n- Comparative drug analysis\r\n- Veterinary drug analysis\r\n\r\nRun examples:\r\n```bash\r\npython scripts/fda_examples.py\r\n```"
}
}---
name: fda-database
description: "Query openFDA API for drugs, devices, adverse events, recalls, regulatory submissions (510k, PMA), substance identification (UNII), for FDA regulatory data analysis and safety research."
---
# FDA Database Access
## 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
## 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
## Quick Start
### 1. Basic Setup
```python
from scripts.fda_query import FDAQuery
# Initialize (API key optional but recommended)
fda = FDAQuery(api_key="YOUR_API_KEY")
# Query drug adverse events
events = fda.query_drug_events("aspirin", limit=100)
# Get drug labeling
label = fda.query_drug_label("Lipitor", brand=True)
# Search device recalls
recalls = fda.query("device", "enforcement",
search="classification:Class+I",
limit=50)
```
### 2. API Key Setup
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
Register at: https://open.fda.gov/apis/authentication/
Set as environment variable:
```bash
export FDA_API_KEY="your_key_here"
```
### 3. Running Examples
```bash
# Run comprehensive examples
python scripts/fda_examples.py
# This demonstrates:
# - Drug safety profiles
# - Device surveillance
# - Food recall monitoring
# - Substance lookup
# - Comparative drug analysis
# - Veterinary drug analysis
```
## FDA Database Categories
### 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
# Safety signal detection
fda.count_by_field("drug", "event",
search="patient.drug.medicinalproduct:metformin",
field="patient.reaction.reactionmeddrapt")
# Get prescribing information
label = fda.query_drug_label("Keytruda", brand=True)
# Check for recalls
recalls = fda.query_drug_recalls(drug_name="metformin")
# Monitor shortages
shortages = fda.query("drug", "drugshortages",
search="status:Currently+in+Shortage")
```
**Reference:** See `references/drugs.md` for detailed documentation
### 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
# Monitor device safety
events = fda.query_device_events("pacemaker", limit=100)
# Look up device classification
classification = fda.query_device_classification("DQY")
# Find 510(k) clearances
clearances = fda.query_device_510k(applicant="Medtronic")
# Search by UDI
device_info = fda.query("device", "udi",
search="identifiers.id:00884838003019")
```
**Reference:** See `references/devices.md` for detailed documentation
### 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
# Monitor allergen recalls
recalls = fda.query_food_recalls(reason="undeclared peanut")
# Track dietary supplement events
events = fda.query_food_events(
industry="Dietary Supplements")
# Find contamination recalls
listeria = fda.query_food_recalls(
reason="listeria",
classification="I")
```
**Reference:** See `references/foods.md` for detailed documentation
### 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
# Species-specific events
dog_events = fda.query_animal_events(
species="Dog",
drug_name="flea collar")
# 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
### 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
# UNII to CAS mapping
substance = fda.query_substance_by_unii("R16CO5Y76E")
# Search by name
results = fda.query_substance_by_name("acetaminophen")
# Get chemical structure
structure = fda.query("other", "substance",
search="names.name:ibuprofen+AND+substanceClass:chemical")
```
**Reference:** See `references/other.md` for detailed documentation
## Common Query Patterns
### Pattern 1: Safety Profile Analysis
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"]
}
```
### Pattern 2: Temporal Trend Analysis
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
```
### Pattern 3: Comparative Analysis
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
```
### Pattern 4: Cross-Database Lookup
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}*")
}
```
## 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
]
}
```
### 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
```
### Pagination
For large result sets, use pagination:
```python
# Automatic pagination
all_results = fda.query_all(
"drug", "event",
search="patient.drug.medicinalproduct:aspirin",
max_results=5000
)
# Manual pagination
for skip in range(0, 1000, 100):
batch = fda.query("drug", "event",
search="...",
limit=100,
skip=skip)
# Process batch
```
## Best Practices
### 1. Use Specific Searches
**DO:**
```python
# Specific field search
search="patient.drug.medicinalproduct:aspirin"
```
**DON'T:**
```python
# Overly broad wildcard
search="*aspirin*"
```
### 2. Implement Rate Limiting
The `FDAQuery` class handles rate limiting automatically, but be aware of limits:
- 240 requests per minute
- 120,000 requests per day (with API key)
### 3. Cache Frequently Accessed Data
The `FDAQuery` class includes built-in caching (enabled by default):
```python
# Caching is automatic
fda = FDAQuery(api_key=api_key, use_cache=True, cache_ttl=3600)
```
### 4. Use Exact Matching for Counting
When counting/aggregating, use `.exact` suffix:
```python
# Count exact phrases
fda.count_by_field("drug", "event",
search="...",
field="patient.reaction.reactionmeddrapt",
exact=True) # Adds .exact automatically
```
### 5. Validate Input Data
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)
```
## API Reference
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`
## Scripts
### `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
### `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
```
## Additional Resources
- **openFDA Homepage**: https://open.fda.gov/
- **API Documentation**: https://open.fda.gov/apis/
- **Interactive API Explorer**: https://open.fda.gov/apis/try-the-api/
- **GitHub Repository**: https://github.com/FDA/openfda
- **Terms of Service**: https://open.fda.gov/terms/
## 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
### Getting Help
- **GitHub Issues**: https://github.com/FDA/openfda/issues
- **Email**: open-fda@fda.hhs.gov