API

Auto-generated reference from the package source.

Sync client

class opentargets.OpenTargetsClient(base_url='https://api.platform.opentargets.org/api/v4/graphql', timeout=30.0, cache=True, cache_ttl=300.0, retry_config=None)[source]

Bases: object

Synchronous client for the Open Targets Platform GraphQL API.

Parameters:
  • base_url (str) – GraphQL endpoint. Override for self-hosted instances.

  • timeout (float) – HTTP timeout in seconds.

  • cache (bool | CacheBackend) – Set to False to disable in-memory caching.

  • cache_ttl (float) – Cache entry lifetime in seconds (default 5 min).

  • retry_config (Optional[RetryConfig])

Example:

from opentargets import OpenTargetsClient

client = OpenTargetsClient()
target = client.get_target("EGFR")
print(target.approved_name)
get_target(target_id)[source]

Return core annotations for a single gene target.

Retrieves approved name, biotype, and functional descriptions for the given target. Accepts either an Ensembl stable ID or an HGNC gene symbol; symbols are resolved automatically via a search call.

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

Target

Returns:

A Target instance.

Raises:

NotFoundError – If no target matches target_id.

Example:

client = OpenTargetsClient()
target = client.get_target("EGFR")
print(target.approved_name)  # epidermal growth factor receptor
print(target.id)             # ENSG00000146648
get_targets(target_ids)[source]

Return core annotations for multiple gene targets in one API call.

More efficient than calling get_target() in a loop when you already have a list of identifiers.

Parameters:

target_ids (list[str]) – List of Ensembl gene IDs like 'ENSG00000146648' or HGNC symbols like 'EGFR'. Mixed formats are accepted.

Return type:

list[Target]

Returns:

List of Target instances in the same order as target_ids (targets not found are silently omitted).

Example:

client = OpenTargetsClient()
targets = client.get_targets(["EGFR", "BRAF", "TP53"])
for t in targets:
    print(t.approved_symbol, t.biotype)
get_target_associations(target_id, limit=25, as_dataframe=False)[source]

Return diseases associated with a target, ranked by association score.

Each association includes an overall score (0–1) and per-datasource scores (genetics, literature, clinical trials, etc.). Results are ordered by descending overall score.

Parameters:
  • target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

  • limit (int) – Maximum number of associations to return (default 25).

  • as_dataframe (bool) – When True, return a flat pandas.DataFrame instead of a list of model objects. Requires pandas.

Return type:

list[Association] | pd.DataFrame

Returns:

List of Association objects, or a pandas.DataFrame when as_dataframe is True.

Example:

client = OpenTargetsClient()
assocs = client.get_target_associations("EGFR", limit=5)
for a in assocs:
    print(a.disease_name, round(a.score, 3))
get_target_drugs(target_id)[source]

Return approved drugs and clinical candidates that interact with a target.

Includes the drug name, type, mechanism of action, trade names, and maximum clinical trial phase reached.

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

list[Drug]

Returns:

List of Drug objects.

Example:

client = OpenTargetsClient()
drugs = client.get_target_drugs("EGFR")
for d in drugs:
    print(d.name, d.maximum_clinical_stage)
get_target_tractability(target_id)[source]

Return tractability assessments indicating how druggable a target is.

Covers small-molecule, antibody, PROTAC, and other modalities, each with a label and value indicating the assessment category (e.g. "Clinical precedence", "Discovery precedence").

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

list[Tractability]

Returns:

List of Tractability objects, one per modality/label combination.

Example:

client = OpenTargetsClient()
tracts = client.get_target_tractability("EGFR")
for t in tracts:
    print(t.modality, t.label, t.value)
get_target_safety(target_id)[source]

Return known safety liabilities for a target.

Safety liabilities describe adverse events associated with target perturbation, the biosample in which they were observed, the directional effect (activation/inhibition), and the source literature.

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

list[SafetyLiability]

Returns:

List of SafetyLiability objects.

Example:

client = OpenTargetsClient()
liabilities = client.get_target_safety("EGFR")
for s in liabilities:
    print(s.event, s.datasource)
get_target_expression(target_id)[source]

Return baseline tissue-level RNA and protein expression for a target.

Data is sourced from GTEx (RNA) and the Human Protein Atlas (protein). Each entry covers one tissue and includes RNA TPM value/z-score and protein reliability/level.

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

