
Pubchem Database
- 35 installs
- 16 repo stars
- Updated November 20, 2025
- jackspace/claudeskillz
Query PubChem via PUG-REST/PubChemPy - search by name/CID/SMILES, retrieve properties, and run similarity/substructure searches.
About
Provides access to PubChem's 110M+ compounds for structure search, property retrieval, and bioactivity data. A developer uses it for cheminformatics tasks like similarity searching and drug-likeness screening.
- Search by name, CID, SMILES, InChI, or molecular formula
- Similarity/substructure searches and molecular property retrieval
Pubchem Database by the numbers
- 35 all-time installs (skills.sh)
- Ranked #1,059 of 2,065 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/jackspace/claudeskillz --skill pubchem-databaseAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 35 |
|---|---|
| repo stars | ★ 16 |
| Last updated | November 20, 2025 |
| Repository | jackspace/claudeskillz ↗ |
What it does
Query PubChem via PUG-REST/PubChemPy - search by name/CID/SMILES, retrieve properties, and run similarity/substructure searches.
Files
PubChem Database
Overview
PubChem is the world's largest freely available chemical database with 110M+ compounds and 270M+ bioactivities. Query chemical structures by name, CID, or SMILES, retrieve molecular properties, perform similarity and substructure searches, access bioactivity data using PUG-REST API and PubChemPy.
When to Use This Skill
This skill should be used when:
- Searching for chemical compounds by name, structure (SMILES/InChI), or molecular formula
- Retrieving molecular properties (MW, LogP, TPSA, hydrogen bonding descriptors)
- Performing similarity searches to find structurally related compounds
- Conducting substructure searches for specific chemical motifs
- Accessing bioactivity data from screening assays
- Converting between chemical identifier formats (CID, SMILES, InChI)
- Batch processing multiple compounds for drug-likeness screening or property analysis
Core Capabilities
1. Chemical Structure Search
Search for compounds using multiple identifier types:
By Chemical Name:
import pubchempy as pcp
compounds = pcp.get_compounds('aspirin', 'name')
compound = compounds[0]By CID (Compound ID):
compound = pcp.Compound.from_cid(2244) # AspirinBy SMILES:
compound = pcp.get_compounds('CC(=O)OC1=CC=CC=C1C(=O)O', 'smiles')[0]By InChI:
compound = pcp.get_compounds('InChI=1S/C9H8O4/...', 'inchi')[0]By Molecular Formula:
compounds = pcp.get_compounds('C9H8O4', 'formula')
# Returns all compounds matching this formula2. Property Retrieval
Retrieve molecular properties for compounds using either high-level or low-level approaches:
Using PubChemPy (Recommended):
import pubchempy as pcp
# Get compound object with all properties
compound = pcp.get_compounds('caffeine', 'name')[0]
# Access individual properties
molecular_formula = compound.molecular_formula
molecular_weight = compound.molecular_weight
iupac_name = compound.iupac_name
smiles = compound.canonical_smiles
inchi = compound.inchi
xlogp = compound.xlogp # Partition coefficient
tpsa = compound.tpsa # Topological polar surface areaGet Specific Properties:
# Request only specific properties
properties = pcp.get_properties(
['MolecularFormula', 'MolecularWeight', 'CanonicalSMILES', 'XLogP'],
'aspirin',
'name'
)
# Returns list of dictionariesBatch Property Retrieval:
import pandas as pd
compound_names = ['aspirin', 'ibuprofen', 'paracetamol']
all_properties = []
for name in compound_names:
props = pcp.get_properties(
['MolecularFormula', 'MolecularWeight', 'XLogP'],
name,
'name'
)
all_properties.extend(props)
df = pd.DataFrame(all_properties)Available Properties: MolecularFormula, MolecularWeight, CanonicalSMILES, IsomericSMILES, InChI, InChIKey, IUPACName, XLogP, TPSA, HBondDonorCount, HBondAcceptorCount, RotatableBondCount, Complexity, Charge, and many more (see references/api_reference.md for complete list).
3. Similarity Search
Find structurally similar compounds using Tanimoto similarity:
import pubchempy as pcp
# Start with a query compound
query_compound = pcp.get_compounds('gefitinib', 'name')[0]
query_smiles = query_compound.canonical_smiles
# Perform similarity search
similar_compounds = pcp.get_compounds(
query_smiles,
'smiles',
searchtype='similarity',
Threshold=85, # Similarity threshold (0-100)
MaxRecords=50
)
# Process results
for compound in similar_compounds[:10]:
print(f"CID {compound.cid}: {compound.iupac_name}")
print(f" MW: {compound.molecular_weight}")Note: Similarity searches are asynchronous for large queries and may take 15-30 seconds to complete. PubChemPy handles the asynchronous pattern automatically.
4. Substructure Search
Find compounds containing a specific structural motif:
import pubchempy as pcp
# Search for compounds containing pyridine ring
pyridine_smiles = 'c1ccncc1'
matches = pcp.get_compounds(
pyridine_smiles,
'smiles',
searchtype='substructure',
MaxRecords=100
)
print(f"Found {len(matches)} compounds containing pyridine")Common Substructures:
- Benzene ring:
c1ccccc1 - Pyridine:
c1ccncc1 - Phenol:
c1ccc(O)cc1 - Carboxylic acid:
C(=O)O
5. Format Conversion
Convert between different chemical structure formats:
import pubchempy as pcp
compound = pcp.get_compounds('aspirin', 'name')[0]
# Convert to different formats
smiles = compound.canonical_smiles
inchi = compound.inchi
inchikey = compound.inchikey
cid = compound.cid
# Download structure files
pcp.download('SDF', 'aspirin', 'name', 'aspirin.sdf', overwrite=True)
pcp.download('JSON', '2244', 'cid', 'aspirin.json', overwrite=True)6. Structure Visualization
Generate 2D structure images:
import pubchempy as pcp
# Download compound structure as PNG
pcp.download('PNG', 'caffeine', 'name', 'caffeine.png', overwrite=True)
# Using direct URL (via requests)
import requests
cid = 2244 # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/PNG?image_size=large"
response = requests.get(url)
with open('structure.png', 'wb') as f:
f.write(response.content)7. Synonym Retrieval
Get all known names and synonyms for a compound:
import pubchempy as pcp
synonyms_data = pcp.get_synonyms('aspirin', 'name')
if synonyms_data:
cid = synonyms_data[0]['CID']
synonyms = synonyms_data[0]['Synonym']
print(f"CID {cid} has {len(synonyms)} synonyms:")
for syn in synonyms[:10]: # First 10
print(f" - {syn}")8. Bioactivity Data Access
Retrieve biological activity data from assays:
import requests
import json
# Get bioassay summary for a compound
cid = 2244 # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/assaysummary/JSON"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Process bioassay information
table = data.get('Table', {})
rows = table.get('Row', [])
print(f"Found {len(rows)} bioassay records")For more complex bioactivity queries, use the scripts/bioactivity_query.py helper script which provides:
- Bioassay summaries with activity outcome filtering
- Assay target identification
- Search for compounds by biological target
- Active compound lists for specific assays
9. Comprehensive Compound Annotations
Access detailed compound information through PUG-View:
import requests
cid = 2244
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON"
response = requests.get(url)
if response.status_code == 200:
annotations = response.json()
# Contains extensive data including:
# - Chemical and Physical Properties
# - Drug and Medication Information
# - Pharmacology and Biochemistry
# - Safety and Hazards
# - Toxicity
# - Literature references
# - PatentsGet Specific Section:
# Get only drug information
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON?heading=Drug and Medication Information"Installation Requirements
Install PubChemPy for Python-based access:
pip install pubchempyFor direct API access and bioactivity queries:
pip install requestsOptional for data analysis:
pip install pandasHelper Scripts
This skill includes Python scripts for common PubChem tasks:
scripts/compound_search.py
Provides utility functions for searching and retrieving compound information:
Key Functions:
search_by_name(name, max_results=10): Search compounds by namesearch_by_smiles(smiles): Search by SMILES stringget_compound_by_cid(cid): Retrieve compound by CIDget_compound_properties(identifier, namespace, properties): Get specific propertiessimilarity_search(smiles, threshold, max_records): Perform similarity searchsubstructure_search(smiles, max_records): Perform substructure searchget_synonyms(identifier, namespace): Get all synonymsbatch_search(identifiers, namespace, properties): Batch search multiple compoundsdownload_structure(identifier, namespace, format, filename): Download structuresprint_compound_info(compound): Print formatted compound information
Usage:
from scripts.compound_search import search_by_name, get_compound_properties
# Search for a compound
compounds = search_by_name('ibuprofen')
# Get specific properties
props = get_compound_properties('aspirin', 'name', ['MolecularWeight', 'XLogP'])scripts/bioactivity_query.py
Provides functions for retrieving biological activity data:
Key Functions:
get_bioassay_summary(cid): Get bioassay summary for compoundget_compound_bioactivities(cid, activity_outcome): Get filtered bioactivitiesget_assay_description(aid): Get detailed assay informationget_assay_targets(aid): Get biological targets for assaysearch_assays_by_target(target_name, max_results): Find assays by targetget_active_compounds_in_assay(aid, max_results): Get active compoundsget_compound_annotations(cid, section): Get PUG-View annotationssummarize_bioactivities(cid): Generate bioactivity summary statisticsfind_compounds_by_bioactivity(target, threshold, max_compounds): Find compounds by target
Usage:
from scripts.bioactivity_query import get_bioassay_summary, summarize_bioactivities
# Get bioactivity summary
summary = summarize_bioactivities(2244) # Aspirin
print(f"Total assays: {summary['total_assays']}")
print(f"Active: {summary['active']}, Inactive: {summary['inactive']}")API Rate Limits and Best Practices
Rate Limits:
- Maximum 5 requests per second
- Maximum 400 requests per minute
- Maximum 300 seconds running time per minute
Best Practices: 1. Use CIDs for repeated queries: CIDs are more efficient than names or structures 2. Cache results locally: Store frequently accessed data 3. Batch requests: Combine multiple queries when possible 4. Implement delays: Add 0.2-0.3 second delays between requests 5. Handle errors gracefully: Check for HTTP errors and missing data 6. Use PubChemPy: Higher-level abstraction handles many edge cases 7. Leverage asynchronous pattern: For large similarity/substructure searches 8. Specify MaxRecords: Limit results to avoid timeouts
Error Handling:
from pubchempy import BadRequestError, NotFoundError, TimeoutError
try:
compound = pcp.get_compounds('query', 'name')[0]
except NotFoundError:
print("Compound not found")
except BadRequestError:
print("Invalid request format")
except TimeoutError:
print("Request timed out - try reducing scope")
except IndexError:
print("No results returned")Common Workflows
Workflow 1: Chemical Identifier Conversion Pipeline
Convert between different chemical identifiers:
import pubchempy as pcp
# Start with any identifier type
compound = pcp.get_compounds('caffeine', 'name')[0]
# Extract all identifier formats
identifiers = {
'CID': compound.cid,
'Name': compound.iupac_name,
'SMILES': compound.canonical_smiles,
'InChI': compound.inchi,
'InChIKey': compound.inchikey,
'Formula': compound.molecular_formula
}Workflow 2: Drug-Like Property Screening
Screen compounds using Lipinski's Rule of Five:
import pubchempy as pcp
def check_drug_likeness(compound_name):
compound = pcp.get_compounds(compound_name, 'name')[0]
# Lipinski's Rule of Five
rules = {
'MW <= 500': compound.molecular_weight <= 500,
'LogP <= 5': compound.xlogp <= 5 if compound.xlogp else None,
'HBD <= 5': compound.h_bond_donor_count <= 5,
'HBA <= 10': compound.h_bond_acceptor_count <= 10
}
violations = sum(1 for v in rules.values() if v is False)
return rules, violations
rules, violations = check_drug_likeness('aspirin')
print(f"Lipinski violations: {violations}")Workflow 3: Finding Similar Drug Candidates
Identify structurally similar compounds to a known drug:
import pubchempy as pcp
# Start with known drug
reference_drug = pcp.get_compounds('imatinib', 'name')[0]
reference_smiles = reference_drug.canonical_smiles
# Find similar compounds
similar = pcp.get_compounds(
reference_smiles,
'smiles',
searchtype='similarity',
Threshold=85,
MaxRecords=20
)
# Filter by drug-like properties
candidates = []
for comp in similar:
if comp.molecular_weight and 200 <= comp.molecular_weight <= 600:
if comp.xlogp and -1 <= comp.xlogp <= 5:
candidates.append(comp)
print(f"Found {len(candidates)} drug-like candidates")Workflow 4: Batch Compound Property Comparison
Compare properties across multiple compounds:
import pubchempy as pcp
import pandas as pd
compound_list = ['aspirin', 'ibuprofen', 'naproxen', 'celecoxib']
properties_list = []
for name in compound_list:
try:
compound = pcp.get_compounds(name, 'name')[0]
properties_list.append({
'Name': name,
'CID': compound.cid,
'Formula': compound.molecular_formula,
'MW': compound.molecular_weight,
'LogP': compound.xlogp,
'TPSA': compound.tpsa,
'HBD': compound.h_bond_donor_count,
'HBA': compound.h_bond_acceptor_count
})
except Exception as e:
print(f"Error processing {name}: {e}")
df = pd.DataFrame(properties_list)
print(df.to_string(index=False))Workflow 5: Substructure-Based Virtual Screening
Screen for compounds containing specific pharmacophores:
import pubchempy as pcp
# Define pharmacophore (e.g., sulfonamide group)
pharmacophore_smiles = 'S(=O)(=O)N'
# Search for compounds containing this substructure
hits = pcp.get_compounds(
pharmacophore_smiles,
'smiles',
searchtype='substructure',
MaxRecords=100
)
# Further filter by properties
filtered_hits = [
comp for comp in hits
if comp.molecular_weight and comp.molecular_weight < 500
]
print(f"Found {len(filtered_hits)} compounds with desired substructure")Reference Documentation
For detailed API documentation, including complete property lists, URL patterns, advanced query options, and more examples, consult references/api_reference.md. This comprehensive reference includes:
- Complete PUG-REST API endpoint documentation
- Full list of available molecular properties
- Asynchronous request handling patterns
- PubChemPy API reference
- PUG-View API for annotations
- Common workflows and use cases
- Links to official PubChem documentation
Troubleshooting
Compound Not Found:
- Try alternative names or synonyms
- Use CID if known
- Check spelling and chemical name format
Timeout Errors:
- Reduce MaxRecords parameter
- Add delays between requests
- Use CIDs instead of names for faster queries
Empty Property Values:
- Not all properties are available for all compounds
- Check if property exists before accessing:
if compound.xlogp: - Some properties only available for certain compound types
Rate Limit Exceeded:
- Implement delays (0.2-0.3 seconds) between requests
- Use batch operations where possible
- Consider caching results locally
Similarity/Substructure Search Hangs:
- These are asynchronous operations that may take 15-30 seconds
- PubChemPy handles polling automatically
- Reduce MaxRecords if timing out
Additional Resources
- PubChem Home: https://pubchem.ncbi.nlm.nih.gov/
- PUG-REST Documentation: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest
- PUG-REST Tutorial: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest-tutorial
- PubChemPy Documentation: https://pubchempy.readthedocs.io/
- PubChemPy GitHub: https://github.com/mcs07/PubChemPy
{
"description": "\"Query PubChem via PUG-REST API/PubChemPy (110M+ compounds). Search by name/CID/SMILES, retrieve properties, similarity/substructure searches, bioactivity, for cheminformatics.\"",
"references": {
"files": [
"references/api_reference.md"
]
},
"content": "### 1. Chemical Structure Search\r\n\r\nSearch for compounds using multiple identifier types:\r\n\r\n**By Chemical Name**:\r\n```python\r\nimport pubchempy as pcp\r\ncompounds = pcp.get_compounds('aspirin', 'name')\r\ncompound = compounds[0]\r\n```\r\n\r\n**By CID (Compound ID)**:\r\n```python\r\ncompound = pcp.Compound.from_cid(2244) # Aspirin\r\n```\r\n\r\n**By SMILES**:\r\n```python\r\ncompound = pcp.get_compounds('CC(=O)OC1=CC=CC=C1C(=O)O', 'smiles')[0]\r\n```\r\n\r\n**By InChI**:\r\n```python\r\ncompound = pcp.get_compounds('InChI=1S/C9H8O4/...', 'inchi')[0]\r\n```\r\n\r\n**By Molecular Formula**:\r\n```python\r\ncompounds = pcp.get_compounds('C9H8O4', 'formula')\r\n```\r\n\r\n### 2. Property Retrieval\r\n\r\nRetrieve molecular properties for compounds using either high-level or low-level approaches:\r\n\r\n**Using PubChemPy (Recommended)**:\r\n```python\r\nimport pubchempy as pcp\r\n\r\ncompound = pcp.get_compounds('caffeine', 'name')[0]\r\n\r\nmolecular_formula = compound.molecular_formula\r\nmolecular_weight = compound.molecular_weight\r\niupac_name = compound.iupac_name\r\nsmiles = compound.canonical_smiles\r\ninchi = compound.inchi\r\nxlogp = compound.xlogp # Partition coefficient\r\ntpsa = compound.tpsa # Topological polar surface area\r\n```\r\n\r\n**Get Specific Properties**:\r\n```python\r\nproperties = pcp.get_properties(\r\n ['MolecularFormula', 'MolecularWeight', 'CanonicalSMILES', 'XLogP'],\r\n 'aspirin',\r\n 'name'\r\n)\r\n```\r\n\r\n**Batch Property Retrieval**:\r\n```python\r\nimport pandas as pd\r\n\r\ncompound_names = ['aspirin', 'ibuprofen', 'paracetamol']\r\nall_properties = []\r\n\r\nfor name in compound_names:\r\n props = pcp.get_properties(\r\n ['MolecularFormula', 'MolecularWeight', 'XLogP'],\r\n name,\r\n 'name'\r\n )\r\n all_properties.extend(props)\r\n\r\ndf = pd.DataFrame(all_properties)\r\n```\r\n\r\n**Available Properties**: MolecularFormula, MolecularWeight, CanonicalSMILES, IsomericSMILES, InChI, InChIKey, IUPACName, XLogP, TPSA, HBondDonorCount, HBondAcceptorCount, RotatableBondCount, Complexity, Charge, and many more (see `references/api_reference.md` for complete list).\r\n\r\n### 3. Similarity Search\r\n\r\nFind structurally similar compounds using Tanimoto similarity:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\nquery_compound = pcp.get_compounds('gefitinib', 'name')[0]\r\nquery_smiles = query_compound.canonical_smiles\r\n\r\nsimilar_compounds = pcp.get_compounds(\r\n query_smiles,\r\n 'smiles',\r\n searchtype='similarity',\r\n Threshold=85, # Similarity threshold (0-100)\r\n MaxRecords=50\r\n)\r\n\r\nfor compound in similar_compounds[:10]:\r\n print(f\"CID {compound.cid}: {compound.iupac_name}\")\r\n print(f\" MW: {compound.molecular_weight}\")\r\n```\r\n\r\n**Note**: Similarity searches are asynchronous for large queries and may take 15-30 seconds to complete. PubChemPy handles the asynchronous pattern automatically.\r\n\r\n### 4. Substructure Search\r\n\r\nFind compounds containing a specific structural motif:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\npyridine_smiles = 'c1ccncc1'\r\n\r\nmatches = pcp.get_compounds(\r\n pyridine_smiles,\r\n 'smiles',\r\n searchtype='substructure',\r\n MaxRecords=100\r\n)\r\n\r\nprint(f\"Found {len(matches)} compounds containing pyridine\")\r\n```\r\n\r\n**Common Substructures**:\r\n- Benzene ring: `c1ccccc1`\r\n- Pyridine: `c1ccncc1`\r\n- Phenol: `c1ccc(O)cc1`\r\n- Carboxylic acid: `C(=O)O`\r\n\r\n### 5. Format Conversion\r\n\r\nConvert between different chemical structure formats:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\ncompound = pcp.get_compounds('aspirin', 'name')[0]\r\n\r\nsmiles = compound.canonical_smiles\r\ninchi = compound.inchi\r\ninchikey = compound.inchikey\r\ncid = compound.cid\r\n\r\npcp.download('SDF', 'aspirin', 'name', 'aspirin.sdf', overwrite=True)\r\npcp.download('JSON', '2244', 'cid', 'aspirin.json', overwrite=True)\r\n```\r\n\r\n### 6. Structure Visualization\r\n\r\nGenerate 2D structure images:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\npcp.download('PNG', 'caffeine', 'name', 'caffeine.png', overwrite=True)\r\n\r\nimport requests\r\n\r\ncid = 2244 # Aspirin\r\nurl = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/PNG?image_size=large\"\r\nresponse = requests.get(url)\r\n\r\nwith open('structure.png', 'wb') as f:\r\n f.write(response.content)\r\n```\r\n\r\n### 7. Synonym Retrieval\r\n\r\nGet all known names and synonyms for a compound:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\nsynonyms_data = pcp.get_synonyms('aspirin', 'name')\r\n\r\nif synonyms_data:\r\n cid = synonyms_data[0]['CID']\r\n synonyms = synonyms_data[0]['Synonym']\r\n\r\n print(f\"CID {cid} has {len(synonyms)} synonyms:\")\r\n for syn in synonyms[:10]: # First 10\r\n print(f\" - {syn}\")\r\n```\r\n\r\n### 8. Bioactivity Data Access\r\n\r\nRetrieve biological activity data from assays:\r\n\r\n```python\r\nimport requests\r\nimport json\r\n\r\ncid = 2244 # Aspirin\r\nurl = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/assaysummary/JSON\"\r\n\r\nresponse = requests.get(url)\r\nif response.status_code == 200:\r\n data = response.json()\r\n # Process bioassay information\r\n table = data.get('Table', {})\r\n rows = table.get('Row', [])\r\n print(f\"Found {len(rows)} bioassay records\")\r\n```\r\n\r\n**For more complex bioactivity queries**, use the `scripts/bioactivity_query.py` helper script which provides:\r\n- Bioassay summaries with activity outcome filtering\r\n- Assay target identification\r\n- Search for compounds by biological target\r\n- Active compound lists for specific assays\r\n\r\n### 9. Comprehensive Compound Annotations\r\n\r\nAccess detailed compound information through PUG-View:\r\n\r\n```python\r\nimport requests\r\n\r\ncid = 2244\r\nurl = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON\"\r\n\r\nresponse = requests.get(url)\r\nif response.status_code == 200:\r\n annotations = response.json()\r\n # Contains extensive data including:\r\n # - Chemical and Physical Properties\r\n # - Drug and Medication Information\r\n # - Pharmacology and Biochemistry\r\n # - Safety and Hazards\r\n # - Toxicity\r\n # - Literature references\r\n # - Patents\r\n```\r\n\r\n**Get Specific Section**:\r\n```python\r\n\r\nThis skill includes Python scripts for common PubChem tasks:\r\n\r\n### scripts/compound_search.py\r\n\r\nProvides utility functions for searching and retrieving compound information:\r\n\r\n**Key Functions**:\r\n- `search_by_name(name, max_results=10)`: Search compounds by name\r\n- `search_by_smiles(smiles)`: Search by SMILES string\r\n- `get_compound_by_cid(cid)`: Retrieve compound by CID\r\n- `get_compound_properties(identifier, namespace, properties)`: Get specific properties\r\n- `similarity_search(smiles, threshold, max_records)`: Perform similarity search\r\n- `substructure_search(smiles, max_records)`: Perform substructure search\r\n- `get_synonyms(identifier, namespace)`: Get all synonyms\r\n- `batch_search(identifiers, namespace, properties)`: Batch search multiple compounds\r\n- `download_structure(identifier, namespace, format, filename)`: Download structures\r\n- `print_compound_info(compound)`: Print formatted compound information\r\n\r\n**Usage**:\r\n```python\r\nfrom scripts.compound_search import search_by_name, get_compound_properties\r\n\r\ncompounds = search_by_name('ibuprofen')\r\n\r\nprops = get_compound_properties('aspirin', 'name', ['MolecularWeight', 'XLogP'])\r\n```\r\n\r\n### scripts/bioactivity_query.py\r\n\r\nProvides functions for retrieving biological activity data:\r\n\r\n**Key Functions**:\r\n- `get_bioassay_summary(cid)`: Get bioassay summary for compound\r\n- `get_compound_bioactivities(cid, activity_outcome)`: Get filtered bioactivities\r\n- `get_assay_description(aid)`: Get detailed assay information\r\n- `get_assay_targets(aid)`: Get biological targets for assay\r\n- `search_assays_by_target(target_name, max_results)`: Find assays by target\r\n- `get_active_compounds_in_assay(aid, max_results)`: Get active compounds\r\n- `get_compound_annotations(cid, section)`: Get PUG-View annotations\r\n- `summarize_bioactivities(cid)`: Generate bioactivity summary statistics\r\n- `find_compounds_by_bioactivity(target, threshold, max_compounds)`: Find compounds by target\r\n\r\n**Usage**:\r\n```python\r\nfrom scripts.bioactivity_query import get_bioassay_summary, summarize_bioactivities\r\n\r\n\r\n### Workflow 1: Chemical Identifier Conversion Pipeline\r\n\r\nConvert between different chemical identifiers:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\ncompound = pcp.get_compounds('caffeine', 'name')[0]\r\n\r\nidentifiers = {\r\n 'CID': compound.cid,\r\n 'Name': compound.iupac_name,\r\n 'SMILES': compound.canonical_smiles,\r\n 'InChI': compound.inchi,\r\n 'InChIKey': compound.inchikey,\r\n 'Formula': compound.molecular_formula\r\n}\r\n```\r\n\r\n### Workflow 2: Drug-Like Property Screening\r\n\r\nScreen compounds using Lipinski's Rule of Five:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\ndef check_drug_likeness(compound_name):\r\n compound = pcp.get_compounds(compound_name, 'name')[0]\r\n\r\n # Lipinski's Rule of Five\r\n rules = {\r\n 'MW <= 500': compound.molecular_weight <= 500,\r\n 'LogP <= 5': compound.xlogp <= 5 if compound.xlogp else None,\r\n 'HBD <= 5': compound.h_bond_donor_count <= 5,\r\n 'HBA <= 10': compound.h_bond_acceptor_count <= 10\r\n }\r\n\r\n violations = sum(1 for v in rules.values() if v is False)\r\n return rules, violations\r\n\r\nrules, violations = check_drug_likeness('aspirin')\r\nprint(f\"Lipinski violations: {violations}\")\r\n```\r\n\r\n### Workflow 3: Finding Similar Drug Candidates\r\n\r\nIdentify structurally similar compounds to a known drug:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\nreference_drug = pcp.get_compounds('imatinib', 'name')[0]\r\nreference_smiles = reference_drug.canonical_smiles\r\n\r\nsimilar = pcp.get_compounds(\r\n reference_smiles,\r\n 'smiles',\r\n searchtype='similarity',\r\n Threshold=85,\r\n MaxRecords=20\r\n)\r\n\r\ncandidates = []\r\nfor comp in similar:\r\n if comp.molecular_weight and 200 <= comp.molecular_weight <= 600:\r\n if comp.xlogp and -1 <= comp.xlogp <= 5:\r\n candidates.append(comp)\r\n\r\nprint(f\"Found {len(candidates)} drug-like candidates\")\r\n```\r\n\r\n### Workflow 4: Batch Compound Property Comparison\r\n\r\nCompare properties across multiple compounds:\r\n\r\n```python\r\nimport pubchempy as pcp\r\nimport pandas as pd\r\n\r\ncompound_list = ['aspirin', 'ibuprofen', 'naproxen', 'celecoxib']\r\n\r\nproperties_list = []\r\nfor name in compound_list:\r\n try:\r\n compound = pcp.get_compounds(name, 'name')[0]\r\n properties_list.append({\r\n 'Name': name,\r\n 'CID': compound.cid,\r\n 'Formula': compound.molecular_formula,\r\n 'MW': compound.molecular_weight,\r\n 'LogP': compound.xlogp,\r\n 'TPSA': compound.tpsa,\r\n 'HBD': compound.h_bond_donor_count,\r\n 'HBA': compound.h_bond_acceptor_count\r\n })\r\n except Exception as e:\r\n print(f\"Error processing {name}: {e}\")\r\n\r\ndf = pd.DataFrame(properties_list)\r\nprint(df.to_string(index=False))\r\n```\r\n\r\n### Workflow 5: Substructure-Based Virtual Screening\r\n\r\nScreen for compounds containing specific pharmacophores:\r\n\r\n```python\r\nimport pubchempy as pcp\r\n\r\npharmacophore_smiles = 'S(=O)(=O)N'\r\n\r\nhits = pcp.get_compounds(\r\n pharmacophore_smiles,\r\n 'smiles',\r\n searchtype='substructure',\r\n MaxRecords=100\r\n)",
"name": "pubchem-database",
"id": "scientific-db-pubchem-database",
"sections": {
"Reference Documentation": "For detailed API documentation, including complete property lists, URL patterns, advanced query options, and more examples, consult `references/api_reference.md`. This comprehensive reference includes:\r\n\r\n- Complete PUG-REST API endpoint documentation\r\n- Full list of available molecular properties\r\n- Asynchronous request handling patterns\r\n- PubChemPy API reference\r\n- PUG-View API for annotations\r\n- Common workflows and use cases\r\n- Links to official PubChem documentation",
"Installation Requirements": "Install PubChemPy for Python-based access:\r\n\r\n```bash\r\npip install pubchempy\r\n```\r\n\r\nFor direct API access and bioactivity queries:\r\n\r\n```bash\r\npip install requests\r\n```\r\n\r\nOptional for data analysis:\r\n\r\n```bash\r\npip install pandas\r\n```",
"Additional Resources": "- PubChem Home: https://pubchem.ncbi.nlm.nih.gov/\r\n- PUG-REST Documentation: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest\r\n- PUG-REST Tutorial: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest-tutorial\r\n- PubChemPy Documentation: https://pubchempy.readthedocs.io/\r\n- PubChemPy GitHub: https://github.com/mcs07/PubChemPy",
"Troubleshooting": "**Compound Not Found**:\r\n- Try alternative names or synonyms\r\n- Use CID if known\r\n- Check spelling and chemical name format\r\n\r\n**Timeout Errors**:\r\n- Reduce MaxRecords parameter\r\n- Add delays between requests\r\n- Use CIDs instead of names for faster queries\r\n\r\n**Empty Property Values**:\r\n- Not all properties are available for all compounds\r\n- Check if property exists before accessing: `if compound.xlogp:`\r\n- Some properties only available for certain compound types\r\n\r\n**Rate Limit Exceeded**:\r\n- Implement delays (0.2-0.3 seconds) between requests\r\n- Use batch operations where possible\r\n- Consider caching results locally\r\n\r\n**Similarity/Substructure Search Hangs**:\r\n- These are asynchronous operations that may take 15-30 seconds\r\n- PubChemPy handles polling automatically\r\n- Reduce MaxRecords if timing out",
"Overview": "PubChem is the world's largest freely available chemical database with 110M+ compounds and 270M+ bioactivities. Query chemical structures by name, CID, or SMILES, retrieve molecular properties, perform similarity and substructure searches, access bioactivity data using PUG-REST API and PubChemPy.",
"Common Workflows": "filtered_hits = [\r\n comp for comp in hits\r\n if comp.molecular_weight and comp.molecular_weight < 500\r\n]\r\n\r\nprint(f\"Found {len(filtered_hits)} compounds with desired substructure\")\r\n```",
"API Rate Limits and Best Practices": "**Rate Limits**:\r\n- Maximum 5 requests per second\r\n- Maximum 400 requests per minute\r\n- Maximum 300 seconds running time per minute\r\n\r\n**Best Practices**:\r\n1. **Use CIDs for repeated queries**: CIDs are more efficient than names or structures\r\n2. **Cache results locally**: Store frequently accessed data\r\n3. **Batch requests**: Combine multiple queries when possible\r\n4. **Implement delays**: Add 0.2-0.3 second delays between requests\r\n5. **Handle errors gracefully**: Check for HTTP errors and missing data\r\n6. **Use PubChemPy**: Higher-level abstraction handles many edge cases\r\n7. **Leverage asynchronous pattern**: For large similarity/substructure searches\r\n8. **Specify MaxRecords**: Limit results to avoid timeouts\r\n\r\n**Error Handling**:\r\n```python\r\nfrom pubchempy import BadRequestError, NotFoundError, TimeoutError\r\n\r\ntry:\r\n compound = pcp.get_compounds('query', 'name')[0]\r\nexcept NotFoundError:\r\n print(\"Compound not found\")\r\nexcept BadRequestError:\r\n print(\"Invalid request format\")\r\nexcept TimeoutError:\r\n print(\"Request timed out - try reducing scope\")\r\nexcept IndexError:\r\n print(\"No results returned\")\r\n```",
"When to Use This Skill": "This skill should be used when:\r\n- Searching for chemical compounds by name, structure (SMILES/InChI), or molecular formula\r\n- Retrieving molecular properties (MW, LogP, TPSA, hydrogen bonding descriptors)\r\n- Performing similarity searches to find structurally related compounds\r\n- Conducting substructure searches for specific chemical motifs\r\n- Accessing bioactivity data from screening assays\r\n- Converting between chemical identifier formats (CID, SMILES, InChI)\r\n- Batch processing multiple compounds for drug-likeness screening or property analysis",
"Core Capabilities": "url = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON?heading=Drug and Medication Information\"\r\n```",
"Helper Scripts": "summary = summarize_bioactivities(2244) # Aspirin\r\nprint(f\"Total assays: {summary['total_assays']}\")\r\nprint(f\"Active: {summary['active']}, Inactive: {summary['inactive']}\")\r\n```"
}
}---
name: pubchem-database
description: "Query PubChem via PUG-REST API/PubChemPy (110M+ compounds). Search by name/CID/SMILES, retrieve properties, similarity/substructure searches, bioactivity, for cheminformatics."
---
# PubChem Database
## Overview
PubChem is the world's largest freely available chemical database with 110M+ compounds and 270M+ bioactivities. Query chemical structures by name, CID, or SMILES, retrieve molecular properties, perform similarity and substructure searches, access bioactivity data using PUG-REST API and PubChemPy.
## When to Use This Skill
This skill should be used when:
- Searching for chemical compounds by name, structure (SMILES/InChI), or molecular formula
- Retrieving molecular properties (MW, LogP, TPSA, hydrogen bonding descriptors)
- Performing similarity searches to find structurally related compounds
- Conducting substructure searches for specific chemical motifs
- Accessing bioactivity data from screening assays
- Converting between chemical identifier formats (CID, SMILES, InChI)
- Batch processing multiple compounds for drug-likeness screening or property analysis
## Core Capabilities
### 1. Chemical Structure Search
Search for compounds using multiple identifier types:
**By Chemical Name**:
```python
import pubchempy as pcp
compounds = pcp.get_compounds('aspirin', 'name')
compound = compounds[0]
```
**By CID (Compound ID)**:
```python
compound = pcp.Compound.from_cid(2244) # Aspirin
```
**By SMILES**:
```python
compound = pcp.get_compounds('CC(=O)OC1=CC=CC=C1C(=O)O', 'smiles')[0]
```
**By InChI**:
```python
compound = pcp.get_compounds('InChI=1S/C9H8O4/...', 'inchi')[0]
```
**By Molecular Formula**:
```python
compounds = pcp.get_compounds('C9H8O4', 'formula')
# Returns all compounds matching this formula
```
### 2. Property Retrieval
Retrieve molecular properties for compounds using either high-level or low-level approaches:
**Using PubChemPy (Recommended)**:
```python
import pubchempy as pcp
# Get compound object with all properties
compound = pcp.get_compounds('caffeine', 'name')[0]
# Access individual properties
molecular_formula = compound.molecular_formula
molecular_weight = compound.molecular_weight
iupac_name = compound.iupac_name
smiles = compound.canonical_smiles
inchi = compound.inchi
xlogp = compound.xlogp # Partition coefficient
tpsa = compound.tpsa # Topological polar surface area
```
**Get Specific Properties**:
```python
# Request only specific properties
properties = pcp.get_properties(
['MolecularFormula', 'MolecularWeight', 'CanonicalSMILES', 'XLogP'],
'aspirin',
'name'
)
# Returns list of dictionaries
```
**Batch Property Retrieval**:
```python
import pandas as pd
compound_names = ['aspirin', 'ibuprofen', 'paracetamol']
all_properties = []
for name in compound_names:
props = pcp.get_properties(
['MolecularFormula', 'MolecularWeight', 'XLogP'],
name,
'name'
)
all_properties.extend(props)
df = pd.DataFrame(all_properties)
```
**Available Properties**: MolecularFormula, MolecularWeight, CanonicalSMILES, IsomericSMILES, InChI, InChIKey, IUPACName, XLogP, TPSA, HBondDonorCount, HBondAcceptorCount, RotatableBondCount, Complexity, Charge, and many more (see `references/api_reference.md` for complete list).
### 3. Similarity Search
Find structurally similar compounds using Tanimoto similarity:
```python
import pubchempy as pcp
# Start with a query compound
query_compound = pcp.get_compounds('gefitinib', 'name')[0]
query_smiles = query_compound.canonical_smiles
# Perform similarity search
similar_compounds = pcp.get_compounds(
query_smiles,
'smiles',
searchtype='similarity',
Threshold=85, # Similarity threshold (0-100)
MaxRecords=50
)
# Process results
for compound in similar_compounds[:10]:
print(f"CID {compound.cid}: {compound.iupac_name}")
print(f" MW: {compound.molecular_weight}")
```
**Note**: Similarity searches are asynchronous for large queries and may take 15-30 seconds to complete. PubChemPy handles the asynchronous pattern automatically.
### 4. Substructure Search
Find compounds containing a specific structural motif:
```python
import pubchempy as pcp
# Search for compounds containing pyridine ring
pyridine_smiles = 'c1ccncc1'
matches = pcp.get_compounds(
pyridine_smiles,
'smiles',
searchtype='substructure',
MaxRecords=100
)
print(f"Found {len(matches)} compounds containing pyridine")
```
**Common Substructures**:
- Benzene ring: `c1ccccc1`
- Pyridine: `c1ccncc1`
- Phenol: `c1ccc(O)cc1`
- Carboxylic acid: `C(=O)O`
### 5. Format Conversion
Convert between different chemical structure formats:
```python
import pubchempy as pcp
compound = pcp.get_compounds('aspirin', 'name')[0]
# Convert to different formats
smiles = compound.canonical_smiles
inchi = compound.inchi
inchikey = compound.inchikey
cid = compound.cid
# Download structure files
pcp.download('SDF', 'aspirin', 'name', 'aspirin.sdf', overwrite=True)
pcp.download('JSON', '2244', 'cid', 'aspirin.json', overwrite=True)
```
### 6. Structure Visualization
Generate 2D structure images:
```python
import pubchempy as pcp
# Download compound structure as PNG
pcp.download('PNG', 'caffeine', 'name', 'caffeine.png', overwrite=True)
# Using direct URL (via requests)
import requests
cid = 2244 # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/PNG?image_size=large"
response = requests.get(url)
with open('structure.png', 'wb') as f:
f.write(response.content)
```
### 7. Synonym Retrieval
Get all known names and synonyms for a compound:
```python
import pubchempy as pcp
synonyms_data = pcp.get_synonyms('aspirin', 'name')
if synonyms_data:
cid = synonyms_data[0]['CID']
synonyms = synonyms_data[0]['Synonym']
print(f"CID {cid} has {len(synonyms)} synonyms:")
for syn in synonyms[:10]: # First 10
print(f" - {syn}")
```
### 8. Bioactivity Data Access
Retrieve biological activity data from assays:
```python
import requests
import json
# Get bioassay summary for a compound
cid = 2244 # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/assaysummary/JSON"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Process bioassay information
table = data.get('Table', {})
rows = table.get('Row', [])
print(f"Found {len(rows)} bioassay records")
```
**For more complex bioactivity queries**, use the `scripts/bioactivity_query.py` helper script which provides:
- Bioassay summaries with activity outcome filtering
- Assay target identification
- Search for compounds by biological target
- Active compound lists for specific assays
### 9. Comprehensive Compound Annotations
Access detailed compound information through PUG-View:
```python
import requests
cid = 2244
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON"
response = requests.get(url)
if response.status_code == 200:
annotations = response.json()
# Contains extensive data including:
# - Chemical and Physical Properties
# - Drug and Medication Information
# - Pharmacology and Biochemistry
# - Safety and Hazards
# - Toxicity
# - Literature references
# - Patents
```
**Get Specific Section**:
```python
# Get only drug information
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON?heading=Drug and Medication Information"
```
## Installation Requirements
Install PubChemPy for Python-based access:
```bash
pip install pubchempy
```
For direct API access and bioactivity queries:
```bash
pip install requests
```
Optional for data analysis:
```bash
pip install pandas
```
## Helper Scripts
This skill includes Python scripts for common PubChem tasks:
### scripts/compound_search.py
Provides utility functions for searching and retrieving compound information:
**Key Functions**:
- `search_by_name(name, max_results=10)`: Search compounds by name
- `search_by_smiles(smiles)`: Search by SMILES string
- `get_compound_by_cid(cid)`: Retrieve compound by CID
- `get_compound_properties(identifier, namespace, properties)`: Get specific properties
- `similarity_search(smiles, threshold, max_records)`: Perform similarity search
- `substructure_search(smiles, max_records)`: Perform substructure search
- `get_synonyms(identifier, namespace)`: Get all synonyms
- `batch_search(identifiers, namespace, properties)`: Batch search multiple compounds
- `download_structure(identifier, namespace, format, filename)`: Download structures
- `print_compound_info(compound)`: Print formatted compound information
**Usage**:
```python
from scripts.compound_search import search_by_name, get_compound_properties
# Search for a compound
compounds = search_by_name('ibuprofen')
# Get specific properties
props = get_compound_properties('aspirin', 'name', ['MolecularWeight', 'XLogP'])
```
### scripts/bioactivity_query.py
Provides functions for retrieving biological activity data:
**Key Functions**:
- `get_bioassay_summary(cid)`: Get bioassay summary for compound
- `get_compound_bioactivities(cid, activity_outcome)`: Get filtered bioactivities
- `get_assay_description(aid)`: Get detailed assay information
- `get_assay_targets(aid)`: Get biological targets for assay
- `search_assays_by_target(target_name, max_results)`: Find assays by target
- `get_active_compounds_in_assay(aid, max_results)`: Get active compounds
- `get_compound_annotations(cid, section)`: Get PUG-View annotations
- `summarize_bioactivities(cid)`: Generate bioactivity summary statistics
- `find_compounds_by_bioactivity(target, threshold, max_compounds)`: Find compounds by target
**Usage**:
```python
from scripts.bioactivity_query import get_bioassay_summary, summarize_bioactivities
# Get bioactivity summary
summary = summarize_bioactivities(2244) # Aspirin
print(f"Total assays: {summary['total_assays']}")
print(f"Active: {summary['active']}, Inactive: {summary['inactive']}")
```
## API Rate Limits and Best Practices
**Rate Limits**:
- Maximum 5 requests per second
- Maximum 400 requests per minute
- Maximum 300 seconds running time per minute
**Best Practices**:
1. **Use CIDs for repeated queries**: CIDs are more efficient than names or structures
2. **Cache results locally**: Store frequently accessed data
3. **Batch requests**: Combine multiple queries when possible
4. **Implement delays**: Add 0.2-0.3 second delays between requests
5. **Handle errors gracefully**: Check for HTTP errors and missing data
6. **Use PubChemPy**: Higher-level abstraction handles many edge cases
7. **Leverage asynchronous pattern**: For large similarity/substructure searches
8. **Specify MaxRecords**: Limit results to avoid timeouts
**Error Handling**:
```python
from pubchempy import BadRequestError, NotFoundError, TimeoutError
try:
compound = pcp.get_compounds('query', 'name')[0]
except NotFoundError:
print("Compound not found")
except BadRequestError:
print("Invalid request format")
except TimeoutError:
print("Request timed out - try reducing scope")
except IndexError:
print("No results returned")
```
## Common Workflows
### Workflow 1: Chemical Identifier Conversion Pipeline
Convert between different chemical identifiers:
```python
import pubchempy as pcp
# Start with any identifier type
compound = pcp.get_compounds('caffeine', 'name')[0]
# Extract all identifier formats
identifiers = {
'CID': compound.cid,
'Name': compound.iupac_name,
'SMILES': compound.canonical_smiles,
'InChI': compound.inchi,
'InChIKey': compound.inchikey,
'Formula': compound.molecular_formula
}
```
### Workflow 2: Drug-Like Property Screening
Screen compounds using Lipinski's Rule of Five:
```python
import pubchempy as pcp
def check_drug_likeness(compound_name):
compound = pcp.get_compounds(compound_name, 'name')[0]
# Lipinski's Rule of Five
rules = {
'MW <= 500': compound.molecular_weight <= 500,
'LogP <= 5': compound.xlogp <= 5 if compound.xlogp else None,
'HBD <= 5': compound.h_bond_donor_count <= 5,
'HBA <= 10': compound.h_bond_acceptor_count <= 10
}
violations = sum(1 for v in rules.values() if v is False)
return rules, violations
rules, violations = check_drug_likeness('aspirin')
print(f"Lipinski violations: {violations}")
```
### Workflow 3: Finding Similar Drug Candidates
Identify structurally similar compounds to a known drug:
```python
import pubchempy as pcp
# Start with known drug
reference_drug = pcp.get_compounds('imatinib', 'name')[0]
reference_smiles = reference_drug.canonical_smiles
# Find similar compounds
similar = pcp.get_compounds(
reference_smiles,
'smiles',
searchtype='similarity',
Threshold=85,
MaxRecords=20
)
# Filter by drug-like properties
candidates = []
for comp in similar:
if comp.molecular_weight and 200 <= comp.molecular_weight <= 600:
if comp.xlogp and -1 <= comp.xlogp <= 5:
candidates.append(comp)
print(f"Found {len(candidates)} drug-like candidates")
```
### Workflow 4: Batch Compound Property Comparison
Compare properties across multiple compounds:
```python
import pubchempy as pcp
import pandas as pd
compound_list = ['aspirin', 'ibuprofen', 'naproxen', 'celecoxib']
properties_list = []
for name in compound_list:
try:
compound = pcp.get_compounds(name, 'name')[0]
properties_list.append({
'Name': name,
'CID': compound.cid,
'Formula': compound.molecular_formula,
'MW': compound.molecular_weight,
'LogP': compound.xlogp,
'TPSA': compound.tpsa,
'HBD': compound.h_bond_donor_count,
'HBA': compound.h_bond_acceptor_count
})
except Exception as e:
print(f"Error processing {name}: {e}")
df = pd.DataFrame(properties_list)
print(df.to_string(index=False))
```
### Workflow 5: Substructure-Based Virtual Screening
Screen for compounds containing specific pharmacophores:
```python
import pubchempy as pcp
# Define pharmacophore (e.g., sulfonamide group)
pharmacophore_smiles = 'S(=O)(=O)N'
# Search for compounds containing this substructure
hits = pcp.get_compounds(
pharmacophore_smiles,
'smiles',
searchtype='substructure',
MaxRecords=100
)
# Further filter by properties
filtered_hits = [
comp for comp in hits
if comp.molecular_weight and comp.molecular_weight < 500
]
print(f"Found {len(filtered_hits)} compounds with desired substructure")
```
## Reference Documentation
For detailed API documentation, including complete property lists, URL patterns, advanced query options, and more examples, consult `references/api_reference.md`. This comprehensive reference includes:
- Complete PUG-REST API endpoint documentation
- Full list of available molecular properties
- Asynchronous request handling patterns
- PubChemPy API reference
- PUG-View API for annotations
- Common workflows and use cases
- Links to official PubChem documentation
## Troubleshooting
**Compound Not Found**:
- Try alternative names or synonyms
- Use CID if known
- Check spelling and chemical name format
**Timeout Errors**:
- Reduce MaxRecords parameter
- Add delays between requests
- Use CIDs instead of names for faster queries
**Empty Property Values**:
- Not all properties are available for all compounds
- Check if property exists before accessing: `if compound.xlogp:`
- Some properties only available for certain compound types
**Rate Limit Exceeded**:
- Implement delays (0.2-0.3 seconds) between requests
- Use batch operations where possible
- Consider caching results locally
**Similarity/Substructure Search Hangs**:
- These are asynchronous operations that may take 15-30 seconds
- PubChemPy handles polling automatically
- Reduce MaxRecords if timing out
## Additional Resources
- PubChem Home: https://pubchem.ncbi.nlm.nih.gov/
- PUG-REST Documentation: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest
- PUG-REST Tutorial: https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest-tutorial
- PubChemPy Documentation: https://pubchempy.readthedocs.io/
- PubChemPy GitHub: https://github.com/mcs07/PubChemPy