Source: https://github.com/aipoch/medical-research-skills
When to Use
- You need to fetch KEGG pathway, gene, compound, enzyme, disease, or drug records directly from the KEGG REST API.
- You want to perform gene ↔ pathway mapping (e.g., building inputs for pathway enrichment or reporting).
- You need cross-references between KEGG databases (e.g., pathway → genes, gene → KO, pathway → compounds).
- You must convert identifiers between KEGG and external databases (e.g., KEGG gene → NCBI Gene ID / UniProt; KEGG compound → PubChem).
- You need drug–drug interaction (DDI) lookups for KEGG drug IDs.
Note: KEGG REST access is intended for academic use. Non-academic/commercial use may require a separate KEGG license.
Key Features
- Full coverage of core KEGG REST operations via Python helpers:
kegg_info (database metadata)
kegg_list (catalog listing)
kegg_find (keyword/property search)
kegg_get (entry retrieval; sequences/structures/images)
kegg_conv (ID conversion)
kegg_link (cross-database linking)
kegg_ddi (drug–drug interactions)
- Supports common KEGG identifiers and formats:
- Pathways:
map00010, hsa00010
- Genes:
hsa:10458
- Compounds:
cpd:C00002
- Drugs:
dr:D00001
- Enzymes:
ec:1.1.1.1
- KO:
ko:K00001
- Output format options for
kegg_get: aaseq, ntseq, mol, kcf, image, kgml, json (some formats are single-entry only).
Dependencies
- Python
>=3.9
requests >=2.31.0
Example Usage
"""
End-to-end example:
1) Find a human gene by keyword
2) Link the gene to pathways
3) Retrieve one pathway entry
4) Convert the gene ID to UniProt
"""
from scripts.kegg_api import kegg_find, kegg_link, kegg_get, kegg_conv
# 1) Search for a gene keyword in KEGG GENES
hits = kegg_find("genes", "p53")
print("FIND results (first lines):")
print("\n".join(hits.splitlines()[:5]), "\n")
# Choose a known KEGG gene ID for TP53 (human)
gene_id = "hsa:7157"
# 2) Link gene -> pathways
pathway_links = kegg_link("pathway", gene_id)
print("LINK gene -> pathways (first lines):")
print("\n".join(pathway_links.splitlines()[:5]), "\n")
# Parse the first pathway ID from the link output
# Typical line format: path:hsaXXXXX<TAB>hsa:7157
first_line = next((ln for ln in pathway_links.splitlines() if ln.strip()), None)
if not first_line:
raise RuntimeError("No pathways returned for the gene ID.")
path_id = first_line.split("\t")[0].replace("path:", "")
print("Selected pathway:", path_id, "\n")
# 3) Retrieve the pathway entry (flat text)
pathway_entry = kegg_get(path_id)
print("GET pathway entry (first 30 lines):")
print("\n".join(pathway_entry.splitlines()[:30]), "\n")
# 4) Convert KEGG gene ID -> UniProt
uniprot_map = kegg_conv("uniprot", gene_id)
print("CONV KEGG -> UniProt:")
print(uniprot_map)
Implementation Details
API-to-function mapping
This skill wraps KEGG REST endpoints into Python functions (see scripts/kegg_api.py):
kegg_info(database_or_org)
Retrieves database or organism metadata (release info, counts, etc.).
kegg_list(database, organism=None)
Lists entries in a database; optionally scoped to an organism (e.g., ("pathway", "hsa")).
Also supports listing explicit IDs (batch-style) when passed as a single string.
kegg_find(database, query, option=None)
Searches by keyword or by chemical properties. Common option values:
formula (exact match)
exact_mass (range like 300-310)
mol_weight (range)
kegg_get(entry_ids, option=None)
Retrieves full entries or specific formats:
- Sequences:
aaseq, ntseq
- Structures:
mol, kcf
- Pathway assets:
image (PNG), kgml (XML), json (Pathway JSON)
Batching rules:
- Most operations allow up to 10 entries per request.
image, kgml, and json typically allow only 1 entry per request.
kegg_conv(target_db, source)
Converts IDs between KEGG and external databases (e.g., uniprot, ncbi-geneid, pubchem, chebi).
Output is tab-delimited pairs: source_id<TAB>target_id.
kegg_link(target_db, source)
Cross-references entries across KEGG databases (e.g., gene → pathway, pathway → compound, gene → KO).
kegg_ddi(drug_ids)
Returns known drug–drug interactions for one or more KEGG drug IDs (up to typical batch limits).
Practical constraints and error handling
- Entry limits: Prefer chunking lists into batches of ≤10 IDs; enforce single-entry calls for
image/kgml/json.
- HTTP status codes: Treat non-200 responses as failures; common issues include:
400 (bad request / malformed parameters)
404 (unknown database or entry ID)
- Rate behavior: KEGG does not publish strict rate limits; avoid high-frequency polling and add backoff/retry for robustness.
Reference documentation
For detailed endpoint syntax, database lists, and species codes, consult:
references/kegg_reference.md
1---2name: kegg-database3description: Direct access to KEGG via the REST API for academic-only pathway/gene/compound/drug queries; use when you need precise HTTP-level control or targeted KEGG ID mapping.4license: MIT5---6> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)78## When to Use910- You need to fetch **KEGG pathway, gene, compound, enzyme, disease, or drug** records directly from the **KEGG REST API**.11- You want to perform **gene ↔ pathway** mapping (e.g., building inputs for pathway enrichment or reporting).12- You need **cross-references** between KEGG databases (e.g., pathway → genes, gene → KO, pathway → compounds).13- You must **convert identifiers** between KEGG and external databases (e.g., KEGG gene → NCBI Gene ID / UniProt; KEGG compound → PubChem).14- You need **drug–drug interaction (DDI)** lookups for KEGG drug IDs.1516> Note: KEGG REST access is intended for academic use. Non-academic/commercial use may require a separate KEGG license.1718## Key Features1920- Full coverage of core KEGG REST operations via Python helpers:21 - `kegg_info` (database metadata)22 - `kegg_list` (catalog listing)23 - `kegg_find` (keyword/property search)24 - `kegg_get` (entry retrieval; sequences/structures/images)25 - `kegg_conv` (ID conversion)26 - `kegg_link` (cross-database linking)27 - `kegg_ddi` (drug–drug interactions)28- Supports common KEGG identifiers and formats:29 - Pathways: `map00010`, `hsa00010`30 - Genes: `hsa:10458`31 - Compounds: `cpd:C00002`32 - Drugs: `dr:D00001`33 - Enzymes: `ec:1.1.1.1`34 - KO: `ko:K00001`35- Output format options for `kegg_get`: `aaseq`, `ntseq`, `mol`, `kcf`, `image`, `kgml`, `json` (some formats are single-entry only).3637## Dependencies3839- Python `>=3.9`40- `requests >=2.31.0`4142## Example Usage4344```python45"""46End-to-end example:471) Find a human gene by keyword482) Link the gene to pathways493) Retrieve one pathway entry504) Convert the gene ID to UniProt51"""5253from scripts.kegg_api import kegg_find, kegg_link, kegg_get, kegg_conv5455# 1) Search for a gene keyword in KEGG GENES56hits = kegg_find("genes", "p53")57print("FIND results (first lines):")58print("\n".join(hits.splitlines()[:5]), "\n")5960# Choose a known KEGG gene ID for TP53 (human)61gene_id = "hsa:7157"6263# 2) Link gene -> pathways64pathway_links = kegg_link("pathway", gene_id)65print("LINK gene -> pathways (first lines):")66print("\n".join(pathway_links.splitlines()[:5]), "\n")6768# Parse the first pathway ID from the link output69# Typical line format: path:hsaXXXXX<TAB>hsa:715770first_line = next((ln for ln in pathway_links.splitlines() if ln.strip()), None)71if not first_line:72 raise RuntimeError("No pathways returned for the gene ID.")7374path_id = first_line.split("\t")[0].replace("path:", "")75print("Selected pathway:", path_id, "\n")7677# 3) Retrieve the pathway entry (flat text)78pathway_entry = kegg_get(path_id)79print("GET pathway entry (first 30 lines):")80print("\n".join(pathway_entry.splitlines()[:30]), "\n")8182# 4) Convert KEGG gene ID -> UniProt83uniprot_map = kegg_conv("uniprot", gene_id)84print("CONV KEGG -> UniProt:")85print(uniprot_map)86```8788## Implementation Details8990### API-to-function mapping9192This skill wraps KEGG REST endpoints into Python functions (see `scripts/kegg_api.py`):9394- `kegg_info(database_or_org)` 95 Retrieves database or organism metadata (release info, counts, etc.).9697- `kegg_list(database, organism=None)` 98 Lists entries in a database; optionally scoped to an organism (e.g., `("pathway", "hsa")`). 99 Also supports listing explicit IDs (batch-style) when passed as a single string.100101- `kegg_find(database, query, option=None)` 102 Searches by keyword or by chemical properties. Common `option` values:103 - `formula` (exact match)104 - `exact_mass` (range like `300-310`)105 - `mol_weight` (range)106107- `kegg_get(entry_ids, option=None)` 108 Retrieves full entries or specific formats:109 - Sequences: `aaseq`, `ntseq`110 - Structures: `mol`, `kcf`111 - Pathway assets: `image` (PNG), `kgml` (XML), `json` (Pathway JSON)112113 **Batching rules**:114 - Most operations allow up to **10 entries** per request.115 - `image`, `kgml`, and `json` typically allow **only 1 entry** per request.116117- `kegg_conv(target_db, source)` 118 Converts IDs between KEGG and external databases (e.g., `uniprot`, `ncbi-geneid`, `pubchem`, `chebi`). 119 Output is tab-delimited pairs: `source_id<TAB>target_id`.120121- `kegg_link(target_db, source)` 122 Cross-references entries across KEGG databases (e.g., gene → pathway, pathway → compound, gene → KO).123124- `kegg_ddi(drug_ids)` 125 Returns known drug–drug interactions for one or more KEGG drug IDs (up to typical batch limits).126127### Practical constraints and error handling128129- **Entry limits**: Prefer chunking lists into batches of ≤10 IDs; enforce single-entry calls for `image/kgml/json`.130- **HTTP status codes**: Treat non-200 responses as failures; common issues include:131 - `400` (bad request / malformed parameters)132 - `404` (unknown database or entry ID)133- **Rate behavior**: KEGG does not publish strict rate limits; avoid high-frequency polling and add backoff/retry for robustness.134135### Reference documentation136137For detailed endpoint syntax, database lists, and species codes, consult:138- `references/kegg_reference.md`