list[TissueExpression]

Returns:

List of TissueExpression objects.

Example:

client = OpenTargetsClient()
expressions = client.get_target_expression("EGFR")
for e in expressions:
    print(e.tissue.label, e.rna.value, e.protein.level)
get_target_constraint(target_id)[source]

Return gnomAD genetic constraint metrics for a target.

Constraint metrics quantify intolerance to variation and are useful when assessing whether perturbing a target is likely to be tolerated. Typical entries cover synonymous (syn), missense (mis), and loss-of-function (lof) variant classes with pLI, LOEUF, and Z-score values.

Parameters:

target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

Return type:

list[GeneticConstraint]

Returns:

List of GeneticConstraint objects — typically one entry each for syn, mis, and lof.

Example:

client = OpenTargetsClient()
constraints = client.get_target_constraint("EGFR")
for c in constraints:
    print(c.constraintType, c.pLI, c.loeuf)
get_disease(disease_id)[source]

Return core annotations for a single disease or phenotype.

Retrieves name, description, therapeutic area classification, and cross-database references (OMIM, MeSH, MONDO, etc.).

Parameters:

disease_id (str) – EFO ontology identifier like 'EFO_0000311' (cancer) or 'EFO_0003060' (lung carcinoma). MONDO and OMIM IDs are also accepted where Open Targets indexes them.

Return type:

Disease

Returns:

A Disease instance.

Raises:

NotFoundError – If no disease matches disease_id.

Example:

client = OpenTargetsClient()
disease = client.get_disease("EFO_0000311")
print(disease.name)         # cancer
print(disease.description)
get_disease_targets(disease_id, limit=25, as_dataframe=False)[source]

Return targets associated with a disease, ranked by association score.

The inverse of get_target_associations(). Each association includes an overall score and per-datasource scores. Results are ordered by descending overall score.

Parameters:
  • disease_id (str) – EFO ontology identifier like 'EFO_0000311' (cancer) or 'EFO_0003060' (lung carcinoma).

  • limit (int) – Maximum number of associations to return (default 25).

  • as_dataframe (bool) – When True, return a flat pandas.DataFrame instead of a list of model objects. Requires pandas.

Return type:

list[Association] | pd.DataFrame

Returns:

List of Association objects or a pandas.DataFrame when as_dataframe is True.

Example:

client = OpenTargetsClient()
assocs = client.get_disease_targets("EFO_0000311", limit=5)
for a in assocs:
    print(a.target_symbol, round(a.score, 3))
get_drug(drug_id)[source]

Return core annotations for a single drug or clinical candidate.

Retrieves the drug name, type (small molecule, antibody, etc.), mechanism of action, synonyms, trade names, and the highest clinical trial phase reached.

Parameters:

drug_id (str) – ChEMBL identifier like 'CHEMBL941' (erlotinib) or 'CHEMBL1421' (gefitinib).

Return type:

Drug

Returns:

A Drug instance.

Raises:

NotFoundError – If no drug matches drug_id.

Example:

client = OpenTargetsClient()
drug = client.get_drug("CHEMBL941")
print(drug.name)                    # ERLOTINIB
print(drug.maximum_clinical_stage)  # 4
get_drug_indications(drug_id)[source]

Return approved and clinical-stage disease indications for a drug.

Each indication includes the disease name and the maximum clinical trial phase associated with the drug–disease pair.

Parameters:

drug_id (str) – ChEMBL identifier like 'CHEMBL941' (erlotinib).

Return type:

list[DrugIndication]

Returns:

List of DrugIndication objects.

Example:

client = OpenTargetsClient()
indications = client.get_drug_indications("CHEMBL941")
for ind in indications:
    print(ind.disease_name, ind.max_clinical_stage)
get_drug_chembl_ids(drug_id)[source]

Return all ChEMBL IDs linked to a drug via its cross-references.

The Open Targets Drug type stores external references in crossReferences (source + ids). This method returns only those ids belonging to sources that look like a ChEMBL reference — i.e. any cross-reference whose ids list contains strings starting with CHEMBL, plus the primary drug ID itself. Useful when a compound has multiple ChEMBL entries (e.g. salt vs. free base).

Parameters:

