
Uniprot Database
- 1.3k installs
- 2.6k repo stars
- Updated July 7, 2026
- google-deepmind/science-skills
uniprot-database is a bioinformatics skill that retrieves protein metadata, sequences, taxonomy, and functional annotations from UniProtKB, UniParc, and UniRef for developers who need hallucination-free protein data in a
About
uniprot-database is a skill from google-deepmind/science-skills that gives coding agents reliable access to UniProt protein records across UniProtKB, UniParc, and UniRef. Developers use it to search proteins, map identifiers, and pull functional annotations and publication-linked metadata without model guesswork. Prerequisites include installing uv per the bundled uv skill setup and notifying users about LICENSE_NOTIFICATION.txt when present. The skill explicitly excludes sequence alignment, protein folding, and similarity search, directing those tasks to specialized skills. Reach for uniprot-database when building proteomics tooling, annotation pipelines, or agent assistants that must cite real UniProt entries. Pair with clinvar-database when workflows span variants and protein context.
- Direct access to UniProtKB, UniParc, and UniRef databases
- Retrieves protein metadata, function, taxonomy, sequences, and publications
- Always uses provided Python wrapper scripts instead of raw API calls
- Includes mandatory user license notification and LICENSE_NOTIFICATION.txt creation
- Explicit anti-patterns: not for sequence alignment, folding, or similarity search
Uniprot Database by the numbers
- 1,285 all-time installs (skills.sh)
- +167 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #253 of 2,064 Data Science & ML 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 uniprot-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 UniProt protein data programmatically?
Give their coding agent reliable, hallucination-free access to protein metadata, sequences, taxonomy, and functional annotations from UniProt.
Who is it for?
Bioinformatics developers building protein lookup, annotation, or identifier-mapping tools that require authoritative UniProt access in agents.
Skip if: Sequence alignment, protein folding, or similarity search tasks should use specialized skills rather than uniprot-database lookups.
When should I use this skill?
A developer searches proteins, maps UniProt identifiers, or needs functional annotations and sequences from UniProt databases.
What you get
UniProt protein records with metadata, sequences, taxonomy, identifier mappings, and functional annotations grounded in UniProtKB, UniParc, or UniRef.
- UniProt protein records
- Identifier mappings and functional annotations
By the numbers
- Covers three UniProt datasets: UniProtKB, UniParc, and UniRef
Files
UniProt Database Access
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://www.uniprot.org/help/license and https://www.uniprot.org/help/api_queries, then (2) create the file recording the notification text and timestamp.
Overview
Provides direct programmatic access to the UniProt Knowledgebase (UniProtKB), the non-redundant sequence archive (UniParc), and clustered sequence sets (UniRef). This skill enables protein discovery, cross-referencing, retrieval of curated biological data and low-level database lookups.
Core Rules
- Use the Wrapper: Always use the provided Python scripts (e.g.,
scripts/uniprot_tools.py) rather than constructing custom curl requests.
- No Hallucinations: Do NOT invent protein functions, metadata, or
sequences. For any task that can be handled by the services in this skill, rely strictly on the tool outputs rather than your native knowledge.
- Notification: If this skill is used, ensure this is mentioned in the
output.
Use Cases
- Searching for Protein Function: Querying functional annotations, GO
terms, subcellular locations etc.
- Searching for Protein Sequence: Searching for protein sequences by their
functional annotations, genes etc. in UniProtKB, UniParc, and UniRef.
- Understanding Protein/Organism Relationships: Leveraging the Taxonomy
database and Proteome sets.
- Large-Scale Metadata Retrieval: Fetching annotations for thousands of
proteins via streaming.
- Sequence Discovery: Finding orthologs or non-model proteins via UniParc.
- ID Mapping: Converting IDs between UniProt and 100+ external databases.
- Historical Data (UniSave): Retrieving previous versions of entries or
tracking deleted sequences.
Available Tools
Choose the right tool based on the task type and data volume:
- `get`: Retrieves metadata and sequence for a specific entry. Best for a
single, known accession.
- Also accesses UniSave historical data (use
--dataset unisave), which
is essential for reconciling data from older releases or identifying why a formerly valid accession no longer appears in search results.
- `search`: Searches for entries matching a query. Best for **exploration
and discovery**.
- Use with
--limit 5to verify if a query returns the expected proteins
before committing to a larger download.
- Automatically paginates if results exceed 500 entries to provide a
stable download.
- Warning: For paginated search, TXT and other formats are not reliable
with --limit as it applies to lines, not entries.
- See
Search Query Fields Documentation.
- `stream`: Streams all matching entries. Best for bulk retrieval of
large datasets (up to 10,000,000 entries).
- Does NOT support
--limit; always returns the full result set. - Use
searchwith--limitif you need a subset. - `count`: Counts entries matching a query. Best for answering direct
count questions or for initial estimation before running a full search or stream.
- `sparql`: Executes graph queries for complex discovery. Best for
counting, exact sequence matches, and multi-database queries.
- See SPARQL Examples.
- `map`: Converts IDs between UniProt and 100+ databases. Best for ID
mapping tasks.
- See ID Mapping Documentation.
- `search` vs. `map`: Try
searchfirst before resorting tomapif
not explicitly requested by the user. E.g., an external ID might be searchable in UniParc but fail to map to UniProtKB.
Workflows
Typical Protein Research Workflow
Copy this checklist and track progress:
- [ ] Step 1: Identify target protein(s) and organism(s).
- [ ] Step 2: Search UniProtKB for reviewed entries (
reviewed:true). - [ ] Step 3: If no reviewed entries, search unreviewed or use UniParc for
sequence discovery.
- [ ] Step 4: Map external IDs (e.g., Ensembl, PDB) to UniProt Accessions if
necessary.
- [ ] Step 5: Retrieve functional metadata or sequence in desired format
(JSON, FASTA).
Handling Search Misses (e.g. Gene Search in Non-Model Organisms)
If a direct query (e.g., gene:SYMBOL) fails:
1. Pivot to Protein Name: Search for the common protein name (e.g., protein_name:Alpha-crystallin A). 2. Use UniParc: Search the UniParc dataset, which integrates sequences from across all of life, even if they aren't fully annotated in UniProtKB. 3. Check Orthologs/Canonical: Resolve the Human/Mouse ortholog first to find the correct naming/mnemonic.
Bulk Retrieval Priorities
[!IMPORTANT] Always prefer `stream` or `sparql` for bulk data.
search is suitable for exploration; if results exceed 500 entries, itautomatically paginates to provide a stable download.
- Priority 0: `count`: ALWAYS check the result count before running a
search or stream.
- Priority 1: `stream`: The primary method for bulk data retrieval (up to
10M entries). Does NOT support --limit; always returns all results.
- Priority 2: `sparql`: Best for complex filtering and exact matching
during retrieval.
Sequence-Based Search (Exact Match)
[!IMPORTANT] Use SPARQL when searching for a protein by its full amino
acid sequence. The REST API /search endpoint does not support directsequence-string lookups. For any non-exact match use specialized sequence
similarity search skills. Use UniParc if you cannot find query in UniProt.
SPARQL Query Pattern (UniProt):
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?protein ?name WHERE {
?protein a up:Protein ;
up:sequence/rdf:value "SEQUENCE_HERE" .
OPTIONAL {
?protein up:recommendedName/up:fullName ?name .
}
}SPARQL Query Pattern (UniParc):
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?uniparc ?val WHERE {
GRAPH <http://sparql.uniprot.org/uniparc> {
?uniparc a up:Sequence ;
rdf:value ?val .
FILTER (?val = "SEQUENCE_HERE")
}
}Counting Entries Efficiently
[!IMPORTANT] Use `count` or `SPARQL` for counting entries (e.g., "How
many proteins in Human?").
Counting Pattern (Proteins per Organism):
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX taxon: <http://purl.uniprot.org/taxonomy/>
SELECT (COUNT(?protein) AS ?count) WHERE {
?protein a up:Protein ;
up:reviewed true ;
up:organism taxon:9606 .
}REST Search Syntax
- No Commas in Lists: Commas are treated as literals. Use capitalized
OR
to separate items.
- Grouped:
accession:(P12345 OR P67890) - Repeated:
accession:P12345 OR accession:P67890 - Space = AND: E.g.,
gene:p53 humansearches for both.
Example Commands
Below are example commands for each mode of uniprot_tools.py.
Count total number of entries for a given query.
uv run scripts/uniprot_tools.py count "taxonomy_id:9606"Search for entries.
uv run scripts/uniprot_tools.py search "gene:p53 AND reviewed:true" --limit 5Retrieve a single entry by accession.
uv run scripts/uniprot_tools.py get P04637Retrieve Historical/Deleted Entry (UniSave).
uv run scripts/uniprot_tools.py get P04637 --dataset unisaveStream large result sets for bulk retrieval (returns ALL matched entries, no --limit support).
uv run scripts/uniprot_tools.py stream "taxonomy_id:9606 AND reviewed:true" --format tsv --fields accession,gene_names > human_reviewed.tsvMap IDs from one database to another.
uv run scripts/uniprot_tools.py map "P04637" --from_db UniProtKB_AC-ID --to_db Gene_NameExecute graph queries with SPARQL.
uv run scripts/uniprot_tools.py sparql 'PREFIX up: <http://purl.uniprot.org/core/> SELECT ?protein WHERE { ?protein a up:Protein ; up:reviewed true . } LIMIT 5'Common Mistakes
- Using `name:` instead of `protein_name:`:
name:is not a supported
query term, use protein_name: instead.
- Ignoring UniParc: Non-model organisms might only exist in UniParc.
- Confusing Accession with UPI: UniProtKB Accessions (e.g.,
P04637) are
linked to functional metadata; UniParc IDs (UPI...) are for sequences only. You can find cross-references from UniParc IDs to UniProtKB Accessions using the ID Mapping tool.
- Using UniProtKB-AC as Target in ID Mapping: Use
UniProtKBinstead. - Giving up on Complex Queries: If a complex search query fails, try to
use SPARQL instead of giving up.
- Using IDs Without Verifying Meaning: NEVER assume you know the meaning
of an ID (e.g. keyword, GO term, Pfam ID etc.). ALWAYS look up the natural language description/meaning of an ID in UniProt before using it for search to ensure it matches your intended search term.
- Ignoring Citation Noise in Broad Searches: Broad text searches (`search
"term") frequently return false positives (e.g., common maintenance proteins) because UniProt searches full metadata, including publication titles. ALWAYS prefer field-specific filters like cc_function: or protein_name:` for functional discovery.
- Forgetting to Quote Short Search Terms: Short, unquoted terms (e.g.,
lanM) can match substrings in organism names (e.g., Lancefieldella) or other fields. Use quotes and field prefixes (e.g., gene:lanM) to isolate true hits.
- Manipulating Protein Sequences Directly: Always use code and tools for
sequence-based operations. Do not attempt to edit, truncate, or modify protein sequences manually.
- Over-using Search for Bulk Data: DO NOT use
searchfor retrieving
millions of entries if stream or sparql can do the job. Streaming is more efficient for very large datasets. Note that stream has a hard limit of 10,000,000 outputs and does NOT support --limit.
- Forgetting to Check Data Volume: ALWAYS perform a
countbefore running
a search without --limit or before using stream. Unlimited queries can take a long time and consume significant resources if millions of entries are returned.
- Using `--limit` with `stream`: The
streamcommand does NOT support
--limit. If you need a limited number of results, use search with --limit instead.
- Forgetting the License Notice: Do not neglect to state that the UniProt
Database was used and to advise the user to review the licensing terms when presenting results for the first time. Even if the task is concise, this attribution is required in the first response containing UniProt data.
Reference Materials
- SPARQL Examples
- Search Query Fields Documentation
- ID Mapping Documentation
- UniProt Evidence Docs
- Underlying API Endpoints (Used by
scripts/uniprot_tools.py): -
get,search,stream,count->rest.uniprot.org/{dataset}/ -
map->rest.uniprot.org/idmapping/ -
sparql->sparql.uniprot.org/sparql -
get --dataset unisave->rest.uniprot.org/unisave/
UniProt ID Mapping Databases Reference
This document lists the exact database identifiers to use with the map command of uniprot_tools.py (i.e. the --from_db and --to_db arguments).
Source: https://rest.uniprot.org/configure/idmapping/fields
Usage
uv run uniprot_tools.py map "P12345,Q67890" --from_db UniProtKB_AC-ID --to_db PDB--------------------------------------------------------------------------------
UniProt
- UniProtKB:
UniProtKB(--to_dbonly) - UniProtKB AC/ID:
UniProtKB_AC-ID(--from_dbonly) - UniProtKB/Swiss-Prot:
UniProtKB-Swiss-Prot(--to_dbonly) - UniParc:
UniParc - UniRef50:
UniRef50 - UniRef90:
UniRef90 - UniRef100:
UniRef100 - Gene Name:
Gene_Name - CRC64:
CRC64 - Proteome ID:
Proteome_ID(--from_dbonly)
Sequence databases
- CCDS:
CCDS - EMBL/GenBank/DDBJ:
EMBL-GenBank-DDBJ - EMBL/GenBank/DDBJ CDS:
EMBL-GenBank-DDBJ_CDS - GI number:
GI_number - PIR:
PIR - RefSeq Nucleotide:
RefSeq_Nucleotide - RefSeq Protein:
RefSeq_Protein
3D structure databases
- PDB:
PDB
Protein-protein interaction databases
- BioGRID:
BioGRID - ComplexPortal:
ComplexPortal - DIP:
DIP - STRING:
STRING
Chemistry
- ChEMBL:
ChEMBL - DrugBank:
DrugBank - GuidetoPHARMACOLOGY:
GuidetoPHARMACOLOGY - SwissLipids:
SwissLipids
Protein family/group databases
- Allergome:
Allergome - ESTHER:
ESTHER - MEROPS:
MEROPS - PeroxiBase:
PeroxiBase - REBASE:
REBASE - TCDB:
TCDB
PTM databases
- GlyConnect:
GlyConnect
Genetic variation databases
- BioMuta:
BioMuta - DMDM:
DMDM
Proteomic databases
- CPTAC:
CPTAC - ProteomicsDB:
ProteomicsDB
Protocols and materials databases
- DNASU:
DNASU
Genome annotation databases
- Ensembl:
Ensembl - Ensembl Genomes:
Ensembl_Genomes - Ensembl Genomes Protein:
Ensembl_Genomes_Protein - Ensembl Genomes Transcript:
Ensembl_Genomes_Transcript - Ensembl Protein:
Ensembl_Protein - Ensembl Transcript:
Ensembl_Transcript - GeneID:
GeneID - KEGG:
KEGG - PATRIC:
PATRIC - UCSC:
UCSC - WBParaSite:
WBParaSite - WBParaSite Transcript/Protein:
WBParaSite_Transcript-Protein
Organism-specific databases
- ArachnoServer:
ArachnoServer - Araport:
Araport - CGD:
CGD - ClinPGx:
ClinPGx - ConoServer:
ConoServer - dictyBase:
dictyBase - EchoBASE:
EchoBASE - euHCVdb:
euHCVdb - FlyBase:
FlyBase - GeneCards:
GeneCards - GeneReviews:
GeneReviews - HGNC:
HGNC - LegioList:
LegioList - Leproma:
Leproma - MaizeGDB:
MaizeGDB - MGI:
MGI - MIM:
MIM - OpenTargets:
OpenTargets - Orphanet:
Orphanet - PomBase:
PomBase - PseudoCAP:
PseudoCAP - RGD:
RGD - SGD:
SGD - TubercuList:
TubercuList - VEuPathDB:
VEuPathDB - VGNC:
VGNC - WormBase:
WormBase - WormBase Protein:
WormBase_Protein - WormBase Transcript:
WormBase_Transcript - Xenbase:
Xenbase - ZFIN:
ZFIN
Phylogenomic databases
- eggNOG:
eggNOG - GeneTree:
GeneTree - HOGENOM:
HOGENOM - OMA:
OMA - OrthoDB:
OrthoDB
Enzyme and pathway databases
- BioCyc:
BioCyc - PlantReactome:
PlantReactome - Reactome:
Reactome - UniPathway:
UniPathway
Miscellaneous
- ChiTaRS:
ChiTaRS - GeneWiki:
GeneWiki - GenomeRNAi:
GenomeRNAi - PHI-base:
PHI-base
Gene expression databases
- CollecTF:
CollecTF
Family and domain databases
- DisProt:
DisProt - IDEAL:
IDEAL
--------------------------------------------------------------------------------
Mapping Rules (Valid --to_db targets per --from_db source)
Not all --from_db → --to_db combinations are valid. The API defines rules that constrain which target databases are allowed for each source. Some source databases also require a taxonId parameter.
Rule 1: UniProtKB_AC-ID (From only)
When mapping from UniProtKB_AC-ID, the valid to databases are: all databases listed above (the full set). Default target: UniProtKB. Taxon ID: not required.
Rule 2: UniParc, Proteome_ID
When mapping from UniParc or Proteome_ID, the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot -
UniParc
Default target: UniProtKB. Taxon ID: not required.
Rule 3: UniRef50
When mapping from UniRef50, the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot -
UniRef50
Default target: UniProtKB. Taxon ID: not required.
Rule 4: UniRef90
When mapping from UniRef90, the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot -
UniRef90
Default target: UniProtKB. Taxon ID: not required.
Rule 5: UniRef100
When mapping from UniRef100, the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot -
UniRef100
Default target: UniProtKB. Taxon ID: not required.
Rule 6: Gene_Name
When mapping from Gene_Name, the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot
Default target: UniProtKB. Taxon ID: required (use &taxId=XXXXX).
Rule 7: All other databases (default rule)
When mapping from any other database (CCDS, EMBL-GenBank-DDBJ, PDB, GeneID, Ensembl, HGNC, etc.), the valid to databases are:
-
UniProtKB -
UniProtKB-Swiss-Prot
Default target: UniProtKB. Taxon ID: not required.
--------------------------------------------------------------------------------
Quick Reference: From-only and To-only databases
From-only databases (cannot be used as --to_db)
- UniProtKB AC/ID:
UniProtKB_AC-ID - Proteome ID:
Proteome_ID
To-only databases (cannot be used as --from_db)
- UniProtKB:
UniProtKB - UniProtKB/Swiss-Prot:
UniProtKB-Swiss-Prot
Common mapping examples
# Map UniProt accessions to PDB IDs
uv run uniprot_tools.py map "P12345" --from_db UniProtKB_AC-ID --to_db PDB
# Map PDB IDs to UniProt accessions
uv run uniprot_tools.py map "1AKE" --from_db PDB --to_db UniProtKB
# Map gene names to UniProt (requires taxon ID in the API, handled internally)
uv run uniprot_tools.py map "BRCA1" --from_db Gene_Name --to_db UniProtKB
# Map RefSeq protein IDs to UniProtKB/Swiss-Prot (reviewed entries only)
uv run uniprot_tools.py map "NP_005219.2" --from_db RefSeq_Protein --to_db UniProtKB-Swiss-Prot
# Map Ensembl gene IDs to UniProtKB
uv run uniprot_tools.py map "ENSG00000141510" --from_db Ensembl --to_db UniProtKB
# Map EMBL/GenBank accessions to UniProtKB
uv run uniprot_tools.py map "M10051" --from_db EMBL-GenBank-DDBJ --to_db UniProtKB
# Map HGNC IDs to UniProtKB
uv run uniprot_tools.py map "HGNC:11998" --from_db HGNC --to_db UniProtKBUniProt REST Query Fields Reference
This document lists the available query fields for searching UniProt databases via the REST API.
Fields marked with (Experimental Evidence) are used to filter for entries where the annotation has experimental support.
UniProtKB (UniProt Knowledgebase)
- UniProtKB AC:
accession - Entry Name [ID]:
id - Secondary Accession:
sec_acc - Protein Name [DE]:
protein_name - Gene Name [GN]:
gene - Organism [OS]:
organism_name - Taxonomy [OC]:
taxonomy_name - Virus host:
virus_host_name - Protein Existence [PE]:
existence - Function
- Enzyme classification [EC]:
ec - Cofactors
- ChEBI term
- Chebi:
cc_cofactor_chebi - Exp (Experimental Evidence):
cc_cofactor_chebi_exp - Note
- Note:
cc_cofactor_note - Exp (Experimental Evidence):
cc_cofactor_note_exp - Biophysicochemical properties
- Any
- Bpcp:
cc_bpcp - Exp (Experimental Evidence):
cc_bpcp_exp - Absorption
- Absorption:
cc_bpcp_absorption - Exp (Experimental Evidence):
cc_bpcp_absorption_exp - Kinetics
- Kinetics:
cc_bpcp_kinetics - Exp (Experimental Evidence):
cc_bpcp_kinetics_exp - pH dependence
- Dependence:
cc_bpcp_ph_dependence - Exp (Experimental Evidence):
cc_bpcp_ph_dependence_exp - Redox potential
- Potential:
cc_bpcp_redox_potential - Exp (Experimental Evidence):
cc_bpcp_redox_potential_exp - Temperature dependence
- Dependence:
cc_bpcp_temp_dependence - Exp (Experimental Evidence):
cc_bpcp_temp_dependence_exp - Catalytic Activity
- Activity:
cc_catalytic_activity - Exp (Experimental Evidence):
cc_catalytic_activity_exp - Activity regulation
- Regulation:
cc_activity_regulation - Exp (Experimental Evidence):
cc_activity_regulation_exp - Function [CC]
- Function:
cc_function - Exp (Experimental Evidence):
cc_function_exp - Caution
- Caution:
cc_caution - Exp (Experimental Evidence):
cc_caution_exp - Sites
- Any
- Sites:
ft_sites - Exp (Experimental Evidence):
ft_sites_exp - Active site
- Site:
ft_act_site - Exp (Experimental Evidence):
ft_act_site_exp - Binding site
- Binding:
ft_binding - Exp (Experimental Evidence):
ft_binding_exp - Other
- Site:
ft_site - Exp (Experimental Evidence):
ft_site_exp - DNA binding
- Bind:
ft_dna_bind - Exp (Experimental Evidence):
ft_dna_bind_exp - Pathway
- Pathway:
cc_pathway - Exp (Experimental Evidence):
cc_pathway_exp - Miscellaneous [CC]
- Miscellaneous:
cc_miscellaneous - Exp (Experimental Evidence):
cc_miscellaneous_exp - Subcellular location
- Subcellular location [CC]
- Subcellular location term
- Term:
cc_scl_term - Exp (Experimental Evidence):
cc_scl_term_exp - Subcellular location note
- Note:
cc_scl_note - Exp (Experimental Evidence):
cc_scl_note_exp - Transmembrane
- Transmem:
ft_transmem - Exp (Experimental Evidence):
ft_transmem_exp - Topological domain
- Dom:
ft_topo_dom - Exp (Experimental Evidence):
ft_topo_dom_exp - Intramembrane
- Intramem:
ft_intramem - Exp (Experimental Evidence):
ft_intramem_exp - Pathology & Biotech
- Disease
- Disease:
cc_disease - Exp (Experimental Evidence):
cc_disease_exp - Allergenic properties
- Allergen:
cc_allergen - Exp (Experimental Evidence):
cc_allergen_exp - Toxic dose
- Dose:
cc_toxic_dose - Exp (Experimental Evidence):
cc_toxic_dose_exp - Biotechnological use
- Biotechnology:
cc_biotechnology - Exp (Experimental Evidence):
cc_biotechnology_exp - Pharmaceutical use
- Pharmaceutical:
cc_pharmaceutical - Exp (Experimental Evidence):
cc_pharmaceutical_exp - Disruption phenotype
- Phenotype:
cc_disruption_phenotype - Exp (Experimental Evidence):
cc_disruption_phenotype_exp - Mutagenesis
- Mutagen:
ft_mutagen - Exp (Experimental Evidence):
ft_mutagen_exp - PTM/Processing
- Post-translational modification [CC]
- Ptm:
cc_ptm - Exp (Experimental Evidence):
cc_ptm_exp - Modified residue [FT]
- Res:
ft_mod_res - Exp (Experimental Evidence):
ft_mod_res_exp - Lipidation [FT]
- Lipid:
ft_lipid - Exp (Experimental Evidence):
ft_lipid_exp - Glycosylation [FT]
- Carbohyd:
ft_carbohyd - Exp (Experimental Evidence):
ft_carbohyd_exp - Disulfide bond [FT]
- Disulfid:
ft_disulfid - Exp (Experimental Evidence):
ft_disulfid_exp - Cross-link [FT]
- Crosslnk:
ft_crosslnk - Exp (Experimental Evidence):
ft_crosslnk_exp - Molecule Processing [FT]
- Any molecule processing
- Processing:
ft_molecule_processing - Exp (Experimental Evidence):
ft_molecule_processing_exp - Chain
- Chain:
ft_chain - Exp (Experimental Evidence):
ft_chain_exp - Initiator methionine
- Met:
ft_init_met - Exp (Experimental Evidence):
ft_init_met_exp - Peptide
- Peptide:
ft_peptide - Exp (Experimental Evidence):
ft_peptide_exp - Signal Peptide
- Signal:
ft_signal - Exp (Experimental Evidence):
ft_signal_exp - Propeptide
- Propep:
ft_propep - Exp (Experimental Evidence):
ft_propep_exp - Transit Peptide
- Transit:
ft_transit - Exp (Experimental Evidence):
ft_transit_exp - Expression
- Developmental stage
- Stage:
cc_developmental_stage - Exp (Experimental Evidence):
cc_developmental_stage_exp - Induction
- Induction:
cc_induction - Exp (Experimental Evidence):
cc_induction_exp - Tissue specificity
- Specificity:
cc_tissue_specificity - Exp (Experimental Evidence):
cc_tissue_specificity_exp - Interaction
- Binary Interaction:
interactor - Subunit structure
- Subunit:
cc_subunit - Exp (Experimental Evidence):
cc_subunit_exp - Structure
- 3D Structure:
structure_3d - Secondary structure
- Any
- Secstruct:
ft_secstruct - Exp (Experimental Evidence):
ft_secstruct_exp - Helix
- Helix:
ft_helix - Exp (Experimental Evidence):
ft_helix_exp - Turn
- Turn:
ft_turn - Exp (Experimental Evidence):
ft_turn_exp - Beta strand
- Strand:
ft_strand - Exp (Experimental Evidence):
ft_strand_exp - Sequence
- Mass(Da):
mass - Checksum (CRC64/MD5):
checksum - Sequence length:
length - Alternative products (isoforms)
- Any
- Ap:
cc_ap - Exp (Experimental Evidence):
cc_ap_exp - Alternative promoter usage
- Apu:
cc_ap_apu - Exp (Experimental Evidence):
cc_ap_apu_exp - Alternative splicing
- As:
cc_ap_as - Exp (Experimental Evidence):
cc_ap_as_exp - Alternative initiation
- Ai:
cc_ap_ai - Exp (Experimental Evidence):
cc_ap_ai_exp - Ribosomal frameshifting
- Rf:
cc_ap_rf - Exp (Experimental Evidence):
cc_ap_rf_exp - Sequence caution
- Any
- Caution:
cc_sequence_caution - Exp (Experimental Evidence):
cc_sequence_caution_exp - Frameshift:
cc_sc_framesh - Erroneous initiation:
cc_sc_einit - Erroneous termination:
cc_sc_eterm - Erroneous gene model prediction:
cc_sc_epred - Erroneous translation:
cc_sc_etran - Miscellaneous Discrepancy
- Misc:
cc_sc_misc - Exp (Experimental Evidence):
cc_sc_misc_exp - Mass Spectrometry
- Spectrometry:
cc_mass_spectrometry - Exp (Experimental Evidence):
cc_mass_spectrometry_exp - Polymorphism
- Polymorphism:
cc_polymorphism - Exp (Experimental Evidence):
cc_polymorphism_exp - RNA Editing
- Editing:
cc_rna_editing - Exp (Experimental Evidence):
cc_rna_editing_exp - Natural Variations
- Any
- Variants:
ft_variants - Exp (Experimental Evidence):
ft_variants_exp - Natural variant
- Variant:
ft_variant - Exp (Experimental Evidence):
ft_variant_exp - Alternative sequence
- Seq:
ft_var_seq - Exp (Experimental Evidence):
ft_var_seq_exp - Non-standard residue
- Std:
ft_non_std - Exp (Experimental Evidence):
ft_non_std_exp - Non-terminal residue
- Ter:
ft_non_ter - Exp (Experimental Evidence):
ft_non_ter_exp - Non-adjacent residue
- Cons:
ft_non_cons - Exp (Experimental Evidence):
ft_non_cons_exp - Sequence conflict
- Conflict:
ft_conflict - Exp (Experimental Evidence):
ft_conflict_exp - Sequence uncertainty
- Unsure:
ft_unsure - Exp (Experimental Evidence):
ft_unsure_exp - Sequence features [FT]
- Positional:
ft_positional - Exp (Experimental Evidence):
ft_positional_exp - Fragment:
fragment - Encoded in:
encoded_in - Precursor:
precursor - Sequence from ... [RC]
- Tissue:
tissue - Strain:
strain - Plasmid:
plasmid - Transposon:
transposon - Family and Domains
- Domain [FT]
- Domain:
ft_domain - Exp (Experimental Evidence):
ft_domain_exp - Domain Comments [CC]
- Domain:
cc_domain - Exp (Experimental Evidence):
cc_domain_exp - Protein family:
family - Coiled-coil
- Coiled:
ft_coiled - Exp (Experimental Evidence):
ft_coiled_exp - Compositional bias
- Compbias:
ft_compbias - Exp (Experimental Evidence):
ft_compbias_exp - Motif
- Motif:
ft_motif - Exp (Experimental Evidence):
ft_motif_exp - Region
- Region:
ft_region - Exp (Experimental Evidence):
ft_region_exp - Repeat
- Repeat:
ft_repeat - Exp (Experimental Evidence):
ft_repeat_exp - Sequence similarity
- Similarity:
cc_similarity - Exp (Experimental Evidence):
cc_similarity_exp - Zinc finger
- Fing:
ft_zn_fing - Exp (Experimental Evidence):
ft_zn_fing_exp - Cross-references
- Source:
source - Any
- Any cross-reference:
xref - Sequence databases
- EMBL:
xref - CCDS:
xref - PIR:
xref - RefSeq:
xref - 3D structure databases
- PDB:
xref - PDBsum:
xref - PCDDB:
xref - SASBDB:
xref - BMRB:
xref - SMR:
xref - AlphaFoldDB:
xref - EMDB:
xref - Protein-protein interaction databases
- BioGRID:
xref - ComplexPortal:
xref - CORUM:
xref - DIP:
xref - ELM:
xref - IntAct:
xref - MINT:
xref - STRING:
xref - FunCoup:
xref - Chemistry
- BindingDB:
xref - ChEMBL:
xref - DrugBank:
xref - GuidetoPHARMACOLOGY:
xref - SwissLipids:
xref - DrugCentral:
xref - Protein family/group databases
- Allergome:
xref - CAZy:
xref - ESTHER:
xref - IMGT_GENE-DB:
xref - MEROPS:
xref - MoonDB:
xref - MoonProt:
xref - PeroxiBase:
xref - REBASE:
xref - TCDB:
xref - UniLectin:
xref - CARD:
xref - PTM databases
- CarbonylDB:
xref - DEPOD:
xref - GlyConnect:
xref - GlyCosmos:
xref - GlyGen:
xref - iPTMnet:
xref - PhosphoSitePlus:
xref - SwissPalm:
xref - UniCarbKB:
xref - MetOSite:
xref - Genetic variation databases
- BioMuta:
xref - DMDM:
xref - dbSNP:
xref - 2D gel databases
- OGP:
xref - REPRODUCTION-2DPAGE:
xref - Proteomic databases
- CPTAC:
xref - PaxDb:
xref - PeptideAtlas:
xref - PRIDE:
xref - ProMEX:
xref - ProteomicsDB:
xref - Pumba:
xref - TopDownProteomics:
xref - jPOST:
xref - MassIVE:
xref - Protocols and materials databases
- DNASU:
xref - ABCD:
xref - Antibodypedia:
xref - CPTC:
xref - YCharOS:
xref - Genome annotation databases
- Ensembl:
xref - EnsemblBacteria:
xref - EnsemblFungi:
xref - EnsemblMetazoa:
xref - EnsemblPlants:
xref - EnsemblProtists:
xref - GeneID:
xref - Gramene:
xref - KEGG:
xref - MANE-Select:
xref - PATRIC:
xref - UCSC:
xref - VectorBase:
xref - WBParaSite:
xref - Organism-specific databases
- ArachnoServer:
xref - Araport:
xref - CGD:
xref - ConoServer:
xref - CTD:
xref - dictyBase:
xref - DisGeNET:
xref - EchoBASE:
xref - euHCVdb:
xref - VEuPathDB:
xref - FlyBase:
xref - GeneCards:
xref - GeneReviews:
xref - HGNC:
xref - AGR:
xref - HPA:
xref - LegioList:
xref - Leproma:
xref - MaizeGDB:
xref - MalaCards:
xref - MGI:
xref - MIM:
xref - NIAGADS:
xref - OpenTargets:
xref - Orphanet:
xref - ClinPGx:
xref - PomBase:
xref - PseudoCAP:
xref - RGD:
xref - SGD:
xref - TAIR:
xref - TubercuList:
xref - VGNC:
xref - WormBase:
xref - Xenbase:
xref - ZFIN:
xref - JaponicusDB:
xref - CIViC:
xref - Phylogenomic databases
- eggNOG:
xref - GeneTree:
xref - HOGENOM:
xref - InParanoid:
xref - OMA:
xref - OrthoDB:
xref - PhylomeDB:
xref - PAN-GO:
xref - Enzyme and pathway databases
- BioCyc:
xref - BRENDA:
xref - Reactome:
xref - SABIO-RK:
xref - SignaLink:
xref - SIGNOR:
xref - UniPathway:
xref - PlantReactome:
xref - PathwayCommons:
xref - STRENDA-DB:
xref - Miscellaneous
- ChiTaRS:
xref - EvolutionaryTrace:
xref - Agora:
xref - GeneWiki:
xref - GenomeRNAi:
xref - PHI-base:
xref - PRO:
xref - Pharos:
xref - RNAct:
xref - BioGRID-ORCS:
xref - CD-CODE:
xref - Gene expression databases
- Bgee:
xref - CleanEx:
xref - CollecTF:
xref - ExpressionAtlas:
xref - Family and domain databases
- AntiFam:
xref - CDD:
xref - FunFam:
xref - Gene3D:
xref - HAMAP:
xref - IDEAL:
xref - InterPro:
xref - PANTHER:
xref - Pfam:
xref - PIRSF:
xref - PRINTS:
xref - SFLD:
xref - SMART:
xref - SUPFAM:
xref - NCBIfam:
xref - PROSITE:
xref - DisProt:
xref - Proteomes databases
- Proteomes:
xref - Database:
database - Web Resources
- Webresource:
cc_webresource - Exp (Experimental Evidence):
cc_webresource_exp - Date Of
- Date Of Creation:
date_created - Date of last entry modification:
date_modified - Date of last sequence modification:
date_sequence_modified - Gene Ontology [GO]
- Go:
go - Small molecule
- Name or ID (CHEBI):
chebi - InChIKey:
inchikey - Keyword [KW]:
keyword - Literature Citation
- Author:
lit_author - Journal:
lit_journal - Published:
lit_pubdate - PubMed ID:
lit_pubmed - Title:
lit_title - Citation ID:
lit_citation_id - Computational PubMed ID:
computational_pubmed_id - Community PubMed ID:
community_pubmed_id - Proteomes
- Proteome ID:
proteome - Proteome Component:
proteomecomponent - Cited for:
scope - Reviewed:
reviewed - Active:
active - UniRef ID
- UniRef50:
uniref_cluster_50 - UniRef90:
uniref_cluster_90 - UniRef100:
uniref_cluster_100 - UniParc ID:
uniparc
UniRef (UniProt Reference Clusters)
- UniRef ID:
id - Cluster name:
name - Sequence identity:
identity - Cluster size:
count - Sequence length:
length - Date of last modification:
date_modified - UniProtKB ID/AC:
uniprotkb - UniParc ID:
uniparc - Taxonomy [OC]:
taxonomy_name - Related clusters:
cluster
UniParc (UniProt Archive)
- UniParc ID:
upi - UniProtKB AC (active only):
uniprotkb - UniProtKB isoform ID:
isoform - Proteome ID:
proteome - Organism:
organism_id - Taxonomy [OC]:
taxonomy_name - Gene name [GN]:
gene - Protein name:
protein_name - Database:
database - Active:
active - Checksum (CRC64/MD5):
checksum - Sequence length:
length - Database ID:
dbid - Feature ID:
feature_id - Proteome Component:
proteomecomponent
UniProt SPARQL Examples
This document contains curated SPARQL queries for accessing UniProt data. These examples are optimized for complex discovery and cross-database federated queries.
Essential Prefixes
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX taxon: <http://purl.uniprot.org/taxonomy/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>1. Retrieve Human Proteins with Gene Names
SELECT ?protein ?mnemonic ?geneName
WHERE {
?protein a up:Protein ;
up:reviewed true ;
up:organism taxon:9606 ;
up:mnemonic ?mnemonic .
OPTIONAL {
?protein up:encodedBy ?gene .
?gene skos:prefLabel ?geneName .
}
}
LIMIT 102. Mapping UniProtKB to PDB (3D Structure)
Find reviewed proteins that have an associated 3D structure in PDB.
SELECT ?protein ?pdbLink
WHERE {
?protein a up:Protein ;
up:reviewed true ;
rdfs:seeAlso ?pdbLink .
?pdbLink up:database <http://purl.uniprot.org/database/PDB> .
}
LIMIT 103. Find Proteins by Keyword (e.g., DNA Binding)
SELECT ?protein ?name
WHERE {
?protein a up:Protein ;
up:reviewed true ;
up:recommendedName/up:fullName ?name ;
up:classifiedWith <http://purl.uniprot.org/keywords/238> . # DNA-binding
}4. Counting Entries Efficiently
4.1 Count Reviewed Proteins per Organism
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX taxon: <http://purl.uniprot.org/taxonomy/>
SELECT (COUNT(?protein) AS ?count)
WHERE {
?protein a up:Protein ;
up:reviewed true ;
up:organism taxon:9606 .
}4.2 Count Proteins per Enzyme Class (Top Level)
PREFIX up: <http://purl.uniprot.org/core/>
SELECT ?enzymeClass (COUNT(?protein) AS ?count)
WHERE {
?protein a up:Protein ;
up:enzyme ?enzymeClass .
}
GROUP BY ?enzymeClass
ORDER BY DESC(?count)4.3 Count reviewed proteins with PDB structures
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT (COUNT(?protein) AS ?count)
WHERE {
?protein a up:Protein ;
up:reviewed true ;
rdfs:seeAlso ?pdbLink .
?pdbLink up:database <http://purl.uniprot.org/database/PDB> .
}5. Federated Query (UniProt + Wikidata)
Note: This query requires the SPARQL endpoint to support federation (`SERVICE` keyword).
SELECT ?protein ?wikidataLabel
WHERE {
?protein a up:Protein ;
up:reviewed true ;
up:organism taxon:9606 .
SERVICE <https://query.wikidata.org/sparql> {
?wikidataItem wdt:P352 ?uniprotAccession . # P352: UniProt ID in Wikidata
?wikidataItem rdfs:label ?wikidataLabel .
FILTER(LANG(?wikidataLabel) = "en")
}
}
LIMIT 5# 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.
"""Uniprot tools for accessing UniProtKB, UniParc, and UniRef."""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "science-skills-common",
# ]
# [tool.uv.sources]
# science-skills-common = { path = "../../science_skills_common" }
# ///
from __future__ import annotations
import argparse
import gzip
import json
import re
import sys
import time
from typing import Any, Iterator
import urllib.parse
from science_skills.science_skills_common import http_client
class UniProtError(Exception):
"""Custom exception for UniProt tool errors."""
BASE_URL = "https://rest.uniprot.org"
SPARQL_URL = "https://sparql.uniprot.org/sparql"
CLIENT = http_client.HttpClient(BASE_URL, qps=1.0)
SPARQL_CLIENT = http_client.HttpClient(SPARQL_URL, qps=1.0)
def _add_params_to_url(url: str, params: dict[str, Any] | None = None) -> str:
"""Adds URL parameters to a URL."""
if params:
sep = "&" if "?" in url else "?"
url += f"{sep}{urllib.parse.urlencode(params, doseq=True)}"
return url
def _get_header(resp: http_client.HttpResponse, header_name: str) -> str:
"""Returns the value of a given header, checking both lower and upper case."""
return resp.headers.get(header_name) or resp.headers.get(header_name.lower())
def _get_decompressed_data(resp: http_client.HttpResponse) -> str:
"""Decompresses gzipped data from a response if necessary and decodes it."""
data = resp.data
# UniProt sometimes double-gzips content.
if data.startswith(b"\x1f\x8b"):
data = gzip.decompress(data)
return data.decode(resp.encoding)
def _fetch(
url: str, method="GET", headers=None, data=None, *, as_json=False
) -> dict[str, Any] | str:
"""Fetch JSON and parse, handling server double-gzipping content."""
if not headers:
headers = {}
if as_json:
headers |= {"Accept": "application/json"}
response = CLIENT.fetch(url, headers=headers, method=method, data=data)
decoded_data = _get_decompressed_data(response)
if as_json:
return json.loads(decoded_data)
else:
return decoded_data
def search_proteins(
query: str,
dataset: str = "uniprotkb",
output_format: str = "json",
limit: int | None = None,
fields: list[str] | None = None,
) -> Iterator[dict[str, Any] | str]:
"""Search proteins in a UniProt dataset with automatic pagination."""
url = f"{BASE_URL}/{dataset}/search"
params: dict[str, Any] = {
"query": query,
"format": output_format,
}
# Determine if automatic pagination is needed
# UniProt has a hard limit of 500 for the 'size' parameter.
use_pagination = limit is None or limit > 500
request_size = min(limit, 500) if limit is not None else 500
params["size"] = request_size
if fields:
params["fields"] = ",".join(fields)
if not use_pagination:
def _single_request_iterator():
full_url = _add_params_to_url(url, params)
yield _fetch(full_url, as_json=(output_format == "json"))
return _single_request_iterator()
# Pagination logic
def _paginate_generator():
next_url = url
current_params = params
fetched_count = 0
total_results = None
header = None
while next_url:
full_url = _add_params_to_url(next_url, current_params)
resp = CLIENT.fetch(full_url)
if total_results is None:
total_results = _get_header(resp, "X-Total-Results")
data = _get_decompressed_data(resp)
if output_format == "json":
data = json.loads(data)
# Extract results from this page to handle limits
page_results = []
if isinstance(data, dict) and "results" in data:
page_results = data["results"]
elif isinstance(data, str):
if output_format == "fasta":
# Split by '>' at the start of a line
parts = re.split(r"(?m)^>", data)
page_results = [">" + p for p in parts if p.strip()]
elif output_format == "tsv":
# UniProt includes TSV headers on each page.
lines = data.strip().splitlines()
if lines:
if header is None: # Store the header only from the first page.
header = lines[0]
page_results = lines[1:]
else:
page_results = []
else:
page_results = data.strip().splitlines()
# Apply limit if necessary
if limit is not None:
remaining = limit - fetched_count
if remaining <= 0:
break
if len(page_results) > remaining:
page_results = page_results[:remaining]
# This reconstruction only executes when we need to truncate results.
#
# No Trimming Needed: If limit is None, or if the current page results
# fit within the remaining limit, data already contains the full page
# content as received from the server (either as a parsed dict for
# JSON or a raw string for FASTA/others). We can just yield it.
#
# Trimming Needed: We only need to reconstruct data if we had to slice
# page_results to respect the limit. In that case, build a new data
# object from the truncated page_results.
#
# TSV is the only exception (handled below) where we always
# reconstruct the data, regardless of whether we applied a limit or
# not. This is because we are actively modifying the content by
# removing the header lines from subsequent pages, so we can never
# just yield the raw server response for TSV after the first page.
if isinstance(data, dict):
data["results"] = page_results
elif output_format == "fasta":
data = "".join(page_results)
elif output_format != "tsv":
data = "\n".join(page_results)
# Reconstruct TSV data to ensure headers are only on the first page
if output_format == "tsv":
page_data = "\n".join(page_results)
if fetched_count == 0 and header:
data = header + "\n" + page_data
else:
data = page_data
fetched_count += len(page_results)
if total_results:
print(
f"Progress: {fetched_count} / {total_results} fetched",
file=sys.stderr,
)
else:
print(f"Progress: {fetched_count} fetched", file=sys.stderr)
yield data
if limit is not None and fetched_count >= limit:
break
link_header = _get_header(resp, "Link")
if link_header and 'rel="next"' in link_header:
next_url = link_header.split(";")[0].strip("<>")
current_params = None # Params are already in the URL
else:
next_url = None
return _paginate_generator()
def get_count(query: str, dataset: str = "uniprotkb") -> int:
"""Retrieve the total number of hits for a query."""
url = f"{BASE_URL}/{dataset}/search"
params = {"query": query, "size": 1, "format": "json"}
resp = CLIENT.fetch(_add_params_to_url(url, params))
return int(_get_header(resp, "X-Total-Results") or 0)
def get_entry(
accession: str,
dataset: str = "uniprotkb",
output_format: str = "json",
) -> dict[str, Any] | str:
"""Retrieve a single UniProt entry."""
url = f"{BASE_URL}/{dataset}/{accession}"
params = {"format": output_format}
full_url = _add_params_to_url(url, params)
return _fetch(full_url, as_json=(output_format == "json"))
def run_id_mapping(ids: list[str], from_db: str, to_db: str) -> dict[str, Any]:
"""Execute the ID mapping workflow."""
# 1. Submit job
submit_url = f"{BASE_URL}/idmapping/run"
form_dict = {
"from": from_db,
"to": to_db,
"ids": ",".join(ids),
}
data = urllib.parse.urlencode(form_dict).encode("utf-8")
headers = {"Content-Type": "application/x-www-form-urlencoded"}
job_id = _fetch(
submit_url, method="POST", headers=headers, data=data, as_json=True
)["jobId"]
# 2. Poll for status
status_url = f"{BASE_URL}/idmapping/status/{job_id}"
results_resp = None
while True:
status_resp = _fetch(status_url, as_json=True)
if not isinstance(status_resp, dict):
raise UniProtError(
f"ID mapping job status response is not a dict: {status_resp}"
)
# Check if we were redirected to results (or results are in the status resp)
if "results" in status_resp:
results_resp = status_resp
break
job_status = status_resp.get("jobStatus")
if job_status == "FINISHED":
break
if job_status == "FAILED":
raise UniProtError(f"ID mapping job failed: {status_resp.get('errors')}")
print(f"ID Mapping Job status: {job_status}")
time.sleep(2)
# 3. Get results (if not already fetched during status poll)
if results_resp:
return results_resp
results_url = f"{BASE_URL}/idmapping/results/{job_id}"
return _fetch(results_url, as_json=True)
def sparql_query(query: str) -> dict[str, Any]:
"""Execute a SPARQL query."""
params = {"query": query, "format": "json"}
return SPARQL_CLIENT.fetch_json(_add_params_to_url(SPARQL_URL, params))
def stream_results(
query: str,
dataset: str = "uniprotkb",
output_format: str = "tsv",
fields: list[str] | None = None,
) -> Iterator[str]:
"""Stream all results for a bulk query using the /stream endpoint.
The /stream endpoint always returns the full result set (up to 10M entries).
It does NOT support limiting the number of results. Use `search_proteins`
with a `limit` parameter if you need a subset of results.
Args:
query: The search query.
dataset: The dataset to search in.
output_format: The output format.
fields: The fields to retrieve.
Yields:
str: Each line of the result set.
"""
url = f"{BASE_URL}/{dataset}/stream"
params = {"query": query, "format": output_format}
headers = {"Accept-Encoding": "identity"}
if fields:
params["fields"] = ",".join(fields)
full_url = _add_params_to_url(url, params)
fetched_count = 0
for line in CLIENT.stream_lines(full_url, headers=headers):
if line:
fetched_count += 1
if fetched_count % 1000 == 0:
print(f"Progress: {fetched_count} lines fetched...", file=sys.stderr)
yield line
print(f"Total fetched lines: {fetched_count}", file=sys.stderr)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command")
# Search command
s_parser = subparsers.add_parser("search", help="Search proteins")
s_parser.add_argument("query", help="Query string")
s_parser.add_argument(
"--dataset",
default="uniprotkb",
help="Dataset to search in (e.g. uniprotkb, uniparc, unipref)",
)
s_parser.add_argument(
"--limit", type=int, help="Total number of results to return"
)
s_parser.add_argument("--format", default="json")
s_parser.add_argument("--fields")
# Get command
g_parser = subparsers.add_parser("get", help="Get protein entry")
g_parser.add_argument("accession")
g_parser.add_argument(
"--dataset",
default="uniprotkb",
help="Dataset to search in (e.g. uniprotkb, uniparc, unipref)",
)
g_parser.add_argument("--format", default="json")
# Map command
m_parser = subparsers.add_parser("map", help="Map IDs")
m_parser.add_argument("ids", help="Comma-separated IDs")
m_parser.add_argument("--from_db", required=True)
m_parser.add_argument("--to_db", required=True)
# Count command
c_parser = subparsers.add_parser("count", help="Count results for a query")
c_parser.add_argument("query")
c_parser.add_argument(
"--dataset",
default="uniprotkb",
help="Dataset to search in (e.g. uniprotkb, uniparc, unipref)",
)
# SPARQL command
sp_parser = subparsers.add_parser("sparql", help="Run SPARQL query")
sp_parser.add_argument("query")
# Stream command
st_parser = subparsers.add_parser(
"stream",
help="Stream ALL results for a bulk query (up to 10M entries, no limit)",
)
st_parser.add_argument("query")
st_parser.add_argument(
"--dataset",
default="uniprotkb",
help="Dataset to search in (e.g. uniprotkb, uniparc, unipref)",
)
st_parser.add_argument("--format", default="tsv")
st_parser.add_argument("--fields")
args = parser.parse_args()
# Validate that --format is lowercase (UniProt API requires lowercase).
if hasattr(args, "format") and args.format != args.format.lower():
parser.error(
f"Invalid format '{args.format}': format must be lowercase"
f" (e.g. 'json', 'tsv', 'fasta'). Got '{args.format}',"
f" did you mean '{args.format.lower()}'?"
)
if args.command == "search":
search_fields = args.fields.split(",") if args.fields else None
result_iterator = search_proteins(
args.query,
args.dataset,
output_format=args.format,
limit=args.limit,
fields=search_fields,
)
for page in result_iterator:
if args.format == "json":
print(json.dumps(page, indent=2))
else:
print(page)
elif args.command == "get":
result = get_entry(
args.accession,
args.dataset,
output_format=args.format,
)
if args.format == "json":
print(json.dumps(result, indent=2))
else:
print(result)
elif args.command == "count":
print(get_count(args.query, args.dataset))
elif args.command == "map":
print(
json.dumps(
run_id_mapping(
args.ids.split(","),
args.from_db,
args.to_db,
),
indent=2,
)
)
elif args.command == "sparql":
print(json.dumps(sparql_query(args.query), indent=2))
elif args.command == "stream":
stream_fields = args.fields.split(",") if args.fields else None
for row in stream_results(
args.query,
args.dataset,
output_format=args.format,
fields=stream_fields,
):
print(row)
elif not args.command:
parser.print_help()
Related skills
How it compares
Choose uniprot-database for protein-centric records; choose clinvar-database for clinical genetic variant significance.
FAQ
Which UniProt databases does uniprot-database access?
uniprot-database accesses UniProtKB, UniParc, and UniRef for protein metadata, sequences, taxonomy, and functional annotations. Identifier mapping and publication-linked annotations are supported use cases.
What tasks should not use uniprot-database?
uniprot-database should not be used for sequence alignment, protein folding, or sequence similarity search. The skill readme directs those workflows to specialized alignment and folding skills instead.
Is Uniprot 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.