Source: https://github.com/aipoch/medical-research-skills
When to Use
- You need to search UniProtKB with Lucene-style queries (e.g., by gene name, organism, reviewed status).
- You want to fetch the full details of a specific protein entry by UniProt accession (e.g.,
P12345).
- You need to map identifiers between databases (e.g., gene names, Ensembl IDs, RefSeq IDs ↔ UniProt accessions).
- You are building pipelines that require automated protein annotation retrieval in JSON/TSV/FASTA formats.
- You need a lightweight client that talks directly to UniProt’s REST API without additional SDKs.
Key Features
- Protein search via UniProtKB REST endpoint using Lucene query syntax.
- Entry retrieval by accession with selectable output formats.
- Identifier mapping between supported source/target databases using UniProt ID mapping service.
- Format control (default
json) for consistent downstream parsing.
- Reference docs for query syntax and available API fields:
references/query_syntax.md
references/api_fields.md
Dependencies
- Python
>=3.8
requests >=2.31.0
Example Usage
import time
import requests
BASE = "https://rest.uniprot.org"
def search_protein(query: str, fmt: str = "json", size: int = 5):
"""
Search UniProtKB using Lucene-style query syntax.
"""
url = f"{BASE}/uniprotkb/search"
params = {"query": query, "format": fmt, "size": size}
r = requests.get(url, params=params, timeout=30)
r.raise_for_status()
return r.json() if fmt == "json" else r.text
def retrieve_entry(accession: str, fmt: str = "json"):
"""
Retrieve a UniProtKB entry by accession.
"""
url = f"{BASE}/uniprotkb/{accession}"
params = {"format": fmt}
r = requests.get(url, params=params, timeout=30)
r.raise_for_status()
return r.json() if fmt == "json" else r.text
def id_mapping(from_db: str, to_db: str, ids, poll_interval_s: float = 1.0):
"""
Map identifiers using UniProt ID Mapping.
ids can be a list of strings or a comma-separated string.
"""
if isinstance(ids, (list, tuple)):
ids = ",".join(ids)
# 1) Submit mapping job
submit_url = f"{BASE}/idmapping/run"
r = requests.post(
submit_url,
data={"from": from_db, "to": to_db, "ids": ids},
timeout=30,
)
r.raise_for_status()
job_id = r.json()["jobId"]
# 2) Poll job status
status_url = f"{BASE}/idmapping/status/{job_id}"
while True:
s = requests.get(status_url, timeout=30)
s.raise_for_status()
payload = s.json()
if payload.get("jobStatus") in (None, "FINISHED"):
break
if payload.get("jobStatus") == "FAILED":
raise RuntimeError(f"ID mapping failed: {payload}")
time.sleep(poll_interval_s)
# 3) Fetch results (JSON)
results_url = f"{BASE}/idmapping/results/{job_id}"
res = requests.get(results_url, params={"format": "json"}, timeout=30)
res.raise_for_status()
return res.json()
if __name__ == "__main__":
# Search example: human BRCA1
search = search_protein("gene:BRCA1 AND organism_id:9606", size=3)
print("Search results (first accessions):",
[item["primaryAccession"] for item in search.get("results", [])])
# Retrieve entry example
entry = retrieve_entry("P38398") # UniProt accession for human BRCA1 (example)
print("Entry primaryAccession:", entry.get("primaryAccession"))
print("Protein name:", entry.get("proteinDescription", {}).get("recommendedName", {}).get("fullName", {}).get("value"))
# ID mapping example: gene name -> UniProtKB
mapping = id_mapping(from_db="Gene_Name", to_db="UniProtKB", ids=["BRCA1"])
print("Mapping results keys:", mapping.keys())
Implementation Details
Search Protein
- Uses
GET /uniprotkb/search
- Key parameters:
query: Lucene-style query string (see references/query_syntax.md)
format: output format (default json)
- Optional common parameters:
size, fields, sort
- Returns parsed JSON when
format=json, otherwise raw text.
Retrieve Entry
- Uses
GET /uniprotkb/{accession}
- Key parameters:
accession: UniProt accession (e.g., P12345)
format: output format (default json)
- Suitable for fetching full record details for a known accession.
ID Mapping
- Uses UniProt asynchronous mapping workflow:
POST /idmapping/run with from, to, ids
- Poll
GET /idmapping/status/{jobId} until finished
- Fetch
GET /idmapping/results/{jobId}?format=json
ids accepts either a list or a comma-separated string.
- Recommended parameters:
poll_interval_s: controls polling frequency to avoid excessive requests.
from_db / to_db must match UniProt-supported database identifiers (consult UniProt mapping documentation as needed).
1---2name: uniprot-database-23description: Direct REST API access to UniProt for protein search, entry retrieval, and identifier mapping; use when you need programmatic UniProtKB queries or cross-database ID conversion.4license: MIT5author: AIPOCH6metadata:7 source: https://skillmd.com/skills/gabrielmoreira/uniprot-database-28---910> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)1112## When to Use1314- You need to search UniProtKB with Lucene-style queries (e.g., by gene name, organism, reviewed status).15- You want to fetch the full details of a specific protein entry by UniProt accession (e.g., `P12345`).16- You need to map identifiers between databases (e.g., gene names, Ensembl IDs, RefSeq IDs ↔ UniProt accessions).17- You are building pipelines that require automated protein annotation retrieval in JSON/TSV/FASTA formats.18- You need a lightweight client that talks directly to UniProt’s REST API without additional SDKs.1920## Key Features2122- **Protein search** via UniProtKB REST endpoint using Lucene query syntax.23- **Entry retrieval** by accession with selectable output formats.24- **Identifier mapping** between supported source/target databases using UniProt ID mapping service.25- **Format control** (default `json`) for consistent downstream parsing.26- **Reference docs** for query syntax and available API fields:27 - `references/query_syntax.md`28 - `references/api_fields.md`2930## Dependencies3132- Python `>=3.8`33- `requests >=2.31.0`3435## Example Usage3637```python38import time39import requests4041BASE = "https://rest.uniprot.org"4243def search_protein(query: str, fmt: str = "json", size: int = 5):44 """45 Search UniProtKB using Lucene-style query syntax.46 """47 url = f"{BASE}/uniprotkb/search"48 params = {"query": query, "format": fmt, "size": size}49 r = requests.get(url, params=params, timeout=30)50 r.raise_for_status()51 return r.json() if fmt == "json" else r.text5253def retrieve_entry(accession: str, fmt: str = "json"):54 """55 Retrieve a UniProtKB entry by accession.56 """57 url = f"{BASE}/uniprotkb/{accession}"58 params = {"format": fmt}59 r = requests.get(url, params=params, timeout=30)60 r.raise_for_status()61 return r.json() if fmt == "json" else r.text6263def id_mapping(from_db: str, to_db: str, ids, poll_interval_s: float = 1.0):64 """65 Map identifiers using UniProt ID Mapping.66 ids can be a list of strings or a comma-separated string.67 """68 if isinstance(ids, (list, tuple)):69 ids = ",".join(ids)7071 # 1) Submit mapping job72 submit_url = f"{BASE}/idmapping/run"73 r = requests.post(74 submit_url,75 data={"from": from_db, "to": to_db, "ids": ids},76 timeout=30,77 )78 r.raise_for_status()79 job_id = r.json()["jobId"]8081 # 2) Poll job status82 status_url = f"{BASE}/idmapping/status/{job_id}"83 while True:84 s = requests.get(status_url, timeout=30)85 s.raise_for_status()86 payload = s.json()87 if payload.get("jobStatus") in (None, "FINISHED"):88 break89 if payload.get("jobStatus") == "FAILED":90 raise RuntimeError(f"ID mapping failed: {payload}")91 time.sleep(poll_interval_s)9293 # 3) Fetch results (JSON)94 results_url = f"{BASE}/idmapping/results/{job_id}"95 res = requests.get(results_url, params={"format": "json"}, timeout=30)96 res.raise_for_status()97 return res.json()9899if __name__ == "__main__":100 # Search example: human BRCA1101 search = search_protein("gene:BRCA1 AND organism_id:9606", size=3)102 print("Search results (first accessions):",103 [item["primaryAccession"] for item in search.get("results", [])])104105 # Retrieve entry example106 entry = retrieve_entry("P38398") # UniProt accession for human BRCA1 (example)107 print("Entry primaryAccession:", entry.get("primaryAccession"))108 print("Protein name:", entry.get("proteinDescription", {}).get("recommendedName", {}).get("fullName", {}).get("value"))109110 # ID mapping example: gene name -> UniProtKB111 mapping = id_mapping(from_db="Gene_Name", to_db="UniProtKB", ids=["BRCA1"])112 print("Mapping results keys:", mapping.keys())113```114115## Implementation Details116117- **Search Protein**118 - Uses `GET /uniprotkb/search`119 - Key parameters:120 - `query`: Lucene-style query string (see `references/query_syntax.md`)121 - `format`: output format (default `json`)122 - Optional common parameters: `size`, `fields`, `sort`123 - Returns parsed JSON when `format=json`, otherwise raw text.124125- **Retrieve Entry**126 - Uses `GET /uniprotkb/{accession}`127 - Key parameters:128 - `accession`: UniProt accession (e.g., `P12345`)129 - `format`: output format (default `json`)130 - Suitable for fetching full record details for a known accession.131132- **ID Mapping**133 - Uses UniProt asynchronous mapping workflow:134 1. `POST /idmapping/run` with `from`, `to`, `ids`135 2. Poll `GET /idmapping/status/{jobId}` until finished136 3. Fetch `GET /idmapping/results/{jobId}?format=json`137 - `ids` accepts either a list or a comma-separated string.138 - Recommended parameters:139 - `poll_interval_s`: controls polling frequency to avoid excessive requests.140 - `from_db` / `to_db` must match UniProt-supported database identifiers (consult UniProt mapping documentation as needed).