drug_id (str) – ChEMBL identifier like 'CHEMBL941' (erlotinib) or 'CHEMBL521'.

Return type:

list[str]

Returns:

Deduplicated list of ChEMBL identifier strings, primary ID first.

Raises:

NotFoundError – If no drug matches drug_id.

Example:

client = OpenTargetsClient()
ids = client.get_drug_chembl_ids("CHEMBL941")
print(ids)  # ['CHEMBL941', ...]
search(query_string, entity_type=None, limit=10)[source]

Search the Open Targets Platform for targets, diseases, or drugs.

Performs a ranked free-text search. Each result carries the entity type, stable ID, display name, and a relevance score. Useful for resolving human-readable names to stable identifiers.

Parameters:
  • query_string (str) – Free-text search string, e.g. 'EGFR', 'lung cancer', or 'erlotinib'.

  • entity_type (str | None) – Restrict results to 'target', 'disease', or 'drug'. Pass None (default) to search all types.

  • limit (int) – Maximum number of results to return (default 10).

Return type:

list[SearchResult]

Returns:

List of SearchResult objects ordered by relevance.

Example:

client = OpenTargetsClient()
results = client.search("lung cancer", entity_type="disease", limit=3)
for r in results:
    print(r.id, r.name, r.entity)
get_associations(target_id, disease_id)[source]

Return the association score between one specific target and disease.

Looks up the direct target–disease pair and returns its overall association score together with per-datasource scores. Returns None if Open Targets does not record an association.

Parameters:
  • target_id (str) – Ensembl gene ID like 'ENSG00000146648' or HGNC symbol like 'EGFR'.

  • disease_id (str) – EFO ontology identifier like 'EFO_0000311' (cancer) or 'EFO_0003060' (lung carcinoma).

Return type:

Association | None

Returns:

An Association with overall and per-datasource scores, or None if no association exists.

Example:

client = OpenTargetsClient()
assoc = client.get_associations("EGFR", "EFO_0000311")
if assoc:
    print(assoc.score)  # e.g. 0.853
close()[source]

Close the underlying HTTP connection pool.

Return type:

None

Async client

class opentargets.AsyncOpenTargetsClient(base_url='https://api.platform.opentargets.org/api/v4/graphql', timeout=30.0, cache=True, cache_ttl=300.0)[source]

Bases: object

Asynchronous client for the Open Targets Platform GraphQL API.

Mirrors OpenTargetsClient with async/await semantics. Use with asyncio.gather to query hundreds of targets concurrently.

Parameters:
  • base_url (str) – GraphQL endpoint. Override for self-hosted instances.

  • timeout (float) – HTTP timeout in seconds.

  • cache (bool) – Set to False to disable in-memory caching.

  • cache_ttl (float) – Cache entry lifetime in seconds (default 5 min).

Example:

import asyncio
from opentargets import AsyncOpenTargetsClient

async def main():
    async with AsyncOpenTargetsClient() as client:
        target = await client.get_target("EGFR")
        print(target.approved_name)

asyncio.run(main())
async get_target(target_id)[source]

Fetch a single target by Ensembl ID or gene symbol.

Parameters:

target_id (str) – Ensembl gene ID (ENSG…) or HGNC symbol (EGFR).

Return type:

Target

Returns:

A Target instance.

Raises:

NotFoundError – If no target matches target_id.

async get_targets(target_ids)[source]

Fetch multiple targets in a single API request.

Parameters:

target_ids (list[str]) – List of Ensembl IDs or gene symbols.

Return type:

list[Target]

Returns:

List of Target instances (same order as input).

async get_target_associations(target_id, limit=25, as_dataframe=False)[source]

Fetch diseases associated with a target.

Parameters:
  • target_id (str) – Ensembl ID or gene symbol.

  • limit (int) – Maximum number of associations to return.

  • as_dataframe (bool) – Return a pandas.DataFrame instead of a list.

Return type:

list[Association] | pd.DataFrame

Returns:

List of Association objects, or a DataFrame when as_dataframe is True.

async get_target_drugs(target_id)[source]

Fetch drugs known to interact with a target.

Parameters:

target_id (str) – Ensembl ID or gene symbol.

Return type:

list[Drug]

Returns:

List of Drug objects.

async get_disease(disease_id)[source]

Fetch a single disease by EFO identifier.

