
Chembl Database
- 1.3k installs
- 2.6k repo stars
- Updated July 7, 2026
- google-deepmind/science-skills
chembl-database is a science-skills integration that lets AI coding agents query the ChEMBL REST API for chemical compounds, bioactivity data, protein targets, and assays from agent sessions.
About
chembl-database is a google-deepmind science-skills module for querying the ChEMBL database at https://www.ebi.ac.uk/chembl/api/data from Claude, Cursor, or Codex agents. It documents list, single, batch, and search endpoint patterns plus SMILES similarity search for molecules. Seven endpoints support free-text search—including activity, assay, molecule, and target—while standard JSON pagination uses limit and offset parameters. Developers reach for chembl-database when building cheminformatics features, drug-discovery tooling, or bioactivity lookups without hand-rolling ChEMBL API docs each time.
- Standard list, single, batch and search endpoints with limit/offset support
- Specialized similarity search using SMILES and similarity threshold
- Substructure search returning molecules containing a given chemical pattern
- Image generation endpoint for 2D molecular structures in SVG format
- Django-style filter operators including exact, iexact and contains
Chembl Database by the numbers
- 1,274 all-time installs (skills.sh)
- +171 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #353 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/google-deepmind/science-skills --skill chembl-databaseAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.3k |
|---|---|
| repo stars | ★ 2.6k |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 7, 2026 |
| Repository | google-deepmind/science-skills ↗ |
How do you query ChEMBL bioactivity data from an agent?
Query the ChEMBL database for chemical compounds, bioactivity data, targets, and assays directly from AI coding agents.
Who is it for?
Developers building cheminformatics or drug-discovery agents that need documented ChEMBL REST patterns for compounds, targets, and bioactivity pulls.
Skip if: Projects unrelated to chemical or bioactivity data that only need general SQL databases or non-EBI scientific APIs.
When should I use this skill?
A developer asks to look up ChEMBL compounds, bioactivity, targets, assays, or run SMILES similarity searches from an AI coding agent.
What you get
ChEMBL JSON records for molecules, targets, assays, activities, and similarity-ranked compound sets.
- ChEMBL JSON entity records
- similarity-ranked molecule sets
By the numbers
- Documents seven ChEMBL endpoints that support free-text search
- Base API URL https://www.ebi.ac.uk/chembl/api/data
Files
ChEMBL Database Query
Prerequisites
1. `uv`: Read the uv skill and follow its Setup instructions to ensure uv is installed and on PATH. 2. User Notification: If LICENSE_NOTIFICATION.txt does not already exist in this skill directory then (1) prominently notify the user to check the terms at https://chembl.gitbook.io/chembl-interface-documentation/about, then (2) create the file recording the notification text and timestamp.
Core Rules
- [!IMPORTANT] Use the Utility Scripts: You MUST ALWAYS use the provided
utility script scripts/chembl_api.py for all ChEMBL API interactions, including checking status. NEVER use curl or custom Python requests to query the ChEMBL API directly. This ensures rate limit is enfoced and also retries on network errors.
- Output to File (Required): The
--outputflag is required for every
subcommand. All JSON results are written to the specified file. After running the command, read the output file with jq or your own code to extract the data. List results are typically wrapped in a JSON array keyed by the endpoint name (e.g., molecules, activities).
- Notification: If this skill is used, ensure this is mentioned in the
output.
Utility Script
All ChEMBL API queries use one script with subcommands:
uv run scripts/chembl_api.py <subcommand> --output <file> [options]--------------------------------------------------------------------------------
1. Check API Status
uv run scripts/chembl_api.py status --output /tmp/status.json--------------------------------------------------------------------------------
2. Molecule Queries
Fetch by ChEMBL ID: bash uv run scripts/chembl_api.py molecule --id CHEMBL25 --output /tmp/mol.json
Search by name: bash uv run scripts/chembl_api.py molecule --search "aspirin" --limit 3 --output /tmp/mol_search.json
Batch fetch: bash uv run scripts/chembl_api.py molecule --ids "CHEMBL25;CHEMBL1642" --limit 10 --output /tmp/mol_batch.json
Filter by properties: bash uv run scripts/chembl_api.py molecule --filter molecule_properties__mw_freebase__lte=500 --limit 5 --output /tmp/mol_filter.json
Filter by range: bash uv run scripts/chembl_api.py molecule --filter molecule_properties__mw_freebase__range=150,200 --limit 5 --output /tmp/mol_range.json
Download SDF structure file: bash uv run scripts/chembl_api.py molecule --id CHEMBL25 --dl_format sdf --output /tmp/aspirin.sdf
Tip: SDF/MOL files can be passed directly to tools like PyMOL or RDKit for
3D visualization and analysis.
--------------------------------------------------------------------------------
3. Target Queries
Search for targets: bash uv run scripts/chembl_api.py target --search "EGFR" --limit 5 --output /tmp/targets.json
Fetch by ID: bash uv run scripts/chembl_api.py target --id CHEMBL203 --output /tmp/egfr.json
--------------------------------------------------------------------------------
4. Bioactivity Data
Fetch activity by ID: bash uv run scripts/chembl_api.py activity --id 31863 --output /tmp/act.json
Search activities: bash uv run scripts/chembl_api.py activity --search "EGFR" --limit 5 --output /tmp/act_search.json
Filter activities for a target: bash uv run scripts/chembl_api.py activity --filter target_chembl_id=CHEMBL203 standard_type=IC50 --limit 10 --output /tmp/egfr_ic50.json
Normalize bioactivity units to nM: bash uv run scripts/chembl_api.py activity --filter target_chembl_id=CHEMBL203 standard_type=IC50 --limit 5 --normalize --output /tmp/egfr_normalized.json
Important: Bioactivity values come in various units (nM, µM, pM). Use
--normalize to convert all values to nM for consistent comparison. Eachrecord will includenormalized_value_nMandnormalization_note.
--------------------------------------------------------------------------------
5. Drug Information
Fetch drug details: bash uv run scripts/chembl_api.py drug --id CHEMBL25 --output /tmp/drug.json
Drug indications: bash uv run scripts/chembl_api.py drug_indication --filter molecule_chembl_id=CHEMBL25 --limit 10 --output /tmp/indications.json
Filter indications by phase: bash uv run scripts/chembl_api.py drug_indication --filter molecule_chembl_id=CHEMBL25 max_phase_for_ind=4.0 --limit 10 --output /tmp/approved_indications.json
Drug warnings: bash uv run scripts/chembl_api.py drug_warning --limit 5 --output /tmp/warnings.json
Mechanisms of action: bash uv run scripts/chembl_api.py mechanism --filter molecule_chembl_id=CHEMBL25 --limit 5 --output /tmp/mech.json
--------------------------------------------------------------------------------
6. Structure-Based Searches
Note: Both similarity and substructure searches are performed
server-side on ChEMBL's pre-indexed database. They do not require a local
RDKit installation.
Similarity search (SMILES + threshold): bash uv run scripts/chembl_api.py similarity --smiles "CC(=O)Oc1ccccc1C(=O)O" --similarity 85 --limit 5 --output /tmp/similar.json
Substructure search (SMILES): bash uv run scripts/chembl_api.py substructure --smiles "c1ccccc1" --limit 5 --output /tmp/substruct.json
--------------------------------------------------------------------------------
7. Compound Image
Download a 2D structure image (SVG by default, scalable for publication):
uv run scripts/chembl_api.py image --id CHEMBL25 --output /tmp/chembl25.svgOptions:
-
--dimensions: Image size in pixels (max 500, default 500). -
--engine: Rendering engine (default: rdkit). -
--img_format: Output format —svg(default, vector) orpng(raster).
--------------------------------------------------------------------------------
8. Cross-Referencing with Other Databases
ChEMBL integrates with UniProt, Ensembl, PubChem, and other databases. Common cross-referencing patterns:
Find a ChEMBL target from a UniProt accession: bash uv run scripts/chembl_api.py target --filter target_components__accession=P00533 --limit 5 --output /tmp/uniprot_target.json
Resolve any ChEMBL ID to its entity type: bash uv run scripts/chembl_api.py chembl_id_lookup --id CHEMBL203 --output /tmp/lookup.json
Look up cross-reference sources: bash uv run scripts/chembl_api.py xref_source --limit 10 --output /tmp/xrefs.json
Tip: Use the target_component endpoint to find UniProt accessions, genenames, and protein sequences for any ChEMBL target.
--------------------------------------------------------------------------------
9. Pagination
All list endpoints support --limit and --offset for pagination:
# First page: 2 results starting at offset 0
uv run scripts/chembl_api.py molecule --limit 2 --offset 0 --output /tmp/page1.json
# Second page: next 2 results starting at offset 2
uv run scripts/chembl_api.py molecule --limit 2 --offset 2 --output /tmp/page2.jsonThe response includes page_meta with total_count, limit, offset, next, and previous links. Use successive --offset values to page through large result sets.
--------------------------------------------------------------------------------
10. Other Endpoints
All remaining endpoints follow the same pattern:
uv run scripts/chembl_api.py <subcommand> --output <file> [--id ID | --ids ID1;ID2 | --search QUERY] [--limit N] [--offset N] [--filter KEY=VAL ...]Key subcommands at a glance:
-
molecule(searchable: true): Molecules/compounds — the primary entry point -
target(searchable: true): Drug targets (proteins, organisms, etc.) -
activity(searchable: true): Bioactivity data (IC50, Ki, EC50, etc.) -
drug(searchable: false): Approved drugs -
mechanism(searchable: false): Mechanisms of action -
assay(searchable: true): Assay descriptions -
similarity(searchable: false): Similarity search (special) -
substructure(searchable: false): Substructure search (special) -
image(searchable: false): Compound image download (special)
Full subcommand list:
-
activity_supp(searchable: false): Supplementary activity data -
assay_class(searchable: false): Assay classifications -
atc_class(searchable: false): ATC drug classifications -
binding_site(searchable: false): Binding site information -
biotherapeutic(searchable: false): Biotherapeutic molecules -
cell_line(searchable: false): Cell line details -
chembl_id_lookup(searchable: true): ChEMBL ID resolution -
chembl_release(searchable: false): Database release info -
compound_record(searchable: false): Compound records -
compound_structural_alert(searchable: false): Structural alerts -
document(searchable: true): Literature documents -
document_similarity(searchable: false): Document similarity -
drug_indication(searchable: false): Drug indications -
drug_warning(searchable: false): Drug safety warnings -
go_slim(searchable: false): GO slim terms -
metabolism(searchable: false): Metabolism data -
molecule_form(searchable: false): Molecule forms (salts/parents) -
organism(searchable: false): Organisms -
protein_classification(searchable: true): Protein classifications -
source(searchable: false): Data sources -
target_component(searchable: false): Target protein components -
target_relation(searchable: false): Target relationships -
tissue(searchable: false): Tissue types -
xref_source(searchable: false): Cross-reference sources -
status(searchable: false): API status check (special)
Common Options
-
--output FILE: Required. Output file path for JSON results. -
--id ID: Fetch a single record by ID. -
--ids ID1;ID2;...: Batch fetch multiple records. -
--search QUERY: Free-text search (only for searchable endpoints, marked
✓).
-
--limit N: Max results to return (default: 5). -
--offset N: Pagination offset. -
--filter KEY=VAL: Filter parameters (can specify multiple). -
--normalize: (activity only) Normalize values to nM. -
--dl_format sdf|mol: (molecule only) Download structure file.
Reference
- API Endpoints Reference: See
references/api_endpoints.md for the full list of endpoints and filter operators.
Workflow
1. Use status --output /tmp/status.json to verify the API is available. 2. Search for targets, molecules, or drugs using the relevant subcommand. 3. Read the output JSON file to extract IDs and data. 4. Use IDs from search results to fetch detailed records. 5. Query activity with filters to get bioactivity data for targets/molecules. Use --normalize when comparing values across studies. 6. Use similarity or substructure for server-side structure-based queries. 7. Download compound images with image or structure files with molecule --dl_format sdf. 8. Use target --filter target_components__accession=<UniProt> to cross- reference with UniProt.
ChEMBL API Endpoints Reference
Base URL: https://www.ebi.ac.uk/chembl/api/data
Standard Endpoint Patterns
Most endpoints support:
- List:
GET /<endpoint>.json?limit=N&offset=M - Single:
GET /<endpoint>/<ID>.json - Batch:
GET /<endpoint>/set/<ID1>;<ID2>.json - Search:
GET /<endpoint>/search.json?q=<query>(only selected endpoints)
Searchable Endpoints
Only these endpoints support free-text search (?q=):
activityassaychembl_id_lookupdocumentmoleculeprotein_classificationtarget
Special Endpoints
Similarity Search
GET /similarity/<SMILES>/<threshold>.json
Returns molecules similar to the given SMILES above the threshold (0-100).
Substructure Search
GET /substructure/<SMILES>.json
Returns molecules containing the given substructure.
Image
GET /image/<ChEMBL_ID_or_InChI_Key>
Returns a 2D structure image (SVG). Parameters:
engine— rendering toolkit (default: rdkit)dimensions— image size in pixels (max 500, default: 500)ignoreCoords— recompute 2D coordinates
Status
GET /status.json
Returns API status information.
Filter Operators
ChEMBL supports Django-style filter operators as query parameters:
| Operator | Description | Example |
|---|---|---|
| (none) | Exact match | molecule_chembl_id=CHEMBL25 |
__exact | Exact match | pref_name__exact=Aspirin |
__iexact | Case-insensitive exact | pref_name__iexact=aspirin |
__contains | Substring match | pref_name__contains=aspirin |
__icontains | Case-insensitive substring | pref_name__icontains=aspirin |
__startswith | Prefix match | pref_name__startswith=Asp |
__endswith | Suffix match | pref_name__endswith=rin |
__gt | Greater than | standard_value__gt=100 |
__gte | Greater than or equal | standard_value__gte=100 |
__lt | Less than | standard_value__lt=100 |
__lte | Less than or equal | standard_value__lte=100 |
__in | Value in list | molecule_type__in=Small molecule,Antibody |
__isnull | Null check | pchembl_value__isnull=false |
__range | Value in range | mw_freebase__range=200,500 |
__flexmatch | SMILES structure match | canonical_smiles__flexmatch=<SMILES> |
Common ID Formats
| Resource | ID Format | Example |
|---|---|---|
| Molecule | CHEMBLNNN | CHEMBL25 |
| Target | CHEMBLNNN | CHEMBL203 |
| Assay | CHEMBLNNN | CHEMBL615819 |
| Document | CHEMBLNNN | CHEMBL1127557 |
| Activity | Numeric | 31863 |
| ATC Class | ATC code | N02BA01 |
Pagination
All list endpoints return paginated results. Use limit and offset:
?limit=20&offset=0— first 20 results?limit=20&offset=20— next 20 results
The response includes page_meta with total_count, limit, offset, next, and previous links.
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ChEMBL REST API client CLI.
CLI tool covering all ChEMBL web services API endpoints. Writes JSON output to
a file specified by --output. Enforces rate limiting between requests and
retries on transient errors (HTTP 429, 503) with exponential backoff.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any
import urllib.parse
from science_skills.skills.scienceskillscommon import http_client
BASE_URL = "https://www.ebi.ac.uk/chembl/api/data"
_CLIENT = http_client.HttpClient(BASE_URL, qps=5.0)
_LICENSE_NOTICE = (
"Data from the ChEMBL Database. You MUST notify the user"
" that this data comes from ChEMBL and advise them to"
" review the ChEMBL licensing terms."
)
SEARCHABLE_ENDPOINTS = frozenset([
"activity",
"assay",
"chembl_id_lookup",
"document",
"molecule",
"protein_classification",
"target",
])
ENDPOINT_MAP = {
"activity": "activity",
"activity_supp": "activity_supplementary_data_by_activity",
"assay": "assay",
"assay_class": "assay_class",
"atc_class": "atc_class",
"binding_site": "binding_site",
"biotherapeutic": "biotherapeutic",
"cell_line": "cell_line",
"chembl_id_lookup": "chembl_id_lookup",
"chembl_release": "chembl_release",
"compound_record": "compound_record",
"compound_structural_alert": "compound_structural_alert",
"document": "document",
"document_similarity": "document_similarity",
"drug": "drug",
"drug_indication": "drug_indication",
"drug_warning": "drug_warning",
"go_slim": "go_slim",
"mechanism": "mechanism",
"metabolism": "metabolism",
"molecule": "molecule",
"molecule_form": "molecule_form",
"organism": "organism",
"protein_classification": "protein_classification",
"source": "source",
"target": "target",
"target_component": "target_component",
"target_relation": "target_relation",
"tissue": "tissue",
"xref_source": "xref_source",
}
UNIT_CONVERSION_TO_NM = {
"nm": 1.0,
"um": 1e3,
"µm": 1e3,
"mm": 1e6,
"m": 1e9,
"pm": 1e-3,
"fm": 1e-6,
}
def _write_json(data: Any, output_path: str) -> None:
"""Write a Python object as indented JSON to the given file path.
Creates parent directories if they do not exist. Prints a short
confirmation to stdout so the agent knows where the file was saved.
Args:
data: The Python object to serialize to JSON.
output_path: The file path to write the JSON output to.
"""
out_dir = os.path.dirname(output_path)
if out_dir:
os.makedirs(out_dir, exist_ok=True)
if isinstance(data, dict):
data["_license_notice"] = (
"Data from the ChEMBL Database. Please review the licensing terms at"
" https://www.ebi.ac.uk/chembl/"
)
with open(output_path, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
print(
json.dumps(
{
"status": "success",
"output_file": output_path,
"size_bytes": os.path.getsize(output_path),
"license_notice": _LICENSE_NOTICE,
},
indent=2,
)
)
def _make_request(url: str) -> dict[str, Any]:
"""Send an HTTP GET to *url* and return the parsed JSON response.
Uses HttpClient for retry logic. Non-retryable HTTP errors
are returned as a dict with ``status=error``.
Args:
url: The URL to send the HTTP GET request to.
Returns:
The parsed JSON response as a dict or list, or a dict with
``status=error`` and a ``message`` key on failure.
"""
try:
return _CLIENT.fetch_json(url)
except http_client.HttpError as e:
return {
"status": "error",
"http_code": e.status_code,
"message": str(e),
"detail": (
e.body.decode("utf-8", errors="replace")[:500] if e.body else ""
),
}
except Exception as e:
return {
"status": "error",
"message": f"Network error: {e}",
}
def _download_binary(url: str, output_path: str) -> dict[str, Any]:
"""Download binary content from *url* and save to *output_path*.
Used for image and structure-file downloads. Uses HttpClient
for retry logic.
Args:
url: The URL to download binary content from.
output_path: The file path to save the downloaded content to.
Returns:
A dict with ``status=success``, ``message``, and ``size_bytes`` on
success, or ``status=error`` and ``message`` on failure.
"""
try:
content = _CLIENT.fetch_bytes(url)
out_dir = os.path.dirname(output_path)
if out_dir:
os.makedirs(out_dir, exist_ok=True)
with open(output_path, "wb") as f:
f.write(content)
return {
"status": "success",
"message": f"Saved to {output_path}",
"size_bytes": len(content),
"license_notice": _LICENSE_NOTICE,
}
except Exception as e:
return {"status": "error", "message": f"File system/Network error: {e}"}
def _build_url(
endpoint: str,
resource_id: str | None = None,
ids_list: str | None = None,
search: str | None = None,
filters: list[str] | None = None,
limit: int | None = None,
offset: int | None = None,
) -> str:
"""Construct a ChEMBL API URL from components.
Handles single-resource, batch (set/), search, filter, and
pagination parameters.
Args:
endpoint: The ChEMBL API endpoint name (e.g., "molecule").
resource_id: A single ChEMBL ID or numeric ID.
ids_list: Semicolon-separated string of IDs for batch fetching.
search: Free-text search query string.
filters: List of "KEY=VALUE" filter strings.
limit: Maximum number of results to return.
offset: Pagination offset.
Returns:
A complete URL string for the ChEMBL API request.
Raises:
SystemExit: If a filter string does not contain '='.
"""
parts = [BASE_URL, endpoint]
if resource_id:
parts.append(resource_id)
elif ids_list:
parts.append("set/" + ids_list)
elif search:
parts.append("search")
url = "/".join(parts) + ".json"
params: dict[str, Any] = {}
if search:
params["q"] = search
if limit is not None:
params["limit"] = limit
if offset is not None:
params["offset"] = offset
if filters:
for filt in filters:
if "=" not in filt:
print(
json.dumps(
{
"status": "error",
"message": (
f"Invalid filter '{filt}': expected KEY=VALUE format."
),
},
indent=2,
),
)
sys.exit(1)
key, val = filt.split("=", 1)
params[key] = val
if params:
url += "?" + urllib.parse.urlencode(params)
return url
def _normalize_activity(record: dict[str, Any]) -> dict[str, Any]:
"""Add normalised nM value to a single activity record.
Reads ``standard_value`` and ``standard_units``, converts to nM
using UNIT_CONVERSION_TO_NM, and adds ``normalized_value_nM`` and
``normalization_note`` keys to *record*.
Args:
record: An activity record dict containing ``standard_value`` and
``standard_units`` keys.
Returns:
The mutated *record* dict with ``normalized_value_nM`` and
``normalization_note`` keys added.
"""
units = (record.get("standard_units") or "").strip().lower()
value = record.get("standard_value")
if value is None or units not in UNIT_CONVERSION_TO_NM:
record["normalized_value_nM"] = None
record["normalization_note"] = (
f"Cannot normalize: units='{record.get('standard_units')}'"
if value is not None
else "No standard_value"
)
return record
try:
nm_value = float(value) * UNIT_CONVERSION_TO_NM[units]
record["normalized_value_nM"] = nm_value
record["normalization_note"] = (
f"Converted {value} {record.get('standard_units')} -> {nm_value} nM"
)
except (ValueError, TypeError):
record["normalized_value_nM"] = None
record["normalization_note"] = f"Cannot convert value: {value}"
return record
def cmd_generic(args: argparse.Namespace) -> None:
"""Handle all standard endpoint subcommands (molecule, target, etc.).
Builds the URL, makes the request, optionally normalises activity
values, and writes JSON output to args.output.
Args:
args: Parsed command-line arguments. Expected attributes: command, search,
id, ids, filter, limit, offset, output, and optionally normalize (for
activity endpoint).
"""
api_endpoint = ENDPOINT_MAP[args.command]
can_search = api_endpoint in SEARCHABLE_ENDPOINTS
if args.search and not can_search:
searchable_list = ", ".join(sorted(SEARCHABLE_ENDPOINTS))
error = {
"status": "error",
"message": f"Search is not supported for endpoint '{args.command}'.",
"suggestion": (
f"Use --filter instead (e.g. {args.command} --filter"
" KEY=VALUE), or search a supported endpoint:"
f" {searchable_list}."
),
}
_write_json(error, args.output)
sys.exit(1)
url = _build_url(
api_endpoint,
resource_id=args.id,
ids_list=args.ids,
search=args.search if can_search else None,
filters=args.filter,
limit=args.limit if not args.id else None,
offset=args.offset if not args.id else None,
)
result = _make_request(url)
normalize = getattr(args, "normalize", False)
if normalize and api_endpoint == "activity":
if isinstance(result, dict) and "activities" in result:
result["activities"] = [
_normalize_activity(r) for r in result["activities"]
]
elif isinstance(result, dict) and "standard_value" in result:
result = _normalize_activity(result)
_write_json(result, args.output)
def cmd_status(args: argparse.Namespace) -> None:
"""Check ChEMBL API status and write the result to args.output.
Args:
args: Parsed command-line arguments. Expected attribute: output.
"""
url = f"{BASE_URL}/status.json"
result = _make_request(url)
_write_json(result, args.output)
def cmd_similarity(args: argparse.Namespace) -> None:
"""Run a server-side similarity search against the ChEMBL database.
Requires --smiles and --similarity (threshold 0-100). Writes
matching molecules to args.output.
Args:
args: An argparse.Namespace object containing the parsed command-line
arguments. Expected attributes: smiles, similarity, limit, offset, output.
"""
smiles_encoded = urllib.parse.quote(args.smiles, safe="")
url = f"{BASE_URL}/similarity/{smiles_encoded}/{args.similarity}.json"
params: dict[str, Any] = {}
if args.limit:
params["limit"] = args.limit
if args.offset:
params["offset"] = args.offset
if params:
url += "?" + urllib.parse.urlencode(params)
result = _make_request(url)
_write_json(result, args.output)
def cmd_substructure(args: argparse.Namespace) -> None:
"""Run a server-side substructure search against ChEMBL.
Requires --smiles. Writes matching molecules to args.output.
Args:
args: An argparse.Namespace object containing the parsed command-line
arguments. Expected attributes: smiles, limit, offset, and output.
"""
smiles_encoded = urllib.parse.quote(args.smiles, safe="")
url = f"{BASE_URL}/substructure/{smiles_encoded}.json"
params: dict[str, Any] = {}
if args.limit:
params["limit"] = args.limit
if args.offset:
params["offset"] = args.offset
if params:
url += "?" + urllib.parse.urlencode(params)
result = _make_request(url)
_write_json(result, args.output)
def cmd_image(args: argparse.Namespace) -> None:
"""Download a compound 2D structure image (SVG or PNG).
Binary content is saved to args.output. A JSON status summary
is printed to stdout.
Args:
args: An argparse.Namespace object containing the parsed command-line
arguments. Expected attributes: id, output, dimensions, engine, img_format
"""
url = f"{BASE_URL}/image/{args.id}"
params: dict[str, Any] = {}
if args.dimensions:
params["dimensions"] = args.dimensions
if args.engine:
params["engine"] = args.engine
if args.img_format:
params["format"] = args.img_format
if params:
url += "?" + urllib.parse.urlencode(params)
result = _download_binary(url, args.output)
print(json.dumps(result, indent=2))
def cmd_molecule_download(args: argparse.Namespace) -> None:
"""Download a molecule structure file in SDF or MOL format.
Requires --id and --dl_format. Binary content is saved to
args.output (or defaults to <CHEMBL_ID>.<format>).
Args:
args: An argparse.Namespace object containing the parsed command-line
arguments. Expected attributes: id, dl_format, output.
"""
fmt = args.dl_format
chembl_id = args.id
if not chembl_id:
error = {
"status": "error",
"message": "--id is required for --dl_format",
}
print(json.dumps(error, indent=2))
sys.exit(1)
url = f"{BASE_URL}/molecule/{chembl_id}.{fmt}"
output = args.output if args.output else f"{chembl_id}.{fmt}"
result = _download_binary(url, output)
print(json.dumps(result, indent=2))
def _add_common_args(parser: argparse.ArgumentParser) -> None:
"""Add shared arguments (--id, --ids, --search, etc.) to a subparser.
Args:
parser: The argparse subparser to add arguments to.
"""
parser.add_argument("--id", type=str, help="Single ChEMBL ID or numeric ID")
parser.add_argument(
"--ids",
type=str,
help="Semicolon-separated list of IDs for batch fetch",
)
parser.add_argument(
"--search",
type=str,
help="Free-text search query (only for searchable endpoints)",
)
parser.add_argument(
"--limit",
type=int,
default=5,
help="Max results to return (default: 5)",
)
parser.add_argument(
"--offset",
type=int,
default=None,
help="Pagination offset",
)
parser.add_argument(
"--filter",
type=str,
nargs="*",
help="Filter as KEY=VALUE pairs",
)
parser.add_argument(
"--output",
type=str,
required=True,
help="Output JSON file path (required)",
)
def build_parser() -> argparse.ArgumentParser:
"""Build the top-level argparse parser with all subcommands.
Creates subparsers for every ChEMBL endpoint plus the special
status, similarity, substructure, and image subcommands.
Returns:
An argparse.ArgumentParser instance configured with all ChEMBL API
subcommands.
"""
parser = argparse.ArgumentParser(
description=(
"ChEMBL REST API client. Query bioactive molecules, targets,"
" activities, and more. All output is written to --output file."
)
)
subparsers = parser.add_subparsers(
dest="command", help="API endpoint to query"
)
for cmd_name in sorted(ENDPOINT_MAP.keys()):
api_name = ENDPOINT_MAP[cmd_name]
searchable = " (searchable)" if api_name in SEARCHABLE_ENDPOINTS else ""
sp = subparsers.add_parser(
cmd_name, help=f"Query {api_name} endpoint{searchable}"
)
_add_common_args(sp)
if cmd_name == "activity":
sp.add_argument(
"--normalize",
action="store_true",
help="Normalize bioactivity values to nM",
)
if cmd_name == "molecule":
sp.add_argument(
"--dl_format",
type=str,
choices=["sdf", "mol"],
help="Download molecule structure file (SDF or MOL)",
)
sp.set_defaults(func=cmd_generic)
sp_status = subparsers.add_parser("status", help="Check ChEMBL API status")
sp_status.add_argument(
"--output",
type=str,
required=True,
help="Output JSON file path (required)",
)
sp_status.set_defaults(func=cmd_status)
sp_sim = subparsers.add_parser(
"similarity", help="Server-side similarity search by SMILES"
)
sp_sim.add_argument("--smiles", type=str, required=True, help="SMILES string")
sp_sim.add_argument(
"--similarity",
type=int,
required=True,
help="Similarity threshold (0-100)",
)
sp_sim.add_argument(
"--limit",
type=int,
default=5,
help="Max results (default: 5)",
)
sp_sim.add_argument(
"--offset",
type=int,
default=None,
help="Pagination offset",
)
sp_sim.add_argument(
"--output",
type=str,
required=True,
help="Output JSON file path (required)",
)
sp_sim.set_defaults(func=cmd_similarity)
sp_sub = subparsers.add_parser(
"substructure", help="Server-side substructure search by SMILES"
)
sp_sub.add_argument("--smiles", type=str, required=True, help="SMILES string")
sp_sub.add_argument(
"--limit",
type=int,
default=5,
help="Max results (default: 5)",
)
sp_sub.add_argument(
"--offset",
type=int,
default=None,
help="Pagination offset",
)
sp_sub.add_argument(
"--output",
type=str,
required=True,
help="Output JSON file path (required)",
)
sp_sub.set_defaults(func=cmd_substructure)
sp_img = subparsers.add_parser(
"image", help="Download compound image (SVG by default)"
)
sp_img.add_argument(
"--id",
type=str,
required=True,
help="ChEMBL ID or InChI Key",
)
sp_img.add_argument(
"--output",
type=str,
required=True,
help="Output file path",
)
sp_img.add_argument(
"--dimensions",
type=int,
help="Image size in pixels (max 500, default 500)",
)
sp_img.add_argument(
"--engine",
type=str,
default=None,
help="Rendering engine (default: rdkit)",
)
sp_img.add_argument(
"--img_format",
type=str,
choices=["svg", "png"],
default=None,
help="Image format: svg (default) or png",
)
sp_img.set_defaults(func=cmd_image)
return parser
if __name__ == "__main__":
main_parser = build_parser()
main_args = main_parser.parse_args()
if not main_args.command:
main_parser.print_help()
sys.exit(1)
if getattr(main_args, "dl_format", None):
cmd_molecule_download(main_args)
else:
main_args.func(main_args)
Related skills
How it compares
Choose chembl-database for EBI ChEMBL compound and bioactivity REST access rather than genomic variant skills when the data need is chemical not genetic.
FAQ
Which ChEMBL endpoints support free-text search?
chembl-database documents seven searchable ChEMBL endpoints—activity, assay, chembl_id_lookup, document, molecule, protein_classification, and target—using search.json with a q parameter.
How does chembl-database perform similarity searches?
chembl-database uses GET /similarity/<SMILES>/<threshold>.json on the ChEMBL API to return molecules similar to a given SMILES string above the specified threshold.
Is Chembl Database safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.