
Embl Ebi Ols
- 1.3k installs
- 2.6k repo stars
- Updated July 7, 2026
- google-deepmind/science-skills
EMBL-EBI OLS is a Claude Code skill that gives coding agents reliable access to biomedical and life-science ontologies via the EMBL-EBI OLS4 API for developers who need standardized ontology terms in pipelines and apps.
About
EMBL-EBI OLS is a science-skills reference from google-deepmind/science-skills that documents the OLS4 REST API at https://www.ebi.ac.uk/ols4/api for ontology search, autocomplete, and term retrieval. The skill catalogs key endpoints including /search, /suggest, /select, /ontologies, and /ontologies/{id}/terms with double-encoded IRI lookup patterns. Developers reach for EMBL-EBI OLS when bioinformatics scripts, annotation pipelines, or agent tools must resolve GO, EFO, or other controlled vocabularies without hand-maintaining term lists. The skill focuses on correct API usage for full-text search, ontology browsing, and class detail retrieval in life-science coding workflows.
- Full-text search across all public ontologies
- Autocomplete suggestions via the suggest endpoint
- Browse terms, parents, children, ancestors and descendants
- Support for both strict is-a and hierarchical transitive relations
- Returns graph JSON for any term
Embl Ebi Ols by the numbers
- 1,262 all-time installs (skills.sh)
- +168 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #908 of 16,546 AI & Agent Building 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 embl-ebi-olsAdd 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 EMBL-EBI ontology terms via API?
Give their coding agent reliable access to biomedical and life-science ontologies via the EMBL-EBI OLS API.
Who is it for?
Bioinformatics and life-science developers integrating standardized ontology lookup into agents, APIs, or annotation pipelines.
Skip if: Developers outside biomedical domains who do not need controlled vocabulary or ontology term resolution.
When should I use this skill?
A developer asks to search EMBL-EBI ontologies, autocomplete biomedical terms, or fetch OLS4 class details by IRI.
What you get
OLS4 API call patterns, ontology term mappings, and search/suggest integration code.
- OLS4 API integration patterns
- ontology term lookup code
Files
EMBL-EBI Ontology Lookup Service (OLS)
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.ebi.ac.uk/ols4/api-docs, 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 under scripts/ for all API interactions, including checking status. NEVER use curl or custom Python requests to query API directly.
- Rate Limiting & Resilience: You MUST respect EBI's Terms of Use with a
maximum 5 requests per second. The provided utility scripts automatically enforce this.
- Notification: If this skill is used, ensure this is mentioned in the
output.
When to Use — Quick Recipes
Use this skill whenever a user query matches one of these patterns:
- Definition of a disease, phenotype, or term → `get_term.py --obo_id <ID>
--summary`
- Subtypes or children of a term → `get_term.py --obo_id <ID>
--relations children`
- Parent of a term →
get_term.py --obo_id <ID> --relations parents - Ancestors / disease categories / classified under → `get_term.py
--obo_id <ID> --relations ancestors`
- Root terms of an ontology →
get_term.py --ontology <id> --roots - Hierarchical parents (is-a + part-of) → `get_term.py --obo_id <ID>
--relations hierarchicalParents`
- Structures part of / hierarchical children → `get_term.py --obo_id <ID>
--relations hierarchicalChildren`
- Compare direct vs hierarchical parents → `get_term.py --obo_id <ID>
--relations parents,hierarchicalParents`
- Search for a term (e.g., "apoptosis" in GO) → `search_ols.py --query "..."
--ontology <id>`
- Find a GO term matching a function → `search_ols.py --query "..."
--ontology go --exact`
- Search in MONDO, CHEBI, CL, UBERON → `search_ols.py --query
"..." --ontology <id> --defining`
- Paginate search results / next page → `search_ols.py --query "..."
--rows N --start <offset>`
- Autocomplete a partial name →
suggest_ols.py --query "..." - Ontology metadata (e.g., EFO info) →
get_ontology.py --id <id> - OLS index statistics →
get_stats.py
Multi-step queries (e.g., "What is the parent of myocardial infarction?"):
When the user names a term but you don't know its OBO ID, complete in
exactly 2 steps — do NOT search across multiple ontologies:
>
1. Search in the single most appropriate ontology: `search_ols.py --query
"myocardial infarction" --ontology doid --exact --rows 1 --output
/tmp/step1.json`
2. Get relations using the OBO ID from step 1: `get_term.py --obo_id
DOID:5844 --relations parents --output /tmp/step2.json`
>
Ontology selection rule: ALWAYS use doid for common human diseases(e.g., diabetes, cancer),hpfor phenotypes,gofor gene functions,
chebifor chemicals,uberonfor anatomy,clfor cell types. Usemondo
ONLY when cross-species context is explicitly mentioned or needed.
Utility Scripts
1. Search Terms Across Ontologies
Search for ontology terms by keyword and return clean JSON.
uv run scripts/search_ols.py --query "diabetes" \
--rows 5 --output /tmp/ols_search_results.json 2>/dev/nullImportant: --output is required for all scripts. Results are alwayswritten to the specified file. For larger output, you can limit --rows(e.g., 5-10) or paginate using --start.Returned Fields: JSON results include iri, label, description, ontology_name, ontology_prefix, obo_id, short_form, type, is_defining_ontology, and exact_synonyms.
Pagination: Output includes a pagination block with start, rows, and has_more so you can decide whether to fetch more results.
Options:
-
--query: Search string (required). Searches labels, synonyms,
descriptions, and identifiers.
-
--ontology: Filter by ontology ID (e.g.,go,doid,efo,hp).
Recommended when you know which ontology to search — avoids noise from 250+ ontologies.
-
--type: Filter by entity type:class,property,individual, or
ontology.
-
--exact: Flag for exact label match only. **Use this for entity
resolution** when mapping a user's string to a specific ontology term ID.
-
--defining: Only return terms from their defining (authoritative)
ontology. E.g., GO:0005634 only from GO, not cross-referenced copies.
-
--obsolete: Flag to include obsolete terms in results. -
--local: Only return terms in their defining ontology. -
--childrenOf: Restrict to children of given term IRI(s), comma-separated. -
--allChildrenOf: Restrict to all children including transitive relations
(part of, develops from), comma-separated IRIs.
-
--queryFields: Comma-separated fields to search in (e.g.,
label,synonym,description).
-
--fieldList: Comma-separated fields to return. -
--groupField: Group results by unique IRI. -
--isLeaf: Only return leaf terms (no children). -
--rows: Number of results to return (default 10). -
--start: Pagination offset (default 0). -
--output: File path to save results (required).
2. Autocomplete / Suggest
Get autocomplete suggestions for partial term names.
uv run scripts/suggest_ols.py --query "diabet" --rows 5 \
--output /tmp/ols_suggest.json 2>/dev/nullOptions:
-
--query: Partial term to autocomplete (required). -
--ontology: Filter by ontology ID(s), comma-separated. -
--rows: Number of suggestions (default 10). -
--start: Pagination offset (default 0). -
--output: File path to save results (default: stdout).
3. Get Term Details
Retrieve full details for a specific ontology term by its OBO ID or IRI.
uv run scripts/get_term.py --obo_id "GO:0005634" \
--output /tmp/ols_term.json 2>/dev/nullReturned Fields: JSON includes iri, label, description, obo_id, synonyms, ontology_name, is_obsolete, is_defining_ontology, has_children, is_root, annotation, in_subset, and any requested relations.
Summary Mode: Use --summary to get a clean, human-readable block on stdout (Label, OBO ID, Ontology, Definition, Synonyms). The full JSON is always saved to the --output file.
uv run scripts/get_term.py --obo_id "GO:0005634" --summary \
--output /tmp/nucleus_full.jsonOptions:
-
--obo_id: OBO-style identifier (e.g.,GO:0005634,DOID:9351). Mutually
exclusive with --iri. Auto-converts to IRI with double encoding.
-
--iri: Full IRI of the term. Mutually exclusive with--obo_id. -
--ontology: Ontology ID (auto-derived from--obo_idif not provided). -
--relations: Comma-separated list of relations to fetch.
- Direct (is-a only):
parents,children,ancestors,
descendants
- Hierarchical (is-a + transitive like "part of", "develops from"):
hierarchicalParents, hierarchicalChildren, hierarchicalAncestors, hierarchicalDescendants
- Graph:
graph— full graph JSON for a term
Note: Use hierarchical variants for anatomical/developmental
ontologies (UBERON, CL) where transitive relations like "part of" and
"develops from" are critical for navigating the hierarchy.
-
--roots: List root terms of the ontology (requires--ontology).
-
--preferred_roots: List preferred root terms (requires--ontology).
-
--summary: Human-readable summary on stdout, full JSON to--output.
-
--output: File path to save results (default: stdout).
4. Get Property Details
Retrieve details for an ontology property (relation type) with hierarchy.
uv run scripts/get_property.py --obo_id "BFO:0000051" --ontology go \
--output /tmp/ols_property.json 2>/dev/nullOptions:
-
--obo_id: OBO-style ID of the property. Mutually exclusive with--iri. -
--iri: Full IRI of the property. Mutually exclusive with--obo_id. -
--ontology: Ontology ID (required with--iri). -
--relations: Comma-separated:parents,children,ancestors,
descendants.
-
--roots: List root properties of the ontology (requires--ontology). -
--output: File path to save results (default: stdout).
5. Get Individual Details
Retrieve details for an ontology individual (instance).
uv run scripts/get_individual.py --obo_id "IAO:0000103" --ontology iao --types \
--output /tmp/ols_individual.json 2>/dev/nullOptions:
-
--obo_id: OBO-style ID. Mutually exclusive with--iri. -
--iri: Full IRI. Mutually exclusive with--obo_id. -
--ontology: Ontology ID (required with--iri). -
--types: Fetch the direct types (classes) of this individual. -
--alltypes: Fetch all types including ancestor classes. -
--output: File path to save results (default: stdout).
6. Get Ontology Information
List available ontologies or retrieve details for a specific one.
uv run scripts/get_ontology.py --id go \
--output /tmp/ols_ontology.json 2>/dev/nullOptions:
-
--id: Specific ontology ID (e.g.,go,efo,doid). If omitted, lists
all ontologies.
-
--page: Page number for pagination (default 0). -
--size: Number of ontologies per page (default 20). -
--output: File path to save results (default: stdout).
7. Get OLS Statistics
Retrieve index statistics (total ontologies, classes, properties, individuals).
uv run scripts/get_stats.py --output /tmp/ols_stats.json 2>/dev/nullOptions:
-
--output: File path to save results (default: stdout).
Reference
- API Reference: See
references/api_reference.md for common ontology IDs, OBO ID format, and key API endpoints.
Workflow
1. Use suggest_ols.py for autocomplete when you have a partial term name. 2. Search for terms using search_ols.py. Use --defining to prioritize authoritative definitions. Use --exact for entity resolution. 3. If full details are needed, use get_term.py with the OBO ID or IRI. Use --summary for a concise view. 4. To explore a term's hierarchy, use get_term.py --relations parents,children for is-a only, or --relations hierarchicalParents,hierarchicalChildren for "part of" etc. 5. To explore from the top down, use get_term.py --ontology go --roots. 6. For properties or individuals, use get_property.py or get_individual.py. 7. To discover available ontologies, use get_ontology.py. 8. To check OLS index status, use get_stats.py.
OLS API Reference
Base URL: https://www.ebi.ac.uk/ols4/api
Key Endpoints
Search & Suggest
| Endpoint | Description |
|---|---|
/search?q={query} | Full-text search across all ontologies |
/suggest?q={query} | Autocomplete suggestions for partial term names |
/select?q={query} | Select endpoint (similar to search with additional filters) |
Ontologies
| Endpoint | Description |
|---|---|
/ontologies | List all ontologies |
/ontologies/{id} | Get ontology details |
Terms (Classes)
| Endpoint | Description |
|---|---|
/ontologies/{id}/terms | List/browse terms in an ontology |
/ontologies/{id}/terms/{iri} | Get term by double-encoded IRI |
/ontologies/{id}/terms/{iri}/parents | Direct parents (is-a only) |
/ontologies/{id}/terms/{iri}/children | Direct children (is-a only) |
/ontologies/{id}/terms/{iri}/ancestors | All ancestors (is-a only) |
/ontologies/{id}/terms/{iri}/descendants | All descendants (is-a only) |
/ontologies/{id}/terms/{iri}/hierarchicalParents | Parents including transitive relations (part_of, develops_from) |
/ontologies/{id}/terms/{iri}/hierarchicalChildren | Children including transitive relations |
/ontologies/{id}/terms/{iri}/hierarchicalAncestors | All ancestors including transitive relations |
/ontologies/{id}/terms/{iri}/hierarchicalDescendants | All descendants including transitive relations |
/ontologies/{id}/terms/{iri}/graph | Graph JSON for a term |
/ontologies/{id}/terms/roots | Root terms of an ontology |
/ontologies/{id}/terms/preferredRoots | Preferred root terms |
Properties
| Endpoint | Description |
|---|---|
/ontologies/{id}/properties | List properties in an ontology |
/ontologies/{id}/properties/{iri} | Get property details |
/ontologies/{id}/properties/{iri}/parents | Property parents |
/ontologies/{id}/properties/{iri}/children | Property children |
/ontologies/{id}/properties/{iri}/ancestors | Property ancestors |
/ontologies/{id}/properties/{iri}/descendants | Property descendants |
/ontologies/{id}/properties/roots | Root properties |
Individuals (Instances)
| Endpoint | Description |
|---|---|
/ontologies/{id}/individuals | List individuals in an ontology |
/ontologies/{id}/individuals/{iri} | Get individual details |
/ontologies/{id}/individuals/{iri}/types | Get direct types (classes) |
/ontologies/{id}/individuals/{iri}/alltypes | Get all types including ancestors |
Statistics
| Endpoint | Description |
|---|---|
/v2/stats | Index statistics (ontology/class/property/individual counts) |
OBO ID Format
OBO IDs follow the pattern PREFIX:NUMBER, e.g., GO:0005634.
The corresponding IRI is typically: http://purl.obolibrary.org/obo/PREFIX_NUMBER (e.g., http://purl.obolibrary.org/obo/GO_0005634).
When passing IRIs to the API, they must be double URL-encoded.
Hierarchical vs Regular Relations
- Regular (
parents,children,ancestors,descendants): Follow only
subClassOf (is-a) relationships.
- Hierarchical (
hierarchicalParents,hierarchicalChildren, etc.):
Follow subClassOf plus transitive properties like part of, develops from, etc. This gives a more complete picture of the ontology structure.
Common Ontology IDs
| ID | Name | Focus |
|---|---|---|
go | Gene Ontology | Molecular function, biological process, cellular component |
doid | Disease Ontology | Human disease classification |
efo | Experimental Factor Ontology | Experimental variables (GWAS, expression) |
hp | Human Phenotype Ontology | Human phenotypic abnormalities |
chebi | Chemical Entities of Biological Interest | Small molecules |
mondo | Mondo Disease Ontology | Cross-species disease integration |
ncit | NCI Thesaurus | Cancer-related terminology |
cl | Cell Ontology | Cell types |
uberon | Uberon | Cross-species anatomical structures |
so | Sequence Ontology | Genomic sequence features |
pato | Phenotype And Trait Ontology | Phenotypic qualities |
envo | Environment Ontology | Environmental biomes and habitats |
obi | Ontology for Biomedical Investigations | Experimental assays and protocols |
iao | Information Artifact Ontology | Information entities |
duo | Data Use Ontology | Data use permissions and conditions |
Search Parameters
| Parameter | Description |
|---|---|
q | Search query (required) |
ontology | Filter by ontology ID |
type | class, property, individual, or ontology |
exact | true for exact label match |
obsoletes | false to exclude obsolete terms |
local | true to only return terms in their defining ontology |
childrenOf | Restrict to children of given IRI(s) |
allChildrenOf | Restrict to all children (incl. transitive relations) |
queryFields | Fields to search in |
fieldList | Fields to return |
groupField | Group results by IRI |
isLeaf | true for leaf terms only |
rows | Results per page (default 10, max 500) |
start | Pagination offset |
# 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.
"""Retrieves individual (instance) information from the EMBL-EBI OLS.
This script fetches ontology individual details from the OLS4 API,
including their types (classes they are instances of).
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import urllib.error
import ols_utils
def get_individual(args: argparse.Namespace):
"""Retrieves and outputs individual information from the EMBL-EBI OLS.
Fetches details for a specific ontology individual (instance) based on either
an OBO ID or a full IRI. Optionally retrieves the individual's direct types
and all types (including ancestors) from the OLS API. The results are
written to a specified output file or standard output.
Args:
args: An argparse.Namespace object containing the command-line arguments:
* obo_id: OBO-style ID of the individual.
* iri: Full IRI of the individual.
* ontology: Ontology ID (required with --iri).
* types: Whether to fetch direct types.
* alltypes: Whether to fetch all types.
* output: Path to the output file.
"""
try:
if args.obo_id:
ontology = ols_utils.resolve_ontology(args.obo_id, args.ontology)
iri = ols_utils.obo_id_to_iri(args.obo_id)
else:
if not args.ontology:
ols_utils.error_exit(
"--ontology is required when using --iri", args.output
)
ontology = args.ontology.lower()
iri = args.iri
encoded_iri = ols_utils.double_encode_iri(iri)
ind_url = (
f"{ols_utils.BASE_URL}/ontologies/{ontology}/individuals/{encoded_iri}"
)
data = ols_utils.CLIENT.fetch_json(ind_url)
individual = {
"iri": data.get("iri", ""),
"label": data.get("label", ""),
"description": data.get("description", []),
"obo_id": data.get("obo_id", ""),
"ontology_name": data.get("ontology_name", ""),
"ontology_prefix": data.get("ontology_prefix", ""),
"is_obsolete": data.get("is_obsolete", False),
"short_form": data.get("short_form", ""),
"synonyms": data.get("synonyms", []),
"annotation": data.get("annotation", {}),
}
if args.types:
types_url = f"{ind_url}/types"
try:
types_data = ols_utils.CLIENT.fetch_json(types_url)
embedded = types_data.get("_embedded", {}).get("terms", [])
individual["types"] = [
{
"iri": t.get("iri", ""),
"label": t.get("label", ""),
"obo_id": t.get("obo_id", ""),
}
for t in embedded
]
except urllib.error.HTTPError:
individual["types"] = []
if args.alltypes:
alltypes_url = f"{ind_url}/alltypes"
try:
alltypes_data = ols_utils.CLIENT.fetch_json(alltypes_url)
embedded = alltypes_data.get("_embedded", {}).get("properties", [])
individual["alltypes"] = [
{
"iri": t.get("iri", ""),
"label": t.get("label", ""),
"obo_id": t.get("obo_id", ""),
}
for t in embedded
]
except urllib.error.HTTPError:
individual["alltypes"] = []
ols_utils.write_output(
{"status": "success", "individual": individual}, args.output
)
except urllib.error.HTTPError as e:
if e.code == 404:
identifier = args.obo_id or args.iri
ols_utils.error_exit(
f"Individual not found: {identifier}. Check the ID.", args.output
)
else:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the script.
Returns:
An argparse.Namespace containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Get individual details from EMBL-EBI OLS"
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"--obo_id",
type=str,
help="OBO-style ID (e.g., 'IAO:0000103')",
)
group.add_argument(
"--iri",
type=str,
help="Full IRI of the individual",
)
parser.add_argument(
"--ontology",
type=str,
help="Ontology ID (required with --iri, auto-derived from --obo_id)",
)
parser.add_argument(
"--types",
action="store_true",
help="Also fetch the direct types (classes) of this individual",
)
parser.add_argument(
"--alltypes",
action="store_true",
help="Fetch all types (including ancestors) of this individual",
)
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
get_individual(main_args)
# 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.
"""Retrieves ontology information from the EMBL-EBI Ontology Lookup Service.
This script lists available ontologies or fetches details for a specific
ontology from the OLS4 API.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import urllib.error
import ols_utils
def get_ontology(args: argparse.Namespace):
"""Fetches and outputs ontology information based on provided arguments.
If args.id is provided, it fetches details for that specific ontology.
Otherwise, it lists available ontologies with pagination. The output is
written to a file or stdout as JSON.
Args:
args: An argparse.Namespace containing the command-line arguments, including
'id', 'page', 'size', and 'output'.
"""
try:
if args.id:
url = f"{ols_utils.BASE_URL}/ontologies/{args.id.lower()}"
data = ols_utils.CLIENT.fetch_json(url)
config = data.get("config", {})
ontology = {
"ontologyId": data.get("ontologyId", ""),
"title": config.get("title", ""),
"description": config.get("description", ""),
"namespace": config.get("namespace", ""),
"homepage": config.get("homepage", ""),
"numberOfTerms": data.get("numberOfTerms", 0),
"numberOfProperties": data.get("numberOfProperties", 0),
"numberOfIndividuals": data.get("numberOfIndividuals", 0),
"status": data.get("status", ""),
"loaded": data.get("loaded", ""),
"updated": data.get("updated", ""),
}
ols_utils.write_output(
{"status": "success", "ontology": ontology}, args.output
)
else:
url = f"{ols_utils.BASE_URL}/ontologies?page={args.page}&size={args.size}"
data = ols_utils.CLIENT.fetch_json(url)
embedded = data.get("_embedded", {}).get("ontologies", [])
page_info = data.get("page", {})
ontologies = []
for ont in embedded:
config = ont.get("config", {})
ontologies.append({
"ontologyId": ont.get("ontologyId", ""),
"title": config.get("title", ""),
"description": config.get("description", ""),
"numberOfTerms": ont.get("numberOfTerms", 0),
"status": ont.get("status", ""),
})
ols_utils.write_output(
{
"status": "success",
"total_ontologies": page_info.get("totalElements", 0),
"page": page_info.get("number", 0),
"total_pages": page_info.get("totalPages", 0),
"results_count": len(ontologies),
"ontologies": ontologies,
},
args.output,
)
except urllib.error.HTTPError as e:
if e.code == 404:
ols_utils.error_exit(
f"Ontology not found: '{args.id}'. "
"Use --id without arguments to list available ontologies.",
args.output,
)
else:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the ontology script.
Returns:
An argparse.Namespace containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Get ontology information from EMBL-EBI OLS"
)
parser.add_argument(
"--id",
type=str,
help="Ontology ID (e.g., 'go', 'efo', 'doid'). If omitted, lists all.",
)
parser.add_argument(
"--page", type=int, default=0, help="Page number for pagination"
)
parser.add_argument(
"--size", type=int, default=20, help="Number of ontologies per page"
)
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
get_ontology(main_args)
# 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.
"""Retrieves property information from the EMBL-EBI Ontology Lookup Service.
This script fetches ontology property details, including hierarchy
(parents, children, ancestors, descendants) and root properties.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import sys
import urllib.error
import ols_utils
def get_roots(args: argparse.Namespace):
"""Fetches and outputs the root properties for a given ontology.
Args:
args: An argparse.Namespace object containing the command-line arguments.
Requires `args.ontology` to be set. The output is written based on
`args.output`.
"""
if not args.ontology:
ols_utils.error_exit("--ontology is required with --roots", args.output)
ontology = args.ontology.lower()
url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/properties/roots"
try:
data = ols_utils.CLIENT.fetch_json(url)
embedded = data.get("_embedded", {}).get("properties", [])
props = [
{
"iri": p.get("iri", ""),
"label": p.get("label", ""),
"obo_id": p.get("obo_id", ""),
"short_form": p.get("short_form", ""),
"has_children": p.get("has_children", False),
}
for p in embedded
]
ols_utils.write_output(
{
"status": "success",
"ontology": ontology,
"type": "property_roots",
"results_count": len(props),
"properties": props,
},
args.output,
)
except urllib.error.HTTPError as e:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
except urllib.error.URLError as e:
ols_utils.error_exit(f"Network error: {str(e)}", args.output)
def get_property(args: argparse.Namespace):
"""Fetches and outputs details for a specific ontology property.
Retrieves information about a property identified by either an OBO ID or IRI,
including optional related properties like parents, children, ancestors, and
descendants. The output is written based on `args.output`.
Args:
args: An argparse.Namespace object containing the command-line arguments.
Requires either `args.obo_id` or `args.iri` to be set. If `args.iri` is
used, `args.ontology` must also be provided. `args.relations` can specify
which related properties to fetch.
"""
try:
if args.obo_id:
ontology = ols_utils.resolve_ontology(args.obo_id, args.ontology)
iri = ols_utils.obo_id_to_iri(args.obo_id)
else:
if not args.ontology:
ols_utils.error_exit(
"--ontology is required when using --iri", args.output
)
ontology = args.ontology.lower()
iri = args.iri
encoded_iri = ols_utils.double_encode_iri(iri)
prop_url = (
f"{ols_utils.BASE_URL}/ontologies/{ontology}/properties/{encoded_iri}"
)
data = ols_utils.CLIENT.fetch_json(prop_url)
prop = {
"iri": data.get("iri", ""),
"label": data.get("label", ""),
"description": data.get("description", []),
"obo_id": data.get("obo_id", ""),
"ontology_name": data.get("ontology_name", ""),
"ontology_prefix": data.get("ontology_prefix", ""),
"is_obsolete": data.get("is_obsolete", False),
"has_children": data.get("has_children", False),
"is_root": data.get("is_root", False),
"short_form": data.get("short_form", ""),
"synonyms": data.get("synonyms", []),
"annotation": data.get("annotation", {}),
}
if args.relations:
valid = {"parents", "children", "ancestors", "descendants"}
requested = [r.strip().lower() for r in args.relations.split(",")]
links = data.get("_links", {})
for rel in requested:
if rel not in valid:
print(f"Warning: Skipping unknown relation '{rel}'", file=sys.stderr)
continue
rel_url = links.get(rel, {}).get("href")
if not rel_url:
rel_url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/properties/{encoded_iri}/{rel}"
try:
rel_data = ols_utils.CLIENT.fetch_json(rel_url)
embedded = rel_data.get("_embedded", {}).get("properties", [])
prop[rel] = [
{
"iri": p.get("iri", ""),
"label": p.get("label", ""),
"obo_id": p.get("obo_id", ""),
}
for p in embedded
]
except urllib.error.HTTPError:
prop[rel] = []
ols_utils.write_output({"status": "success", "property": prop}, args.output)
except urllib.error.HTTPError as e:
if e.code == 404:
identifier = args.obo_id or args.iri
ols_utils.error_exit(
f"Property not found: {identifier}. Check the ID.", args.output
)
else:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the script.
Returns:
An argparse.Namespace containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Get property details from EMBL-EBI OLS"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--obo_id",
type=str,
help="OBO-style ID of the property (e.g., 'BFO:0000051')",
)
group.add_argument(
"--iri",
type=str,
help="Full IRI of the property",
)
parser.add_argument(
"--ontology",
type=str,
help="Ontology ID (required with --iri, auto-derived from --obo_id)",
)
parser.add_argument(
"--relations",
type=str,
help="Comma-separated: parents, children, ancestors, descendants",
)
parser.add_argument(
"--roots",
action="store_true",
help="List root properties of the ontology (requires --ontology)",
)
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
if main_args.roots:
get_roots(main_args)
elif not main_args.obo_id and not main_args.iri:
ols_utils.error_exit("Must provide --obo_id, --iri, or --roots", None)
else:
get_property(main_args)
# 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.
"""Retrieves statistics from the EMBL-EBI Ontology Lookup Service.
This script fetches index statistics from the OLS4 v2 stats API,
including counts of ontologies, classes, properties, and individuals.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import ols_utils
def get_stats(args: argparse.Namespace):
"""Fetches and writes OLS index statistics.
This function calls the OLS4 v2 stats API, parses the JSON response,
and writes the extracted statistics to an output file or stdout.
Args:
args: An argparse.Namespace object containing command-line arguments,
including the 'output' file path.
"""
url = "https://www.ebi.ac.uk/ols4/api/v2/stats"
data = ols_utils.CLIENT.fetch_json(url)
stats = {
"numberOfOntologies": data.get("numberOfOntologies", 0),
"numberOfClasses": data.get("numberOfClasses", 0),
"numberOfProperties": data.get("numberOfProperties", 0),
"numberOfIndividuals": data.get("numberOfIndividuals", 0),
"lastModified": data.get("lastModified", ""),
}
ols_utils.write_output(
{"status": "success", "statistics": stats}, args.output
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Get OLS index statistics")
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
get_stats(main_args)
# 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.
"""Retrieves detailed information for a specific ontology term from OLS.
This script fetches term details from the EMBL-EBI Ontology Lookup Service
using either an OBO ID (e.g., GO:0005634) or a full IRI. It can also retrieve
hierarchical relations (parents, children, ancestors, descendants), including
hierarchical variants that follow transitive relations like 'part of'.
Additionally, it can list root terms or preferred root terms of an ontology.
Relation types:
Direct (is-a only):
parents, children, ancestors, descendants
Hierarchical (is-a + transitive relations like 'part of', 'develops from'):
hierarchicalParents, hierarchicalChildren,
hierarchicalAncestors, hierarchicalDescendants
Graph:
graph — returns the full graph JSON for a term
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import sys
from typing import Any
import urllib.error
import ols_utils
VALID_RELATIONS = {
"parents",
"children",
"ancestors",
"descendants",
"hierarchicalParents",
"hierarchicalChildren",
"hierarchicalAncestors",
"hierarchicalDescendants",
"graph",
}
def format_summary(term: dict[str, Any]) -> str:
"""Formats a term dictionary into a human-readable summary string.
Args:
term: A dictionary containing term details fetched from OLS.
Returns:
A string containing a formatted summary of the term.
"""
lines = []
lines.append(f"Label: {term.get('label', 'N/A')}")
lines.append(f"OBO ID: {term.get('obo_id', 'N/A')}")
lines.append(f"Ontology: {term.get('ontology_name', 'N/A')}")
lines.append(f"IRI: {term.get('iri', 'N/A')}")
desc = term.get("description", [])
if desc:
lines.append(f"Definition: {desc[0]}")
synonyms = term.get("synonyms", [])
if synonyms:
lines.append(f"Synonyms: {', '.join(synonyms)}")
lines.append(f"Obsolete: {term.get('is_obsolete', False)}")
lines.append(f"Has children: {term.get('has_children', False)}")
lines.append(f"Is root: {term.get('is_root', False)}")
for rel in VALID_RELATIONS - {"graph"}:
if rel in term:
labels = [t.get("label", t.get("obo_id", "?")) for t in term[rel]]
lines.append(f"{rel}: {', '.join(labels)}")
return "\n".join(lines)
def get_roots(args: argparse.Namespace):
"""Fetches and outputs root terms for a specified ontology.
Retrieves either all root terms or preferred root terms from the OLS
for the ontology provided in `args.ontology`. The results are written
to the file specified by `args.output` or to stdout.
Args:
args: An argparse.Namespace containing the parsed command-line arguments,
including 'ontology', 'preferred_roots', and 'output'.
"""
if not args.ontology:
ols_utils.error_exit("--ontology is required with --roots", args.output)
ontology = args.ontology.lower()
if args.preferred_roots:
url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/terms/preferredRoots"
else:
url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/terms/roots"
try:
data = ols_utils.CLIENT.fetch_json(url)
embedded = data.get("_embedded", {}).get("terms", [])
terms = [
{
"iri": t.get("iri", ""),
"label": t.get("label", ""),
"obo_id": t.get("obo_id", ""),
"short_form": t.get("short_form", ""),
"has_children": t.get("has_children", False),
}
for t in embedded
]
ols_utils.write_output(
{
"status": "success",
"ontology": ontology,
"type": "preferred_roots" if args.preferred_roots else "roots",
"results_count": len(terms),
"terms": terms,
},
args.output,
)
except urllib.error.HTTPError as e:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
except urllib.error.URLError as e:
ols_utils.error_exit(f"Network error: {str(e)}", args.output)
def get_term(args: argparse.Namespace):
"""Fetches and outputs detailed information for a specific ontology term.
Retrieves term details from the OLS based on either an OBO ID or an IRI.
Optionally fetches related terms (parents, children, etc.) and can output
a human-readable summary or the full JSON. The results are written
to the file specified by `args.output` or to stdout.
Args:
args: An argparse.Namespace containing the parsed command-line arguments,
including 'obo_id', 'iri', 'ontology', 'relations', 'summary', and
'output'.
"""
try:
if args.obo_id:
ontology = ols_utils.resolve_ontology(args.obo_id, args.ontology)
iri = ols_utils.obo_id_to_iri(args.obo_id)
else:
if not args.ontology:
ols_utils.error_exit(
"--ontology is required when using --iri", args.output
)
ontology = args.ontology.lower()
iri = args.iri
encoded_iri = ols_utils.double_encode_iri(iri)
term_url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/terms/{encoded_iri}"
data = ols_utils.CLIENT.fetch_json(term_url)
term = {
"iri": data.get("iri", ""),
"label": data.get("label", ""),
"description": data.get("description", []),
"obo_id": data.get("obo_id", ""),
"ontology_name": data.get("ontology_name", ""),
"ontology_prefix": data.get("ontology_prefix", ""),
"is_defining_ontology": data.get("is_defining_ontology", False),
"is_obsolete": data.get("is_obsolete", False),
"has_children": data.get("has_children", False),
"is_root": data.get("is_root", False),
"short_form": data.get("short_form", ""),
"synonyms": data.get("synonyms", []),
"annotation": data.get("annotation", {}),
"in_subset": data.get("in_subset", []),
}
if args.relations:
requested = [r.strip() for r in args.relations.split(",")]
links = data.get("_links", {})
for rel in requested:
if rel not in VALID_RELATIONS:
print(
f"Warning: Skipping unknown relation '{rel}'",
file=sys.stderr,
)
continue
if rel == "graph":
graph_url = links.get("graph", {}).get("href")
if not graph_url:
graph_url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/terms/{encoded_iri}/graph"
graph_data = ols_utils.CLIENT.fetch_json(graph_url)
term["graph"] = graph_data
continue
rel_url = links.get(rel, {}).get("href")
if not rel_url:
rel_url = f"{ols_utils.BASE_URL}/ontologies/{ontology}/terms/{encoded_iri}/{rel}"
try:
term[rel] = []
while rel_url:
# API returns http links but client expects https to match base_url
rel_url = rel_url.replace("http://", "https://")
rel_data = ols_utils.CLIENT.fetch_json(rel_url)
embedded = rel_data.get("_embedded", {}).get("terms", [])
term[rel].extend([
{
"iri": t.get("iri", ""),
"label": t.get("label", ""),
"obo_id": t.get("obo_id", ""),
}
for t in embedded
])
rel_url = rel_data.get("_links", {}).get("next", {}).get("href")
except urllib.error.HTTPError:
term[rel] = []
result = {"status": "success", "term": term}
if args.summary:
print(format_summary(term))
if args.output:
ols_utils.write_output(result, args.output)
else:
ols_utils.write_output(result, args.output)
except urllib.error.HTTPError as e:
if e.code == 404:
identifier = args.obo_id or args.iri
ols_utils.error_exit(
f"Term not found: {identifier}. Check the ID.", args.output
)
else:
ols_utils.error_exit(f"HTTP Error {e.code}: {e.reason}", args.output)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the get_term script.
Returns:
An argparse.Namespace containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Get term details from EMBL-EBI OLS"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--obo_id",
type=str,
help="OBO-style ID (e.g., 'GO:0005634', 'DOID:9351')",
)
group.add_argument(
"--iri",
type=str,
help="Full IRI of the term",
)
parser.add_argument(
"--ontology",
type=str,
help="Ontology ID (auto-derived from --obo_id if not provided)",
)
parser.add_argument(
"--relations",
type=str,
help=(
"Comma-separated relations to fetch. "
"Direct (is-a only): parents, children, ancestors, descendants. "
"Hierarchical (is-a + transitive like 'part of', 'develops from'): "
"hierarchicalParents, hierarchicalChildren, "
"hierarchicalAncestors, hierarchicalDescendants. "
"Also: graph"
),
)
parser.add_argument(
"--roots",
action="store_true",
help="List root terms of the ontology (requires --ontology)",
)
parser.add_argument(
"--preferred_roots",
action="store_true",
help="List preferred root terms of the ontology (requires --ontology)",
)
parser.add_argument(
"--summary",
action="store_true",
help=(
"Output a clean human-readable summary to stdout. "
"If --output is also specified, the full JSON is saved to that file."
),
)
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
if main_args.roots or main_args.preferred_roots:
get_roots(main_args)
elif not main_args.obo_id and not main_args.iri:
ols_utils.error_exit(
"Must provide --obo_id, --iri, --roots, or --preferred_roots",
main_args.output,
)
else:
get_term(main_args)
# 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.
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
"""Shared utilities for OLS skill scripts.
Provides common functions for HTTP requests with retry logic,
JSON output handling, and OBO ID to IRI conversion.
"""
from __future__ import annotations
import json
import sys
from typing import Any
import urllib.parse
from science_skills.skills.scienceskillscommon import http_client
RATE_LIMIT_DELAY = 0.2
MAX_RETRIES = 10
BASE_URL = "https://www.ebi.ac.uk/ols4/api"
CLIENT = http_client.HttpClient(BASE_URL, qps=5.0)
OBO_PREFIX_TO_ONTOLOGY: dict[str, str] = {
"GO": "go",
"DOID": "doid",
"EFO": "efo",
"HP": "hp",
"CHEBI": "chebi",
"MONDO": "mondo",
"NCIT": "ncit",
"CL": "cl",
"UBERON": "uberon",
"SO": "so",
"PR": "pr",
"PATO": "pato",
"MP": "mp",
"OBI": "obi",
"BFO": "bfo",
"IAO": "iao",
"ENVO": "envo",
"PO": "po",
"CLO": "clo",
"DUO": "duo",
}
def write_output(data: dict[str, Any], output_path: str | None):
"""Write `data` as indented JSON to `output_path`, or print to stdout."""
text = json.dumps(data, indent=2)
if output_path:
with open(output_path, "w") as f:
f.write(text)
print(f"Results saved to {output_path}", file=sys.stderr)
else:
print(text)
def obo_id_to_iri(obo_id: str) -> str:
"""Convert an OBO-style ID (e.g. 'GO:0005634') to its canonical IRI."""
return "http://purl.obolibrary.org/obo/" + obo_id.replace(":", "_")
def double_encode_iri(iri: str) -> str:
"""Double-URL-encode an IRI for use in OLS API path segments."""
return urllib.parse.quote(urllib.parse.quote(iri, safe=""), safe="")
def resolve_ontology(obo_id: str, ontology: str | None) -> str:
"""Return the ontology slug from an explicit value or the OBO ID prefix."""
if ontology:
return ontology.lower()
prefix = obo_id.split(":")[0].upper()
if prefix in OBO_PREFIX_TO_ONTOLOGY:
return OBO_PREFIX_TO_ONTOLOGY[prefix]
return prefix.lower()
def error_exit(message: str, output_path: str | None = None):
"""Write a JSON error object and exit with status 1."""
write_output({"status": "error", "message": message}, output_path)
sys.exit(1)
# 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.
"""Searches the EMBL-EBI Ontology Lookup Service and returns results as JSON.
This script queries the OLS4 search API for ontology terms matching a keyword.
It parses the JSON response and outputs structured results.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import urllib.parse
import ols_utils
def search_ols(args: argparse.Namespace):
"""Searches the OLS API with the given arguments and writes the results.
Constructs a query URL from the provided argparse namespace, fetches the
JSON response from the OLS search API, and parses the results. The results
are then written to a file or stdout in JSON format.
Args:
args: An argparse.Namespace object containing the command-line arguments.
"""
params = {
"q": args.query,
"rows": args.rows,
"start": args.start,
}
if args.ontology:
params["ontology"] = args.ontology.lower()
if args.type:
params["type"] = args.type
if args.exact:
params["exact"] = "true"
if not args.obsolete:
params["obsoletes"] = "false"
if args.local:
params["local"] = "true"
if args.defining:
params["is_defining_ontology"] = "true"
if args.groupField:
params["groupField"] = args.groupField
if args.isLeaf:
params["isLeaf"] = "true"
if args.queryFields:
params["queryFields"] = args.queryFields
if args.fieldList:
params["fieldList"] = args.fieldList
query_string = urllib.parse.urlencode(params)
if args.childrenOf:
for iri in args.childrenOf.split(","):
query_string += "&childrenOf=" + urllib.parse.quote(iri.strip())
if args.allChildrenOf:
for iri in args.allChildrenOf.split(","):
query_string += "&allChildrenOf=" + urllib.parse.quote(iri.strip())
url = f"{ols_utils.BASE_URL}/search?{query_string}"
data = ols_utils.CLIENT.fetch_json(url)
docs = data.get("response", {}).get("docs", [])
num_found = data.get("response", {}).get("numFound", 0)
results = []
for doc in docs:
term = {
"iri": doc.get("iri", ""),
"label": doc.get("label", ""),
"description": doc.get("description", []),
"ontology_name": doc.get("ontology_name", ""),
"ontology_prefix": doc.get("ontology_prefix", ""),
"obo_id": doc.get("obo_id", ""),
"short_form": doc.get("short_form", ""),
"type": doc.get("type", ""),
"is_defining_ontology": doc.get("is_defining_ontology", False),
"exact_synonyms": doc.get("exact_synonyms", []),
}
results.append(term)
ols_utils.write_output(
{
"status": "success",
"total_found": num_found,
"results_count": len(results),
"pagination": {
"start": args.start,
"rows": args.rows,
"has_more": (args.start + args.rows) < num_found,
},
"terms": results,
},
args.output,
)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the OLS search script.
Returns:
An argparse.Namespace object containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Search EMBL-EBI OLS for ontology terms"
)
parser.add_argument(
"--query",
type=str,
required=True,
help="Search query string (e.g., 'diabetes', 'apoptosis')",
)
parser.add_argument(
"--ontology",
type=str,
help="Filter by ontology ID (e.g., 'go', 'doid', 'efo')",
)
parser.add_argument(
"--type",
type=str,
choices=["class", "property", "individual", "ontology"],
help="Filter by entity type",
)
parser.add_argument(
"--exact",
action="store_true",
help=(
"Only return exact label matches. Use this for entity resolution "
"when mapping a user string to a specific ontology term ID."
),
)
parser.add_argument(
"--defining",
action="store_true",
help=(
"Only return terms from their defining (authoritative) ontology. "
"E.g., GO:0005634 only from GO, not cross-referenced copies."
),
)
parser.add_argument(
"--obsolete",
action="store_true",
help="Include obsolete terms in results",
)
parser.add_argument(
"--local",
action="store_true",
help=(
"Only return terms in their defining ontology (e.g., GO terms only"
" from GO, not from ontologies that reference them)"
),
)
parser.add_argument(
"--childrenOf",
type=str,
help="Restrict to children of given term IRI(s), comma-separated",
)
parser.add_argument(
"--allChildrenOf",
type=str,
help=(
"Restrict to all children of given term IRI(s), comma-separated "
"(includes transitive relations like 'part of', 'develops from')"
),
)
parser.add_argument(
"--queryFields",
type=str,
help=(
"Comma-separated fields to search in "
"(default: label,synonym,description,short_form,obo_id,annotations,"
"logical_description,iri)"
),
)
parser.add_argument(
"--fieldList",
type=str,
help=(
"Comma-separated fields to return "
"(default: iri,label,short_form,obo_id,ontology_name,ontology_prefix,"
"description,type)"
),
)
parser.add_argument(
"--groupField",
type=str,
help="Group results by unique id (IRI)",
)
parser.add_argument(
"--isLeaf",
action="store_true",
help="Only return leaf terms (terms with no children)",
)
parser.add_argument(
"--rows", type=int, default=10, help="Number of results to return"
)
parser.add_argument("--start", type=int, default=0, help="Pagination offset")
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
search_ols(main_args)
# 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.
"""Provides autocomplete suggestions from the EMBL-EBI Ontology Lookup Service.
This script queries the OLS4 suggest API for term name completions,
useful for interactive term discovery and autocomplete workflows.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "scienceskillscommon",
# ]
# [tool.uv.sources]
# scienceskillscommon = { path = "../../scienceskillscommon" }
# ///
import argparse
import urllib.parse
import ols_utils
def suggest_ols(args: argparse.Namespace):
"""Queries the OLS suggest API and writes the results.
Fetches autocomplete suggestions from the EMBL-EBI OLS based on the provided
arguments and writes the formatted output to a file or stdout. Handles
potential API and network errors.
Args:
args: An argparse.Namespace object containing the command-line arguments:
* query (str): The partial term to autocomplete.
* ontology (str, optional): Comma-separated ontology IDs for filtering.
* rows (int): Number of suggestions to return.
* start (int): Pagination offset.
* output (str, optional): Path to the output file.
"""
params = {
"q": args.query,
"rows": args.rows,
"start": args.start,
}
query_string = urllib.parse.urlencode(params)
if args.ontology:
for ont in args.ontology.split(","):
query_string += "&ontology=" + urllib.parse.quote(ont.strip().lower())
url = f"{ols_utils.BASE_URL}/suggest?{query_string}"
data = ols_utils.CLIENT.fetch_json(url)
docs = data.get("response", {}).get("docs", [])
num_found = data.get("response", {}).get("numFound", 0)
suggestions = []
for doc in docs:
suggestions.append({
"autosuggest": doc.get("autosuggest", ""),
"label": doc.get("label", ""),
"ontology_name": doc.get("ontology_name", ""),
"ontology_prefix": doc.get("ontology_prefix", ""),
"short_form": doc.get("short_form", ""),
"obo_id": doc.get("obo_id", ""),
})
ols_utils.write_output(
{
"status": "success",
"total_found": num_found,
"results_count": len(suggestions),
"pagination": {
"start": args.start,
"rows": args.rows,
"has_more": (args.start + args.rows) < num_found,
},
"suggestions": suggestions,
},
args.output,
)
def parse_args() -> argparse.Namespace:
"""Parses command-line arguments for the OLS suggest script.
Returns:
An argparse.Namespace containing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Get autocomplete suggestions from EMBL-EBI OLS"
)
parser.add_argument(
"--query",
type=str,
required=True,
help="Partial term to autocomplete (e.g., 'diabet', 'apopt')",
)
parser.add_argument(
"--ontology",
type=str,
help="Filter by ontology ID (e.g., 'go', 'doid', 'efo'), comma-separated",
)
parser.add_argument(
"--rows", type=int, default=10, help="Number of suggestions to return"
)
parser.add_argument("--start", type=int, default=0, help="Pagination offset")
parser.add_argument(
"--output", type=str, required=True, help="Output file path"
)
return parser.parse_args()
if __name__ == "__main__":
main_args = parse_args()
suggest_ols(main_args)
Related skills
FAQ
What API base URL does EMBL-EBI OLS use?
EMBL-EBI OLS uses the OLS4 REST API at https://www.ebi.ac.uk/ols4/api, exposing /search, /suggest, /select, /ontologies, and term endpoints for biomedical ontology access.
How does EMBL-EBI OLS help coding agents?
EMBL-EBI OLS gives coding agents reliable patterns to resolve life-science ontology terms via OLS4 search, suggest, and term-by-IRI endpoints instead of hardcoding stale vocabulary lists.
Is Embl Ebi Ols safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.