Parameters:

disease_id (str) – EFO identifier (e.g. EFO_0003060).

Return type:

Disease

Returns:

A Disease instance.

Raises:

NotFoundError – If no disease matches disease_id.

async get_disease_targets(disease_id, limit=25, as_dataframe=False)[source]

Fetch targets associated with a disease.

Parameters:
  • disease_id (str) – EFO identifier.

  • limit (int) – Maximum number of associations to return.

  • as_dataframe (bool) – Return a pandas.DataFrame instead of a list.

Return type:

list[Association] | pd.DataFrame

Returns:

List of Association objects or a DataFrame.

async get_drug(drug_id)[source]

Fetch a single drug by ChEMBL identifier.

Parameters:

drug_id (str) – ChEMBL ID (e.g. CHEMBL939).

Return type:

Drug

Returns:

A Drug instance.

Raises:

NotFoundError – If no drug matches drug_id.

async get_drug_indications(drug_id)[source]

Fetch disease indications for a drug.

Parameters:

drug_id (str) – ChEMBL ID.

Return type:

list[DrugIndication]

Returns:

List of DrugIndication objects.

async search(query_string, entity_type=None, limit=10)[source]

Search the platform for targets, diseases, or drugs.

Parameters:
  • query_string (str) – Free-text search string.

  • entity_type (Optional[str]) – Filter by "target", "disease", or "drug". Pass None to search all entity types.

  • limit (int) – Maximum number of results.

Return type:

list[SearchResult]

Returns:

List of SearchResult objects.

async get_associations(target_id, disease_id)[source]

Fetch the association between a specific target and disease.

Parameters:
  • target_id (str) – Ensembl ID or gene symbol.

  • disease_id (str) – EFO identifier.

Return type:

Optional[Association]

Returns:

An Association or None if no association exists.

async close()[source]

Close the underlying HTTP connection pool.

Return type:

None

Configuration

class opentargets.RetryConfig(max_retries=3, base_delay=1.0, max_delay=60.0, retryable_statuses=<factory>, respect_retry_after=True)[source]

Bases: object

Immutable configuration for retry behavior.

Parameters:
  • max_retries (int) – Maximum number of retry attempts (0 = no retries).

  • base_delay (float) – Initial backoff delay in seconds.

  • max_delay (float) – Maximum backoff delay in seconds.

  • retryable_statuses (frozenset) – Set of HTTP status codes that trigger a retry.

  • respect_retry_after (bool) – When True (default) honour the Retry-After response header value for 429 responses. When False use exponential back-off instead.

max_retries: int = 3
base_delay: float = 1.0
max_delay: float = 60.0
retryable_statuses: frozenset
respect_retry_after: bool = True
opentargets.DEFAULT_RETRY_CONFIG = RetryConfig(max_retries=3, base_delay=1.0, max_delay=60.0, retryable_statuses=frozenset({500, 502, 503, 504, 429}), respect_retry_after=True)

Immutable configuration for retry behavior.

Parameters:
  • max_retries – Maximum number of retry attempts (0 = no retries).

  • base_delay – Initial backoff delay in seconds.

  • max_delay – Maximum backoff delay in seconds.

  • retryable_statuses – Set of HTTP status codes that trigger a retry.

  • respect_retry_after – When True (default) honour the Retry-After response header value for 429 responses. When False use exponential back-off instead.

class opentargets.DiskCache(path, ttl=86400.0, maxsize=None)[source]

Bases: object

Disk-backed cache using SQLite, safe for concurrent use within a process.

Values are serialised with pickle. The database is created lazily on first use, and the parent directory is auto-created if it does not exist.

Parameters:
  • path (str | Path) – File system path for the SQLite database file.

  • ttl (float) – Seconds before a cached entry is considered stale. Defaults to 24 hours.

  • maxsize (Optional[int]) – When set, the cache is pruned to at most maxsize entries (oldest first) whenever a new entry is inserted.

get(key)[source]

Return the cached value for key, or None if missing / expired.

Return type:

Any

Parameters:

key (str)

set(key, value)[source]

Store value under key.

Return type:

None

Parameters:
clear()[source]

Remove all entries from the cache.

Return type:

None

close()[source]

Close the underlying SQLite connection.

Return type:

None

class opentargets.CacheBackend(*args, **kwargs)[source]

Bases: Protocol

Minimal protocol that every cache backend must satisfy.

get(key)[source]

Return the cached value for key, or None if missing / expired.

Return type:

Any

Parameters:

key (str)

set(key, value)[source]

Store value under key.

Return type:

None

Parameters:
clear()[source]

Remove all entries.

Return type:

None

Models

Pydantic v2 response models for the Open Targets Platform API.

class opentargets.models.Target(**data)[source]

Bases: BaseModel

A drug target (gene/protein) from the Open Targets Platform.

Parameters:
  • id (str)

  • approvedSymbol (str)

  • approvedName (str)

  • biotype (str)

  • description (str)

  • functionDescriptions (list[str])

id

Ensembl gene ID (e.g. “ENSG00000146648”).

approved_symbol

HGNC-approved gene symbol (e.g. “EGFR”).

approved_name

Full gene name.

biotype

Ensembl biotype (e.g. “protein_coding”).

description

Short description from Ensembl.

function_descriptions

List of functional annotation strings.

id: str
approved_symbol: str
approved_name: str
biotype: str
description: str
function_descriptions: list[str]
model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class opentargets.models.Disease(**data)[source]

Bases: BaseModel

A disease or phenotype from the Open Targets Platform.

Parameters:
id

EFO identifier (e.g. “EFO_0003060”).

name

Disease name.

description

Plain-text description.

therapeutic_areas

List of broad therapeutic area names.

db_x_refs

Cross-references to external databases.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
description: str
therapeutic_areas: list[str]
db_x_refs: list[str]
class opentargets.models.Drug(**data)[source]

Bases: BaseModel

A drug or compound from the Open Targets Platform.

Parameters:
id

ChEMBL identifier (e.g. “CHEMBL939”).

name

Drug name.

drug_type

Molecule type (e.g. “Small molecule”).

mechanism_of_action

Pharmacological mechanism string.

synonyms

Alternative drug names.

trade_names

Commercial brand names.

max_clinical_trial_phase

Highest phase reached in clinical trials (0-4).

chembl_ids

ChEMBL IDs extracted from crossReferences.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
drug_type: str
mechanism_of_action: str
synonyms: list[str]
trade_names: list[str]
max_clinical_trial_phase: str | None
chembl_ids: list[str]
class opentargets.models.DatasourceScore(**data)[source]

Bases: BaseModel

A per-datasource association score.

Parameters:
id

Datasource identifier (e.g. “ot_genetics_portal”).

score

Numeric score between 0 and 1.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
score: float
class opentargets.models.Association(**data)[source]

Bases: BaseModel

A target–disease association with evidence scores.

Parameters:
target_id

Ensembl gene ID of the associated target.

target_symbol

Gene symbol of the associated target.

disease_id

EFO identifier of the associated disease.

disease_name

Name of the associated disease.

score

Overall association score (0–1).

datasource_scores

Per-datasource evidence scores.

evidence_count

Total number of supporting evidence items.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

target_id: str
target_symbol: str
disease_id: str
disease_name: str
score: float
datasource_scores: list[DatasourceScore]
evidence_count: int
class opentargets.models.SearchResult(**data)[source]

Bases: BaseModel

A single result from the platform-wide search endpoint.

Parameters:
id

Entity identifier.

name

Display name.

entity_type

One of “target”, “disease”, “drug”.

description

Short description.

score

Search relevance score.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
entity_type: str
description: str
score: float
class opentargets.models.DrugIndication(**data)[source]

Bases: BaseModel

A disease indication for a given drug.

Parameters:
  • disease_id (str)

  • disease_name (str)

  • maxClinicalStage (str | None)

disease_id

EFO identifier.

disease_name

Disease name.

max_phase_for_indication

Highest clinical trial phase for this indication.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

disease_id: str
disease_name: str
max_phase_for_indication: str | None
class opentargets.models.Tractability(**data)[source]

Bases: BaseModel

A tractability assessment for a target.

Parameters:
modality

Modality type (e.g. “SM”, “AB”, “OC”).

label

Human-readable tractability label.

value

Whether the target meets this tractability criterion.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

modality: str
label: str
value: bool
class opentargets.models.SafetyBiosample(**data)[source]

Bases: BaseModel

Biosample information from a safety liability entry.

Parameters:
  • tissueLabel (str | None)

  • tissueId (str | None)

  • cellLabel (str | None)

  • cellId (str | None)

tissue_label

Tissue label from the biosample.

tissue_id

Tissue ontology ID.

cell_label

Cell type label.

cell_id

Cell ontology ID.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tissue_label: str | None
tissue_id: str | None
cell_label: str | None
cell_id: str | None
class opentargets.models.SafetyEffect(**data)[source]

Bases: BaseModel

An effect associated with a safety liability entry.

Parameters:
  • direction (str | None)

  • dosing (str | None)

direction

Direction of effect (e.g. “Activation/Increase/Upregulation”).

dosing

Dosing information if available.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

direction: str | None
dosing: str | None
class opentargets.models.SafetyLiability(**data)[source]

Bases: BaseModel

A safety liability entry for a target.

Parameters:
event

Safety event description.

datasource

Data source name.

biosamples

List of relevant biosamples.

effects

List of associated effects.

literature

PubMed/literature reference.

url

URL for further information.

event_id

Optional event identifier.

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

event: str | None
datasource: str
biosamples: list[SafetyBiosample]
effects: list[SafetyEffect]
literature: str | None
url: str | None
event_id: str | None
class opentargets.models.TissueInfo(**data)[source]

Bases: BaseModel

Tissue identity from expression data.

Parameters:
id

Tissue ontology ID.

label

Human-readable tissue label.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
label: str
class opentargets.models.RnaExpression(**data)[source]

Bases: BaseModel

RNA expression values for a tissue.

Parameters:
value

Expression value (e.g. TPM or RPKM).

level

Discretised expression level (0–4).

zscore

Z-score relative to other tissues.

unit

Unit of expression value.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

value: float
level: int
zscore: int
unit: str
class opentargets.models.ProteinExpression(**data)[source]

Bases: BaseModel

Protein expression values for a tissue.

Parameters:
level

Discretised protein expression level.

reliability

Whether the antibody used is reliable.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

level: int
reliability: bool
class opentargets.models.TissueExpression(**data)[source]

Bases: BaseModel

Baseline tissue expression for a target.

Parameters:
tissue

Tissue identity.

rna

RNA expression data.

protein

Protein expression data.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tissue: TissueInfo
rna: RnaExpression
protein: ProteinExpression
class opentargets.models.GeneticConstraint(**data)[source]

Bases: BaseModel

gnomAD genetic constraint metric for a target.

Parameters:
constraint_type

Type of constraint (syn, mis, lof).

obs

Observed variant count.

exp

Expected variant count.

oe

Observed/expected ratio.

oe_lower

Lower 95 % CI for oe ratio.

oe_upper

Upper 95 % CI for oe ratio.

score

Constraint score (pLI-equivalent for lof).

model_config: ClassVar[ConfigDict] = {'frozen': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

constraint_type: str
obs: int | None
exp: float | None
oe: float | None
oe_lower: float | None
oe_upper: float | None
score: float | None

Exceptions

Custom exceptions for the opentargets-py SDK.

exception opentargets.exceptions.OpenTargetsError[source]

Bases: Exception

Base exception for all opentargets-py errors.

exception opentargets.exceptions.APIError(status_code, message)[source]

Bases: OpenTargetsError

Raised when the API returns an HTTP error response.

Parameters:
  • status_code (int) – HTTP status code returned by the API.

  • message (str) – Human-readable error message.

Return type:

None

exception opentargets.exceptions.QueryError(errors)[source]

Bases: OpenTargetsError

Raised when the GraphQL API returns errors in the response body.

Parameters:

errors (list[dict[str, object]]) – List of GraphQL error objects from the response.

Return type:

None

exception opentargets.exceptions.NotFoundError(entity_type, entity_id)[source]

Bases: OpenTargetsError

Raised when a requested entity does not exist in the platform.

Parameters:
  • entity_type (str) – Type of entity that was not found (e.g. “target”, “disease”).

  • entity_id (str) – Identifier that was searched for.

Return type:

None

exception opentargets.exceptions.RateLimitError(retry_after=None)[source]

Bases: APIError

Raised when the API responds with 429 Too Many Requests.

Parameters:

retry_after (float | None) – Seconds to wait before retrying, if provided by the API.

Return type:

None