Skip to content

ChEBI

Online: the ChEBI 2.0 REST service. The offline client is ChebiSDF. See the ChEBI tutorial.

provesid.chebi

ChEBI (Chemical Entities of Biological Interest) API interface.

This module provides a Python interface to the ChEBI 2.0 REST API for retrieving chemical compound information from the ChEBI database. Offline access through ChEBI's SDF release is ChebiSDF, in provesid.chebi_sdf.

API documentation: https://www.ebi.ac.uk/chebi/backend/api/docs/

Author: USEtox team Date: August 2025

Attributes

CHEBI_MIN_INTERVAL module-attribute

Seconds between two requests to ChEBI from this process. EBI publishes no per-IP figure for the ChEBI 2.0 API, so this is politeness rather than a quoted limit: ten requests a second is well inside what a walk over an ontology subtree needs.

Classes

ChEBIError

Bases: ServiceError

Custom exception for ChEBI API errors.

Also the base for the two more specific failures below, so a caller that catches this one keeps catching everything --- which is what every method in this module does internally before returning None.

Examples:

>>> issubclass(ChEBINotFoundError, ChEBIError)
True
Source code in src/provesid/chebi.py
30
31
32
33
34
35
36
37
38
39
40
41
42
class ChEBIError(ServiceError):
    """
    Custom exception for ChEBI API errors.

    Also the base for the two more specific failures below, so a caller that
    catches this one keeps catching everything --- which is what every method
    in this module does internally before returning None.

    Examples:
        >>> issubclass(ChEBINotFoundError, ChEBIError)
        True
    """
    pass

ChEBINotFoundError

Bases: ChEBIError, NotFoundError

ChEBI answered, and its answer was that there is no such record.

A statement about the data rather than the request, so it is never retried.

Examples:

>>> issubclass(ChEBINotFoundError, NotFoundError)
True
Source code in src/provesid/chebi.py
45
46
47
48
49
50
51
52
53
54
55
class ChEBINotFoundError(ChEBIError, NotFoundError):
    """
    ChEBI answered, and its answer was that there is no such record.

    A statement about the data rather than the request, so it is never retried.

    Examples:
        >>> issubclass(ChEBINotFoundError, NotFoundError)
        True
    """
    pass

ChEBITimeoutError

Bases: ChEBIError, ServiceTimeoutError

Every attempt timed out or the connection could not be made.

Examples:

>>> issubclass(ChEBITimeoutError, ServiceTimeoutError)
True
Source code in src/provesid/chebi.py
58
59
60
61
62
63
64
65
66
class ChEBITimeoutError(ChEBIError, ServiceTimeoutError):
    """
    Every attempt timed out or the connection could not be made.

    Examples:
        >>> issubclass(ChEBITimeoutError, ServiceTimeoutError)
        True
    """
    pass

ChEBI

Interface for the ChEBI 2.0 (Chemical Entities of Biological Interest) REST API.

The ChEBI database is a freely available dictionary of molecular entities focused on 'small' chemical compounds. This class provides methods to search for and retrieve compound information from the ChEBI 2.0 API.

Attributes:

Name Type Description
base_url str

Base URL for ChEBI 2.0 API

timeout int

Request timeout in seconds

session Session

HTTP session for connection pooling

Every method needs the network. Lookups that fail return None (or an empty collection) after logging a warning, rather than raising; the offline alternative for records, names and structures is ChebiSDF.

Examples:

>>> chebi = ChEBI()
>>> compound = chebi.get_compound(15377)
>>> print(compound['name'])
water
Source code in src/provesid/chebi.py
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
class ChEBI:
    """
    Interface for the ChEBI 2.0 (Chemical Entities of Biological Interest) REST API.

    The ChEBI database is a freely available dictionary of molecular entities
    focused on 'small' chemical compounds. This class provides methods to search
    for and retrieve compound information from the ChEBI 2.0 API.

    Attributes:
        base_url (str): Base URL for ChEBI 2.0 API
        timeout (int): Request timeout in seconds
        session (requests.Session): HTTP session for connection pooling

    Every method needs the network. Lookups that fail return None (or an
    empty collection) after logging a warning, rather than raising; the
    offline alternative for records, names and structures is
    [`ChebiSDF`][provesid.chebi_sdf.ChebiSDF].

    Examples:
        >>> chebi = ChEBI()
        >>> compound = chebi.get_compound(15377)  # doctest: +SKIP
        >>> print(compound['name'])               # doctest: +SKIP
        water
    """

    # Valid ontology relation types for the ChEBI 2.0 API
    VALID_RELATIONS = [
        "has_functional_parent", "has_parent_hydride", "has_part", "has_role",
        "is_a", "is_conjugate_acid_of", "is_conjugate_base_of",
        "is_enantiomer_of", "is_part_of", "is_substituent_group_from",
        "is_tautomer_of",
    ]

    # Valid structure search types
    VALID_SEARCH_TYPES = ["connectivity", "similarity", "substructure"]

    def __init__(self, timeout: int = 30):
        """
        Initialize ChEBI 2.0 API client.

        Args:
            timeout (int): Request timeout in seconds (default: 30)

        Examples:
            >>> ChEBI(timeout=60)
            ChEBI(base_url='https://www.ebi.ac.uk/chebi/backend/api/public', timeout=60)
        """
        self.base_url = "https://www.ebi.ac.uk/chebi/backend/api/public"
        self.timeout = timeout
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'PROVESID-ChEBI-Client/2.0',
            'Accept': 'application/json',
        })

        # Setup logging
        self.logger = logging.getLogger(__name__)

        # One shared transport, making its calls through the session above so
        # that the pooled connection and the persistent headers survive the
        # move. ChEBI uses its status codes honestly --- unlike PubChem and
        # CACTUS, it has no fault code in the body to read --- so the default
        # classifier is the right one.
        #
        # Two retries with a half-second base, rather than the transport's
        # three and one: an ontology walk makes many small requests to a fast
        # service, where a long back-off curve costs more than the request it
        # is protecting.
        self._http = HTTPClient(
            session=self.session,
            min_interval=CHEBI_MIN_INTERVAL,
            timeout=timeout,
            max_retries=2,
            backoff=0.5,
            error_cls=ChEBIError,
            not_found_cls=ChEBINotFoundError,
            timeout_cls=ChEBITimeoutError,
            pace_host=self.base_url,
            logger=self.logger,
        )

    @staticmethod
    def _format_chebi_id(chebi_id: Union[int, str]) -> str:
        """
        Format a ChEBI ID to the canonical ``CHEBI:<number>`` form.

        The ChEBI 2.0 API accepts IDs with or without the prefix, but this
        helper ensures consistency.

        Args:
            chebi_id: ChEBI ID (int, bare number string, or ``CHEBI:…`` string)

        Returns:
            (str): ID in ``CHEBI:<number>`` form
        """
        chebi_id_str = str(chebi_id).strip()
        if not chebi_id_str.upper().startswith("CHEBI:"):
            chebi_id_str = f"CHEBI:{chebi_id_str}"
        return chebi_id_str

    # ------------------------------------------------------------------
    # Low-level HTTP helpers
    # ------------------------------------------------------------------

    def _json_or_text(self, response: requests.Response) -> Any:
        """
        Return a response body as JSON when ChEBI says it is JSON, else as text.

        ChEBI serves molfiles and SVG from the same API as its records, and
        labels them honestly in ``Content-Type``, so the header is what decides.

        Args:
            response: The response to read.

        Returns:
            The decoded JSON, or the body as text.

        Raises:
            ChEBIError: The body was labelled JSON and is not.
        """
        if response.headers.get("Content-Type", "").startswith("application/json"):
            return self._http.decode_json(response)
        return response.text

    def _get(self, endpoint: str, params: Optional[Dict] = None) -> Any:
        """
        Perform a GET request and return the parsed JSON body.

        Pacing, retries and back-off belong to the shared transport; what stays
        here is ChEBI's own contract --- where its endpoints live and how it
        labels what it returns.

        Args:
            endpoint (str): Path relative to *base_url* (e.g. ``compound/15377/``).
            params (dict, optional): Query-string parameters.

        Returns:
            Parsed JSON response (dict / list / str).

        Raises:
            ChEBINotFoundError: ChEBI reported no such record (404).
            ChEBITimeoutError: Every attempt timed out or could not connect.
            ChEBIError: Any other HTTP or JSON failure, including a transient
                one that outlived the retries.
        """
        url = f"{self.base_url}/{endpoint}"
        return self._json_or_text(self._http.get(url, params=params))

    def _get_raw(self, endpoint: str, params: Optional[Dict] = None) -> requests.Response:
        """
        Perform a GET request and return the raw `requests.Response`.

        Useful for endpoints that return non-JSON content (SVG, molfile, images).

        Args:
            endpoint (str): Path relative to *base_url*.
            params (dict, optional): Query-string parameters.

        Returns:
            The response, already classified as a success.

        Raises:
            ChEBINotFoundError: ChEBI reported no such record (404).
            ChEBITimeoutError: Every attempt timed out or could not connect.
            ChEBIError: Any other HTTP failure.
        """
        url = f"{self.base_url}/{endpoint}"
        return self._http.get(url, params=params)

    def _post_json(self, endpoint: str, json_body: Any = None,
                   params: Optional[Dict] = None) -> Any:
        """
        Perform a POST request with a JSON body and return parsed JSON.

        Args:
            endpoint (str): Path relative to *base_url*.
            json_body: Object to serialise as JSON request body.
            params (dict, optional): Query-string parameters.

        Returns:
            Parsed JSON response.

        Raises:
            ChEBINotFoundError: ChEBI reported no such record (404).
            ChEBITimeoutError: Every attempt timed out or could not connect.
            ChEBIError: Any other HTTP or JSON failure.
        """
        url = f"{self.base_url}/{endpoint}"
        return self._json_or_text(
            self._http.post(url, json=json_body, params=params)
        )

    def _post_text(self, endpoint: str, text_body: str,
                   params: Optional[Dict] = None) -> str:
        """
        Perform a POST request with a ``text/plain`` body and return the
        response text.  Used by the structure-calculation endpoints.

        Args:
            endpoint (str): Path relative to *base_url*.
            text_body (str): The body to send, a SMILES string or a formula.
            params (dict, optional): Query-string parameters.

        Returns:
            The response body as text.

        Raises:
            ChEBINotFoundError: ChEBI reported no such record (404).
            ChEBITimeoutError: Every attempt timed out or could not connect.
            ChEBIError: Any other HTTP failure.
        """
        return self._post_raw(endpoint, text_body, params=params).text

    def _post_raw(self, endpoint: str, text_body: str,
                  params: Optional[Dict] = None) -> requests.Response:
        """
        POST a ``text/plain`` body and return the raw response.

        The structure-calculation endpoints want the text; ``depict_structure``
        wants the bytes of a PNG. Two headers are set per request, and
        ``requests`` merges them over the session's own: ``Content-Type``, and
        ``Accept``. These endpoints answer ``text/plain`` or ``image/png``, and
        refuse the session's ``Accept: application/json`` with HTTP 406, which
        until 2026-09-22 made every one of them return None.

        Args:
            endpoint (str): Path relative to *base_url*.
            text_body (str): The body to send.
            params (dict, optional): Query-string parameters.

        Returns:
            The response, already classified as a success.

        Raises:
            ChEBINotFoundError: ChEBI reported no such record (404).
            ChEBITimeoutError: Every attempt timed out or could not connect.
            ChEBIError: Any other HTTP failure.
        """
        url = f"{self.base_url}/{endpoint}"
        return self._http.post(
            url, data=text_body, params=params,
            headers={"Content-Type": "text/plain;charset=UTF-8", "Accept": "*/*"},
        )

    # ------------------------------------------------------------------
    # Compound retrieval
    # ------------------------------------------------------------------

    def get_compound(self, chebi_id: Union[int, str], *,
                     only_ontology_parents: bool = False,
                     only_ontology_children: bool = False) -> Optional[Dict[str, Any]]:
        """
        Retrieve information about a single compound.

        Endpoint: ``GET /compound/{chebi_id}/``

        Args:
            chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).
            only_ontology_parents: If *True*, return only ontology parents.
            only_ontology_children: If *True*, return only ontology children.

        Returns:
            dict with compound data, or *None* if not found.

        Examples:
            >>> chebi = ChEBI()
            >>> water = chebi.get_compound(15377)              # doctest: +SKIP
            >>> water['name'], water['chebi_accession']        # doctest: +SKIP
            ('water', 'CHEBI:15377')
        """
        chebi_id_str = self._format_chebi_id(chebi_id)
        params: Dict[str, Any] = {}
        if only_ontology_parents:
            params["only_ontology_parents"] = "true"
        if only_ontology_children:
            params["only_ontology_children"] = "true"

        try:
            return self._get(f"compound/{chebi_id_str}/", params=params or None)
        except ChEBIError as e:
            self.logger.warning(f"Failed to get compound {chebi_id_str}: {e}")
            return None

    def get_compounds(self, chebi_ids: List[Union[int, str]]) -> Optional[Any]:
        """
        Retrieve information about one or more compounds in a single call.

        Endpoint: ``POST /compounds/``

        Args:
            chebi_ids: List of ChEBI IDs.

        Returns:
            API response, or *None* on error: a dict keyed by ``CHEBI:<id>``,
            one entry per ID asked for. Each holds ``exists``,
            ``primary_chebi_id`` (the ID a secondary one maps to),
            ``id_type``, ``standardized_chebi_id`` and ``data``, which is the
            [`get_compound`][provesid.chebi.ChEBI.get_compound] record, or
            None when the ID does not exist.

        Examples:
            >>> chebi = ChEBI()
            >>> results = chebi.get_compounds(["CHEBI:15377", "CHEBI:15365"])  # doctest: +SKIP
            >>> {key: entry["data"]["name"] for key, entry in results.items()}  # doctest: +SKIP
            {'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
            >>> chebi.get_compounds([999999999])["CHEBI:999999999"]["exists"]  # doctest: +SKIP
            False
        """
        ids_formatted = [self._format_chebi_id(cid) for cid in chebi_ids]
        try:
            return self._post_json("compounds/", json_body={"chebi_ids": ids_formatted})
        except ChEBIError as e:
            self.logger.warning(f"Failed to get compounds: {e}")
            return None

    # ------------------------------------------------------------------
    # Search
    # ------------------------------------------------------------------

    def search(self, term: str, *, page: int = 1, size: int = 15) -> Optional[Any]:
        """
        General text search (Elasticsearch-backed).

        Endpoint: ``GET /es_search/``

        You can search by ChEBI name, brand name, IUPAC name, synonym,
        InChIKey, formula, SMILES, InChI, CAS number, database cross-reference
        IDs, PubMed IDs, and more.

        Args:
            term: Search term (name, SMILES, InChIKey, CAS, formula, …).
            page: Page number for pagination (default 1).
            size: Page size (default 15).

        Returns:
            Search results dict, or *None* on error: ``results`` (the hits,
            best first, each with its record under ``_source``), ``total`` and
            ``number_pages``.

        Examples:
            >>> chebi = ChEBI()
            >>> results = chebi.search("paracetamol")               # doctest: +SKIP
            >>> results["results"][0]["_source"]["chebi_accession"]  # doctest: +SKIP
            'CHEBI:46195'
        """
        params: Dict[str, Any] = {"term": term, "page": page, "size": size}
        try:
            return self._get("es_search/", params=params)
        except ChEBIError as e:
            self.logger.warning(f"Search failed for '{term}': {e}")
            return None

    def search_by_name(self, search_text: str, *, page: int = 1,
                       size: int = 15) -> List[Dict[str, Any]]:
        """
        Search ChEBI by compound name (convenience wrapper around
        [`search`][provesid.chebi.ChEBI.search]).

        Args:
            search_text: Text to search for.
            page: Page number for pagination (default 1).
            size: Page size (default 15).

        Returns:
            list of matching entity dicts (may be empty): the ``results`` of
            [`search`][provesid.chebi.ChEBI.search], each carrying ``_score``
            and the record under ``_source``.

        Examples:
            >>> hits = ChEBI().search_by_name("paracetamol", size=2)  # doctest: +SKIP
            >>> [(hit["_source"]["chebi_accession"], hit["_source"]["name"]) for hit in hits]  # doctest: +SKIP
            [('CHEBI:46195', 'paracetamol'), ('CHEBI:74529', 'antidote to paracetamol poisoning')]
        """
        result = self.search(search_text, page=page, size=size)
        if result is None:
            return []
        # The es_search endpoint typically returns a dict with a results list
        if isinstance(result, dict):
            return result.get("results", result.get("items", [result]))
        if isinstance(result, list):
            return result
        return []

    # ------------------------------------------------------------------
    # Advanced search
    # ------------------------------------------------------------------

    def advanced_search(
        self,
        specification: Dict[str, Any],
        *,
        three_star_only: bool = True,
        has_structure: Optional[bool] = None,
        page: int = 1,
        size: int = 15,
        download: bool = False,
    ) -> Optional[Any]:
        """
        Perform an advanced compound search using specification objects.

        Endpoint: ``POST /advanced_search/``

        Seven specification types are supported (combine with ``and_specification``,
        ``or_specification``, ``but_not_specification``):

        - ``ontology_specification``
        - ``formula_specification``
        - ``mass_specification``
        - ``monoisotopicmass_specification``
        - ``charge_specification``
        - ``database_name_specification``
        - ``text_search_specification``

        Args:
            specification: Request body following the ``FullSpecification`` schema.
            three_star_only: Only include 3-star compounds (default *True*).
            has_structure: Filter by structure availability (*None* = no filter).
            page: Page number (default 1).
            size: Page size (default 15).
            download: Return results in download format (default *False*).

        Returns:
            API response dict/list, or *None* on error.

        Examples:
            >>> chebi = ChEBI()
            >>> results = chebi.advanced_search({
            ...     "formula_specification": {
            ...         "and_specification": [{"term": "C6H12O7"}]
            ...     }
            ... }, three_star_only=False)                         # doctest: +SKIP
            >>> results["total"]                                  # doctest: +SKIP
            15
        """
        params: Dict[str, Any] = {
            "three_star_only": str(three_star_only).lower(),
            "page": page,
            "size": size,
            "download": str(download).lower(),
        }
        if has_structure is not None:
            params["has_structure"] = str(has_structure).lower()

        try:
            return self._post_json("advanced_search/", json_body=specification,
                                   params=params)
        except ChEBIError as e:
            self.logger.warning(f"Advanced search failed: {e}")
            return None

    def get_sources_list(self) -> Optional[Any]:
        """
        Retrieve the list of available database sources for advanced search.

        Endpoint: ``GET /advanced_search/sources_list``

        Returns:
            Sources information, or *None* on error: a list of
            ``{"prefix", "name"}`` dicts, the names usable in a
            ``database_name_specification``.

        Examples:
            >>> ChEBI().get_sources_list()[:2]                    # doctest: +SKIP
            [{'prefix': 'agr', 'name': 'Agricola'}, {'prefix': 'pesticides', 'name': "Alan Wood's Pesticides"}]
        """
        try:
            return self._get("advanced_search/sources_list")
        except ChEBIError as e:
            self.logger.warning(f"Failed to get sources list: {e}")
            return None

    # ------------------------------------------------------------------
    # Ontology
    # ------------------------------------------------------------------

    def get_ontology_parents(self, chebi_id: Union[int, str]) -> Optional[Any]:
        """
        Get the ontology parents of a compound.

        Endpoint: ``GET /ontology/parents/{chebi_id}/``

        Args:
            chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).

        Returns:
            Ontology parent data, or *None* on error: the compound's ``id`` and
            ``chebi_accession``, with its relations under
            ``ontology_relations["outgoing_relations"]``, each naming the
            ``relation_type`` and the parent (``final_id``, ``final_name``).

        Examples:
            >>> parents = ChEBI().get_ontology_parents(15377)     # doctest: +SKIP
            >>> first = parents["ontology_relations"]["outgoing_relations"][0]  # doctest: +SKIP
            >>> first["relation_type"], first["final_id"]         # doctest: +SKIP
            ('has role', 75772)
        """
        chebi_id_str = self._format_chebi_id(chebi_id)
        try:
            return self._get(f"ontology/parents/{chebi_id_str}/")
        except ChEBIError as e:
            self.logger.warning(f"Failed to get ontology parents for {chebi_id_str}: {e}")
            return None

    def get_ontology_children(self, chebi_id: Union[int, str]) -> Optional[Any]:
        """
        Get the ontology children of a compound.

        Endpoint: ``GET /ontology/children/{chebi_id}/``

        Args:
            chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).

        Returns:
            Ontology children data, or *None* on error: as for
            [`get_ontology_parents`][provesid.chebi.ChEBI.get_ontology_parents],
            with the relations under
            ``ontology_relations["incoming_relations"]`` and the child named by
            ``init_id`` and ``init_name``.

        Examples:
            >>> children = ChEBI().get_ontology_children(15377)   # doctest: +SKIP
            >>> children["ontology_relations"]["incoming_relations"][0]["init_name"]  # doctest: +SKIP
            'methane clathrate'
        """
        chebi_id_str = self._format_chebi_id(chebi_id)
        try:
            return self._get(f"ontology/children/{chebi_id_str}/")
        except ChEBIError as e:
            self.logger.warning(f"Failed to get ontology children for {chebi_id_str}: {e}")
            return None

    def get_all_ontology_children_in_path(
        self,
        relation: str,
        entity: Union[int, str],
        *,
        three_star_only: bool = True,
        has_structure: Optional[bool] = None,
        page: int = 1,
        size: int = 15,
        download: bool = False,
    ) -> Optional[Any]:
        """
        Search all compounds in the ontology matching a relation and entity.

        Endpoint: ``GET /ontology/all_children_in_path/``

        Args:
            relation: Ontology relation type (e.g. ``is_a``, ``has_role``).
            entity: ChEBI ID of the entity to find children of.
            three_star_only: Only include 3-star compounds (default *True*).
            has_structure: Filter by structure availability.
            page: Page number (default 1).
            size: Page size (default 15).
            download: Return results in download format.

        Returns:
            API response, or *None* on error.

        Examples:
            >>> chebi = ChEBI()
            >>> # Get all compounds that are alcohols
            >>> results = chebi.get_all_ontology_children_in_path(
            ...     relation="is_a", entity="CHEBI:30879"
            ... )                                                 # doctest: +SKIP
            >>> results["total"]                                  # doctest: +SKIP
            4029
        """
        entity_str = self._format_chebi_id(entity)
        params: Dict[str, Any] = {
            "relation": relation,
            "entity": entity_str,
            "three_star_only": str(three_star_only).lower(),
            "page": page,
            "size": size,
            "download": str(download).lower(),
        }
        if has_structure is not None:
            params["has_structure"] = str(has_structure).lower()

        try:
            return self._get("ontology/all_children_in_path/", params=params)
        except ChEBIError as e:
            self.logger.warning(f"Failed to get all ontology children: {e}")
            return None

    # ------------------------------------------------------------------
    # Structures
    # ------------------------------------------------------------------

    def get_compound_structure(self, chebi_id: Union[int, str], *,
                               width: int = 300, height: int = 300) -> Optional[str]:
        """
        Get the default SVG structure for a compound.

        Endpoint: ``GET /compound/{id}/structure/``

        Args:
            chebi_id: ChEBI ID (numeric, the primary key of the compound).
            width: Width of the SVG (default 300).
            height: Height of the SVG (default 300).

        Returns:
            Raw SVG string, or *None* on error.

        Examples:
            >>> ChEBI().get_compound_structure(15377)[:21]        # doctest: +SKIP
            "<?xml version='1.0' e"
        """
        # This endpoint expects the numeric compound PK
        numeric_id = str(chebi_id)
        if numeric_id.upper().startswith("CHEBI:"):
            numeric_id = numeric_id.split(":")[-1]

        params: Dict[str, Any] = {"width": width, "height": height}
        try:
            resp = self._get_raw(f"compound/{numeric_id}/structure/", params=params)
            return resp.text
        except ChEBIError as e:
            self.logger.warning(f"Failed to get compound structure for {chebi_id}: {e}")
            return None

    def get_structure(self, structure_id: int, *, width: int = 300,
                      height: int = 300) -> Optional[str]:
        """
        Get raw SVG contents of a structure by its primary key.

        Endpoint: ``GET /structure/{id}/``

        Args:
            structure_id: Primary key of the structure.
            width: Width of the SVG (default 300).
            height: Height of the SVG (default 300).

        Returns:
            Raw SVG string, or *None* on error.

        Examples:
            >>> chebi = ChEBI()
            >>> structure_id = chebi.get_compound(15377)["default_structure"]["id"]  # doctest: +SKIP
            >>> structure_id, chebi.get_structure(structure_id)[:5]  # doctest: +SKIP
            (2018, '<?xml')
        """
        params: Dict[str, Any] = {"width": width, "height": height}
        try:
            resp = self._get_raw(f"structure/{structure_id}/", params=params)
            return resp.text
        except ChEBIError as e:
            self.logger.warning(f"Failed to get structure {structure_id}: {e}")
            return None

    def get_molfile(self, compound_id: int) -> Optional[str]:
        """
        Download the Mol file for a compound's default structure.

        Endpoint: ``GET /molfile/{id}/``

        Args:
            compound_id: Primary key of the compound.

        Returns:
            Mol file contents as string, or *None* on error.

        Examples:
            >>> molfile = ChEBI().get_molfile(15377)              # doctest: +SKIP
            >>> molfile.splitlines()[3][:6]                       # doctest: +SKIP
            '  3  2'
        """
        try:
            resp = self._get_raw(f"molfile/{compound_id}/")
            return resp.text
        except ChEBIError as e:
            self.logger.warning(f"Failed to get molfile for {compound_id}: {e}")
            return None

    # ------------------------------------------------------------------
    # Structure search
    # ------------------------------------------------------------------

    def structure_search(
        self,
        smiles: str,
        search_type: str = "connectivity",
        *,
        similarity: Optional[float] = None,
        three_star_only: bool = True,
        page: int = 1,
        size: int = 15,
        download: bool = False,
    ) -> Optional[Any]:
        """
        Search compounds by chemical structure.

        Endpoint: ``GET /structure_search/``

        Args:
            smiles: Molecule structure in SMILES representation.
            search_type: One of ``connectivity``, ``similarity``, ``substructure``.
            similarity: Similarity threshold for similarity search (0.4–1.0).
            three_star_only: Only include 3-star compounds (default *True*).
            page: Page number (default 1).
            size: Page size (default 15).
            download: Return in download format.

        Returns:
            Search results, or *None* on error.

        Examples:
            >>> chebi = ChEBI()
            >>> results = chebi.structure_search("CCO", "connectivity")  # doctest: +SKIP
            >>> results["total"]                                         # doctest: +SKIP
            2
        """
        params: Dict[str, Any] = {
            "smiles": smiles,
            "search_type": search_type,
            "three_star_only": str(three_star_only).lower(),
            "page": page,
            "size": size,
            "download": str(download).lower(),
        }
        if similarity is not None:
            params["similarity"] = similarity

        try:
            return self._get("structure_search/", params=params)
        except ChEBIError as e:
            self.logger.warning(f"Structure search failed: {e}")
            return None

    # ------------------------------------------------------------------
    # Structure calculations
    # ------------------------------------------------------------------

    def calculate_avg_mass(self, structure: str) -> Optional[str]:
        """
        Calculate the average mass from a structure (a molfile).

        Endpoint: ``POST /structure-calculations/avg-mass/``

        Args:
            structure: A molfile. ChEBI does not accept SMILES here.

        Returns:
            The average mass as text, e.g. ``'46.069'``, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> from rdkit import Chem
            >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
            >>> chebi.calculate_avg_mass(molfile)  # doctest: +SKIP
            '46.069'
        """
        try:
            return self._post_text("structure-calculations/avg-mass/", structure)
        except ChEBIError as e:
            self.logger.warning(f"avg-mass calculation failed: {e}")
            return None

    def calculate_avg_mass_from_formula(self, formula: str) -> Optional[str]:
        """
        Calculate the average mass from a molecular formula.

        Endpoint: ``POST /structure-calculations/avg-mass/from-formula/``

        Args:
            formula: A molecular formula, e.g. ``'C2H6O'``.

        Returns:
            The average mass as text, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> chebi.calculate_avg_mass_from_formula('C2H6O')  # doctest: +SKIP
            '46.069'
        """
        try:
            return self._post_text("structure-calculations/avg-mass/from-formula/", formula)
        except ChEBIError as e:
            self.logger.warning(f"avg-mass-from-formula calculation failed: {e}")
            return None

    def calculate_mol_formula(self, structure: str) -> Optional[str]:
        """
        Calculate the molecular formula from a structure (a molfile).

        Endpoint: ``POST /structure-calculations/mol-formula/``

        Args:
            structure: A molfile. ChEBI does not accept SMILES here.

        Returns:
            The formula as text, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> from rdkit import Chem
            >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
            >>> chebi.calculate_mol_formula(molfile)  # doctest: +SKIP
            'C2H6O'
        """
        try:
            return self._post_text("structure-calculations/mol-formula/", structure)
        except ChEBIError as e:
            self.logger.warning(f"mol-formula calculation failed: {e}")
            return None

    def calculate_monoisotopic_mass(self, structure: str) -> Optional[str]:
        """
        Calculate the monoisotopic mass from a structure (a molfile).

        Endpoint: ``POST /structure-calculations/monoisotopic-mass/``

        Args:
            structure: A molfile. ChEBI does not accept SMILES here.

        Returns:
            The monoisotopic mass as text, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> from rdkit import Chem
            >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
            >>> chebi.calculate_monoisotopic_mass(molfile)  # doctest: +SKIP
            '46.041864812'
        """
        try:
            return self._post_text("structure-calculations/monoisotopic-mass/", structure)
        except ChEBIError as e:
            self.logger.warning(f"monoisotopic-mass calculation failed: {e}")
            return None

    def calculate_monoisotopic_mass_from_formula(self, formula: str) -> Optional[str]:
        """
        Calculate the monoisotopic mass from a molecular formula.

        Endpoint: ``POST /structure-calculations/monoisotopic-mass/from-formula/``

        Args:
            formula: A molecular formula, e.g. ``'C2H6O'``.

        Returns:
            The monoisotopic mass as text, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> chebi.calculate_monoisotopic_mass_from_formula('C2H6O')  # doctest: +SKIP
            '46.041864812'
        """
        try:
            return self._post_text(
                "structure-calculations/monoisotopic-mass/from-formula/", formula,
            )
        except ChEBIError as e:
            self.logger.warning(f"monoisotopic-mass-from-formula calculation failed: {e}")
            return None

    def calculate_net_charge(self, structure: str) -> Optional[str]:
        """
        Calculate the net charge from a structure (a molfile).

        Endpoint: ``POST /structure-calculations/net-charge/``

        Args:
            structure: A molfile. ChEBI does not accept SMILES here.

        Returns:
            The net charge as text, e.g. ``'-1'``, or *None* on error (a structure ChEBI cannot parse is
            HTTP 400, logged).

        Examples:
            >>> chebi = ChEBI()
            >>> from rdkit import Chem
            >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
            >>> chebi.calculate_net_charge(molfile)  # doctest: +SKIP
            '0'
        """
        try:
            return self._post_text("structure-calculations/net-charge/", structure)
        except ChEBIError as e:
            self.logger.warning(f"net-charge calculation failed: {e}")
            return None

    def depict_structure(self, structure: str, *, width: int = 300,
                         height: int = 300,
                         transparent_bg: bool = False) -> Optional[bytes]:
        """
        Generate a PNG depiction of a structure using Indigo.

        Endpoint: ``POST /structure-calculations/depict-indigo/``

        Args:
            structure: Structure in SMILES or molfile format.
            width: Image width in pixels (default 300).
            height: Image height in pixels (default 300).
            transparent_bg: Use transparent background (default *False*).

        Returns:
            PNG image data as bytes, or *None* on error.

        Examples:
            >>> png = ChEBI().depict_structure("CCO")             # doctest: +SKIP
            >>> png[:4]                                           # doctest: +SKIP
            b'\x89PNG'
        """
        params: Dict[str, Any] = {
            "width": width,
            "height": height,
            "transbg": str(transparent_bg).lower(),
        }
        try:
            response = self._post_raw(
                "structure-calculations/depict-indigo/", structure, params=params,
            )
            return response.content
        except ChEBIError as e:
            self.logger.warning(f"depict-indigo failed: {e}")
            return None

    # ------------------------------------------------------------------
    # Batch helpers
    # ------------------------------------------------------------------

    def batch_get_compounds(self, chebi_ids: List[Union[int, str]],
                            pause_time: float = 0.1) -> Dict[str, Dict[str, Any]]:
        """
        Retrieve compound info for multiple ChEBI IDs one-by-one.

        For small batches prefer
        [`get_compounds`][provesid.chebi.ChEBI.get_compounds] which uses the
        bulk endpoint.  This method calls
        [`get_compound`][provesid.chebi.ChEBI.get_compound] in a loop with an
        optional pause between requests.

        Args:
            chebi_ids: List of ChEBI IDs.
            pause_time: Seconds to pause between requests (default 0.1).

        Returns:
            dict mapping ``CHEBI:<id>`` to compound data. IDs that could not
            be fetched are left out.

        Examples:
            >>> found = ChEBI().batch_get_compounds([15377, 15365])  # doctest: +SKIP
            >>> {key: record["name"] for key, record in found.items()}  # doctest: +SKIP
            {'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
        """
        results: Dict[str, Dict[str, Any]] = {}
        for chebi_id in chebi_ids:
            key = self._format_chebi_id(chebi_id)
            entity = self.get_compound(chebi_id)
            if entity:
                results[key] = entity
            if pause_time > 0:
                time.sleep(pause_time)
        return results

    # ------------------------------------------------------------------
    # Dunder
    # ------------------------------------------------------------------

    def __repr__(self) -> str:
        """String representation of ChEBI client."""
        return f"ChEBI(base_url='{self.base_url}', timeout={self.timeout})"
Methods:
__init__(timeout=30)

Initialize ChEBI 2.0 API client.

Parameters:

Name Type Description Default
timeout int

Request timeout in seconds (default: 30)

30

Examples:

>>> ChEBI(timeout=60)
ChEBI(base_url='https://www.ebi.ac.uk/chebi/backend/api/public', timeout=60)
Source code in src/provesid/chebi.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def __init__(self, timeout: int = 30):
    """
    Initialize ChEBI 2.0 API client.

    Args:
        timeout (int): Request timeout in seconds (default: 30)

    Examples:
        >>> ChEBI(timeout=60)
        ChEBI(base_url='https://www.ebi.ac.uk/chebi/backend/api/public', timeout=60)
    """
    self.base_url = "https://www.ebi.ac.uk/chebi/backend/api/public"
    self.timeout = timeout
    self.session = requests.Session()
    self.session.headers.update({
        'User-Agent': 'PROVESID-ChEBI-Client/2.0',
        'Accept': 'application/json',
    })

    # Setup logging
    self.logger = logging.getLogger(__name__)

    # One shared transport, making its calls through the session above so
    # that the pooled connection and the persistent headers survive the
    # move. ChEBI uses its status codes honestly --- unlike PubChem and
    # CACTUS, it has no fault code in the body to read --- so the default
    # classifier is the right one.
    #
    # Two retries with a half-second base, rather than the transport's
    # three and one: an ontology walk makes many small requests to a fast
    # service, where a long back-off curve costs more than the request it
    # is protecting.
    self._http = HTTPClient(
        session=self.session,
        min_interval=CHEBI_MIN_INTERVAL,
        timeout=timeout,
        max_retries=2,
        backoff=0.5,
        error_cls=ChEBIError,
        not_found_cls=ChEBINotFoundError,
        timeout_cls=ChEBITimeoutError,
        pace_host=self.base_url,
        logger=self.logger,
    )
get_compound(chebi_id, *, only_ontology_parents=False, only_ontology_children=False)

Retrieve information about a single compound.

Endpoint: GET /compound/{chebi_id}/

Parameters:

Name Type Description Default
chebi_id Union[int, str]

ChEBI ID (with or without CHEBI: prefix).

required
only_ontology_parents bool

If True, return only ontology parents.

False
only_ontology_children bool

If True, return only ontology children.

False

Returns:

Type Description
Optional[Dict[str, Any]]

dict with compound data, or None if not found.

Examples:

>>> chebi = ChEBI()
>>> water = chebi.get_compound(15377)
>>> water['name'], water['chebi_accession']
('water', 'CHEBI:15377')
Source code in src/provesid/chebi.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def get_compound(self, chebi_id: Union[int, str], *,
                 only_ontology_parents: bool = False,
                 only_ontology_children: bool = False) -> Optional[Dict[str, Any]]:
    """
    Retrieve information about a single compound.

    Endpoint: ``GET /compound/{chebi_id}/``

    Args:
        chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).
        only_ontology_parents: If *True*, return only ontology parents.
        only_ontology_children: If *True*, return only ontology children.

    Returns:
        dict with compound data, or *None* if not found.

    Examples:
        >>> chebi = ChEBI()
        >>> water = chebi.get_compound(15377)              # doctest: +SKIP
        >>> water['name'], water['chebi_accession']        # doctest: +SKIP
        ('water', 'CHEBI:15377')
    """
    chebi_id_str = self._format_chebi_id(chebi_id)
    params: Dict[str, Any] = {}
    if only_ontology_parents:
        params["only_ontology_parents"] = "true"
    if only_ontology_children:
        params["only_ontology_children"] = "true"

    try:
        return self._get(f"compound/{chebi_id_str}/", params=params or None)
    except ChEBIError as e:
        self.logger.warning(f"Failed to get compound {chebi_id_str}: {e}")
        return None
get_compounds(chebi_ids)

Retrieve information about one or more compounds in a single call.

Endpoint: POST /compounds/

Parameters:

Name Type Description Default
chebi_ids List[Union[int, str]]

List of ChEBI IDs.

required

Returns:

Type Description
Optional[Any]

API response, or None on error: a dict keyed by CHEBI:<id>, one entry per ID asked for. Each holds exists, primary_chebi_id (the ID a secondary one maps to), id_type, standardized_chebi_id and data, which is the get_compound record, or None when the ID does not exist.

Examples:

>>> chebi = ChEBI()
>>> results = chebi.get_compounds(["CHEBI:15377", "CHEBI:15365"])
>>> {key: entry["data"]["name"] for key, entry in results.items()}
{'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
>>> chebi.get_compounds([999999999])["CHEBI:999999999"]["exists"]
False
Source code in src/provesid/chebi.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def get_compounds(self, chebi_ids: List[Union[int, str]]) -> Optional[Any]:
    """
    Retrieve information about one or more compounds in a single call.

    Endpoint: ``POST /compounds/``

    Args:
        chebi_ids: List of ChEBI IDs.

    Returns:
        API response, or *None* on error: a dict keyed by ``CHEBI:<id>``,
        one entry per ID asked for. Each holds ``exists``,
        ``primary_chebi_id`` (the ID a secondary one maps to),
        ``id_type``, ``standardized_chebi_id`` and ``data``, which is the
        [`get_compound`][provesid.chebi.ChEBI.get_compound] record, or
        None when the ID does not exist.

    Examples:
        >>> chebi = ChEBI()
        >>> results = chebi.get_compounds(["CHEBI:15377", "CHEBI:15365"])  # doctest: +SKIP
        >>> {key: entry["data"]["name"] for key, entry in results.items()}  # doctest: +SKIP
        {'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
        >>> chebi.get_compounds([999999999])["CHEBI:999999999"]["exists"]  # doctest: +SKIP
        False
    """
    ids_formatted = [self._format_chebi_id(cid) for cid in chebi_ids]
    try:
        return self._post_json("compounds/", json_body={"chebi_ids": ids_formatted})
    except ChEBIError as e:
        self.logger.warning(f"Failed to get compounds: {e}")
        return None
search(term, *, page=1, size=15)

General text search (Elasticsearch-backed).

Endpoint: GET /es_search/

You can search by ChEBI name, brand name, IUPAC name, synonym, InChIKey, formula, SMILES, InChI, CAS number, database cross-reference IDs, PubMed IDs, and more.

Parameters:

Name Type Description Default
term str

Search term (name, SMILES, InChIKey, CAS, formula, …).

required
page int

Page number for pagination (default 1).

1
size int

Page size (default 15).

15

Returns:

Type Description
Optional[Any]

Search results dict, or None on error: results (the hits, best first, each with its record under _source), total and number_pages.

Examples:

>>> chebi = ChEBI()
>>> results = chebi.search("paracetamol")
>>> results["results"][0]["_source"]["chebi_accession"]
'CHEBI:46195'
Source code in src/provesid/chebi.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def search(self, term: str, *, page: int = 1, size: int = 15) -> Optional[Any]:
    """
    General text search (Elasticsearch-backed).

    Endpoint: ``GET /es_search/``

    You can search by ChEBI name, brand name, IUPAC name, synonym,
    InChIKey, formula, SMILES, InChI, CAS number, database cross-reference
    IDs, PubMed IDs, and more.

    Args:
        term: Search term (name, SMILES, InChIKey, CAS, formula, …).
        page: Page number for pagination (default 1).
        size: Page size (default 15).

    Returns:
        Search results dict, or *None* on error: ``results`` (the hits,
        best first, each with its record under ``_source``), ``total`` and
        ``number_pages``.

    Examples:
        >>> chebi = ChEBI()
        >>> results = chebi.search("paracetamol")               # doctest: +SKIP
        >>> results["results"][0]["_source"]["chebi_accession"]  # doctest: +SKIP
        'CHEBI:46195'
    """
    params: Dict[str, Any] = {"term": term, "page": page, "size": size}
    try:
        return self._get("es_search/", params=params)
    except ChEBIError as e:
        self.logger.warning(f"Search failed for '{term}': {e}")
        return None
search_by_name(search_text, *, page=1, size=15)

Search ChEBI by compound name (convenience wrapper around search).

Parameters:

Name Type Description Default
search_text str

Text to search for.

required
page int

Page number for pagination (default 1).

1
size int

Page size (default 15).

15

Returns:

Type Description
List[Dict[str, Any]]

list of matching entity dicts (may be empty): the results of search, each carrying _score and the record under _source.

Examples:

>>> hits = ChEBI().search_by_name("paracetamol", size=2)
>>> [(hit["_source"]["chebi_accession"], hit["_source"]["name"]) for hit in hits]
[('CHEBI:46195', 'paracetamol'), ('CHEBI:74529', 'antidote to paracetamol poisoning')]
Source code in src/provesid/chebi.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def search_by_name(self, search_text: str, *, page: int = 1,
                   size: int = 15) -> List[Dict[str, Any]]:
    """
    Search ChEBI by compound name (convenience wrapper around
    [`search`][provesid.chebi.ChEBI.search]).

    Args:
        search_text: Text to search for.
        page: Page number for pagination (default 1).
        size: Page size (default 15).

    Returns:
        list of matching entity dicts (may be empty): the ``results`` of
        [`search`][provesid.chebi.ChEBI.search], each carrying ``_score``
        and the record under ``_source``.

    Examples:
        >>> hits = ChEBI().search_by_name("paracetamol", size=2)  # doctest: +SKIP
        >>> [(hit["_source"]["chebi_accession"], hit["_source"]["name"]) for hit in hits]  # doctest: +SKIP
        [('CHEBI:46195', 'paracetamol'), ('CHEBI:74529', 'antidote to paracetamol poisoning')]
    """
    result = self.search(search_text, page=page, size=size)
    if result is None:
        return []
    # The es_search endpoint typically returns a dict with a results list
    if isinstance(result, dict):
        return result.get("results", result.get("items", [result]))
    if isinstance(result, list):
        return result
    return []

Perform an advanced compound search using specification objects.

Endpoint: POST /advanced_search/

Seven specification types are supported (combine with and_specification, or_specification, but_not_specification):

  • ontology_specification
  • formula_specification
  • mass_specification
  • monoisotopicmass_specification
  • charge_specification
  • database_name_specification
  • text_search_specification

Parameters:

Name Type Description Default
specification Dict[str, Any]

Request body following the FullSpecification schema.

required
three_star_only bool

Only include 3-star compounds (default True).

True
has_structure Optional[bool]

Filter by structure availability (None = no filter).

None
page int

Page number (default 1).

1
size int

Page size (default 15).

15
download bool

Return results in download format (default False).

False

Returns:

Type Description
Optional[Any]

API response dict/list, or None on error.

Examples:

>>> chebi = ChEBI()
>>> results = chebi.advanced_search({
...     "formula_specification": {
...         "and_specification": [{"term": "C6H12O7"}]
...     }
... }, three_star_only=False)
>>> results["total"]
15
Source code in src/provesid/chebi.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def advanced_search(
    self,
    specification: Dict[str, Any],
    *,
    three_star_only: bool = True,
    has_structure: Optional[bool] = None,
    page: int = 1,
    size: int = 15,
    download: bool = False,
) -> Optional[Any]:
    """
    Perform an advanced compound search using specification objects.

    Endpoint: ``POST /advanced_search/``

    Seven specification types are supported (combine with ``and_specification``,
    ``or_specification``, ``but_not_specification``):

    - ``ontology_specification``
    - ``formula_specification``
    - ``mass_specification``
    - ``monoisotopicmass_specification``
    - ``charge_specification``
    - ``database_name_specification``
    - ``text_search_specification``

    Args:
        specification: Request body following the ``FullSpecification`` schema.
        three_star_only: Only include 3-star compounds (default *True*).
        has_structure: Filter by structure availability (*None* = no filter).
        page: Page number (default 1).
        size: Page size (default 15).
        download: Return results in download format (default *False*).

    Returns:
        API response dict/list, or *None* on error.

    Examples:
        >>> chebi = ChEBI()
        >>> results = chebi.advanced_search({
        ...     "formula_specification": {
        ...         "and_specification": [{"term": "C6H12O7"}]
        ...     }
        ... }, three_star_only=False)                         # doctest: +SKIP
        >>> results["total"]                                  # doctest: +SKIP
        15
    """
    params: Dict[str, Any] = {
        "three_star_only": str(three_star_only).lower(),
        "page": page,
        "size": size,
        "download": str(download).lower(),
    }
    if has_structure is not None:
        params["has_structure"] = str(has_structure).lower()

    try:
        return self._post_json("advanced_search/", json_body=specification,
                               params=params)
    except ChEBIError as e:
        self.logger.warning(f"Advanced search failed: {e}")
        return None
get_sources_list()

Retrieve the list of available database sources for advanced search.

Endpoint: GET /advanced_search/sources_list

Returns:

Type Description
Optional[Any]

Sources information, or None on error: a list of {"prefix", "name"} dicts, the names usable in a database_name_specification.

Examples:

>>> ChEBI().get_sources_list()[:2]
[{'prefix': 'agr', 'name': 'Agricola'}, {'prefix': 'pesticides', 'name': "Alan Wood's Pesticides"}]
Source code in src/provesid/chebi.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def get_sources_list(self) -> Optional[Any]:
    """
    Retrieve the list of available database sources for advanced search.

    Endpoint: ``GET /advanced_search/sources_list``

    Returns:
        Sources information, or *None* on error: a list of
        ``{"prefix", "name"}`` dicts, the names usable in a
        ``database_name_specification``.

    Examples:
        >>> ChEBI().get_sources_list()[:2]                    # doctest: +SKIP
        [{'prefix': 'agr', 'name': 'Agricola'}, {'prefix': 'pesticides', 'name': "Alan Wood's Pesticides"}]
    """
    try:
        return self._get("advanced_search/sources_list")
    except ChEBIError as e:
        self.logger.warning(f"Failed to get sources list: {e}")
        return None
get_ontology_parents(chebi_id)

Get the ontology parents of a compound.

Endpoint: GET /ontology/parents/{chebi_id}/

Parameters:

Name Type Description Default
chebi_id Union[int, str]

ChEBI ID (with or without CHEBI: prefix).

required

Returns:

Type Description
Optional[Any]

Ontology parent data, or None on error: the compound's id and chebi_accession, with its relations under ontology_relations["outgoing_relations"], each naming the relation_type and the parent (final_id, final_name).

Examples:

>>> parents = ChEBI().get_ontology_parents(15377)
>>> first = parents["ontology_relations"]["outgoing_relations"][0]
>>> first["relation_type"], first["final_id"]
('has role', 75772)
Source code in src/provesid/chebi.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def get_ontology_parents(self, chebi_id: Union[int, str]) -> Optional[Any]:
    """
    Get the ontology parents of a compound.

    Endpoint: ``GET /ontology/parents/{chebi_id}/``

    Args:
        chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).

    Returns:
        Ontology parent data, or *None* on error: the compound's ``id`` and
        ``chebi_accession``, with its relations under
        ``ontology_relations["outgoing_relations"]``, each naming the
        ``relation_type`` and the parent (``final_id``, ``final_name``).

    Examples:
        >>> parents = ChEBI().get_ontology_parents(15377)     # doctest: +SKIP
        >>> first = parents["ontology_relations"]["outgoing_relations"][0]  # doctest: +SKIP
        >>> first["relation_type"], first["final_id"]         # doctest: +SKIP
        ('has role', 75772)
    """
    chebi_id_str = self._format_chebi_id(chebi_id)
    try:
        return self._get(f"ontology/parents/{chebi_id_str}/")
    except ChEBIError as e:
        self.logger.warning(f"Failed to get ontology parents for {chebi_id_str}: {e}")
        return None
get_ontology_children(chebi_id)

Get the ontology children of a compound.

Endpoint: GET /ontology/children/{chebi_id}/

Parameters:

Name Type Description Default
chebi_id Union[int, str]

ChEBI ID (with or without CHEBI: prefix).

required

Returns:

Type Description
Optional[Any]

Ontology children data, or None on error: as for get_ontology_parents, with the relations under ontology_relations["incoming_relations"] and the child named by init_id and init_name.

Examples:

>>> children = ChEBI().get_ontology_children(15377)
>>> children["ontology_relations"]["incoming_relations"][0]["init_name"]
'methane clathrate'
Source code in src/provesid/chebi.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def get_ontology_children(self, chebi_id: Union[int, str]) -> Optional[Any]:
    """
    Get the ontology children of a compound.

    Endpoint: ``GET /ontology/children/{chebi_id}/``

    Args:
        chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).

    Returns:
        Ontology children data, or *None* on error: as for
        [`get_ontology_parents`][provesid.chebi.ChEBI.get_ontology_parents],
        with the relations under
        ``ontology_relations["incoming_relations"]`` and the child named by
        ``init_id`` and ``init_name``.

    Examples:
        >>> children = ChEBI().get_ontology_children(15377)   # doctest: +SKIP
        >>> children["ontology_relations"]["incoming_relations"][0]["init_name"]  # doctest: +SKIP
        'methane clathrate'
    """
    chebi_id_str = self._format_chebi_id(chebi_id)
    try:
        return self._get(f"ontology/children/{chebi_id_str}/")
    except ChEBIError as e:
        self.logger.warning(f"Failed to get ontology children for {chebi_id_str}: {e}")
        return None
get_all_ontology_children_in_path(relation, entity, *, three_star_only=True, has_structure=None, page=1, size=15, download=False)

Search all compounds in the ontology matching a relation and entity.

Endpoint: GET /ontology/all_children_in_path/

Parameters:

Name Type Description Default
relation str

Ontology relation type (e.g. is_a, has_role).

required
entity Union[int, str]

ChEBI ID of the entity to find children of.

required
three_star_only bool

Only include 3-star compounds (default True).

True
has_structure Optional[bool]

Filter by structure availability.

None
page int

Page number (default 1).

1
size int

Page size (default 15).

15
download bool

Return results in download format.

False

Returns:

Type Description
Optional[Any]

API response, or None on error.

Examples:

>>> chebi = ChEBI()
>>> # Get all compounds that are alcohols
>>> results = chebi.get_all_ontology_children_in_path(
...     relation="is_a", entity="CHEBI:30879"
... )
>>> results["total"]
4029
Source code in src/provesid/chebi.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def get_all_ontology_children_in_path(
    self,
    relation: str,
    entity: Union[int, str],
    *,
    three_star_only: bool = True,
    has_structure: Optional[bool] = None,
    page: int = 1,
    size: int = 15,
    download: bool = False,
) -> Optional[Any]:
    """
    Search all compounds in the ontology matching a relation and entity.

    Endpoint: ``GET /ontology/all_children_in_path/``

    Args:
        relation: Ontology relation type (e.g. ``is_a``, ``has_role``).
        entity: ChEBI ID of the entity to find children of.
        three_star_only: Only include 3-star compounds (default *True*).
        has_structure: Filter by structure availability.
        page: Page number (default 1).
        size: Page size (default 15).
        download: Return results in download format.

    Returns:
        API response, or *None* on error.

    Examples:
        >>> chebi = ChEBI()
        >>> # Get all compounds that are alcohols
        >>> results = chebi.get_all_ontology_children_in_path(
        ...     relation="is_a", entity="CHEBI:30879"
        ... )                                                 # doctest: +SKIP
        >>> results["total"]                                  # doctest: +SKIP
        4029
    """
    entity_str = self._format_chebi_id(entity)
    params: Dict[str, Any] = {
        "relation": relation,
        "entity": entity_str,
        "three_star_only": str(three_star_only).lower(),
        "page": page,
        "size": size,
        "download": str(download).lower(),
    }
    if has_structure is not None:
        params["has_structure"] = str(has_structure).lower()

    try:
        return self._get("ontology/all_children_in_path/", params=params)
    except ChEBIError as e:
        self.logger.warning(f"Failed to get all ontology children: {e}")
        return None
get_compound_structure(chebi_id, *, width=300, height=300)

Get the default SVG structure for a compound.

Endpoint: GET /compound/{id}/structure/

Parameters:

Name Type Description Default
chebi_id Union[int, str]

ChEBI ID (numeric, the primary key of the compound).

required
width int

Width of the SVG (default 300).

300
height int

Height of the SVG (default 300).

300

Returns:

Type Description
Optional[str]

Raw SVG string, or None on error.

Examples:

>>> ChEBI().get_compound_structure(15377)[:21]
"<?xml version='1.0' e"
Source code in src/provesid/chebi.py
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
def get_compound_structure(self, chebi_id: Union[int, str], *,
                           width: int = 300, height: int = 300) -> Optional[str]:
    """
    Get the default SVG structure for a compound.

    Endpoint: ``GET /compound/{id}/structure/``

    Args:
        chebi_id: ChEBI ID (numeric, the primary key of the compound).
        width: Width of the SVG (default 300).
        height: Height of the SVG (default 300).

    Returns:
        Raw SVG string, or *None* on error.

    Examples:
        >>> ChEBI().get_compound_structure(15377)[:21]        # doctest: +SKIP
        "<?xml version='1.0' e"
    """
    # This endpoint expects the numeric compound PK
    numeric_id = str(chebi_id)
    if numeric_id.upper().startswith("CHEBI:"):
        numeric_id = numeric_id.split(":")[-1]

    params: Dict[str, Any] = {"width": width, "height": height}
    try:
        resp = self._get_raw(f"compound/{numeric_id}/structure/", params=params)
        return resp.text
    except ChEBIError as e:
        self.logger.warning(f"Failed to get compound structure for {chebi_id}: {e}")
        return None
get_structure(structure_id, *, width=300, height=300)

Get raw SVG contents of a structure by its primary key.

Endpoint: GET /structure/{id}/

Parameters:

Name Type Description Default
structure_id int

Primary key of the structure.

required
width int

Width of the SVG (default 300).

300
height int

Height of the SVG (default 300).

300

Returns:

Type Description
Optional[str]

Raw SVG string, or None on error.

Examples:

>>> chebi = ChEBI()
>>> structure_id = chebi.get_compound(15377)["default_structure"]["id"]
>>> structure_id, chebi.get_structure(structure_id)[:5]
(2018, '<?xml')
Source code in src/provesid/chebi.py
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def get_structure(self, structure_id: int, *, width: int = 300,
                  height: int = 300) -> Optional[str]:
    """
    Get raw SVG contents of a structure by its primary key.

    Endpoint: ``GET /structure/{id}/``

    Args:
        structure_id: Primary key of the structure.
        width: Width of the SVG (default 300).
        height: Height of the SVG (default 300).

    Returns:
        Raw SVG string, or *None* on error.

    Examples:
        >>> chebi = ChEBI()
        >>> structure_id = chebi.get_compound(15377)["default_structure"]["id"]  # doctest: +SKIP
        >>> structure_id, chebi.get_structure(structure_id)[:5]  # doctest: +SKIP
        (2018, '<?xml')
    """
    params: Dict[str, Any] = {"width": width, "height": height}
    try:
        resp = self._get_raw(f"structure/{structure_id}/", params=params)
        return resp.text
    except ChEBIError as e:
        self.logger.warning(f"Failed to get structure {structure_id}: {e}")
        return None
get_molfile(compound_id)

Download the Mol file for a compound's default structure.

Endpoint: GET /molfile/{id}/

Parameters:

Name Type Description Default
compound_id int

Primary key of the compound.

required

Returns:

Type Description
Optional[str]

Mol file contents as string, or None on error.

Examples:

>>> molfile = ChEBI().get_molfile(15377)
>>> molfile.splitlines()[3][:6]
'  3  2'
Source code in src/provesid/chebi.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def get_molfile(self, compound_id: int) -> Optional[str]:
    """
    Download the Mol file for a compound's default structure.

    Endpoint: ``GET /molfile/{id}/``

    Args:
        compound_id: Primary key of the compound.

    Returns:
        Mol file contents as string, or *None* on error.

    Examples:
        >>> molfile = ChEBI().get_molfile(15377)              # doctest: +SKIP
        >>> molfile.splitlines()[3][:6]                       # doctest: +SKIP
        '  3  2'
    """
    try:
        resp = self._get_raw(f"molfile/{compound_id}/")
        return resp.text
    except ChEBIError as e:
        self.logger.warning(f"Failed to get molfile for {compound_id}: {e}")
        return None

Search compounds by chemical structure.

Endpoint: GET /structure_search/

Parameters:

Name Type Description Default
smiles str

Molecule structure in SMILES representation.

required
search_type str

One of connectivity, similarity, substructure.

'connectivity'
similarity Optional[float]

Similarity threshold for similarity search (0.4–1.0).

None
three_star_only bool

Only include 3-star compounds (default True).

True
page int

Page number (default 1).

1
size int

Page size (default 15).

15
download bool

Return in download format.

False

Returns:

Type Description
Optional[Any]

Search results, or None on error.

Examples:

>>> chebi = ChEBI()
>>> results = chebi.structure_search("CCO", "connectivity")
>>> results["total"]
2
Source code in src/provesid/chebi.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def structure_search(
    self,
    smiles: str,
    search_type: str = "connectivity",
    *,
    similarity: Optional[float] = None,
    three_star_only: bool = True,
    page: int = 1,
    size: int = 15,
    download: bool = False,
) -> Optional[Any]:
    """
    Search compounds by chemical structure.

    Endpoint: ``GET /structure_search/``

    Args:
        smiles: Molecule structure in SMILES representation.
        search_type: One of ``connectivity``, ``similarity``, ``substructure``.
        similarity: Similarity threshold for similarity search (0.4–1.0).
        three_star_only: Only include 3-star compounds (default *True*).
        page: Page number (default 1).
        size: Page size (default 15).
        download: Return in download format.

    Returns:
        Search results, or *None* on error.

    Examples:
        >>> chebi = ChEBI()
        >>> results = chebi.structure_search("CCO", "connectivity")  # doctest: +SKIP
        >>> results["total"]                                         # doctest: +SKIP
        2
    """
    params: Dict[str, Any] = {
        "smiles": smiles,
        "search_type": search_type,
        "three_star_only": str(three_star_only).lower(),
        "page": page,
        "size": size,
        "download": str(download).lower(),
    }
    if similarity is not None:
        params["similarity"] = similarity

    try:
        return self._get("structure_search/", params=params)
    except ChEBIError as e:
        self.logger.warning(f"Structure search failed: {e}")
        return None
calculate_avg_mass(structure)

Calculate the average mass from a structure (a molfile).

Endpoint: POST /structure-calculations/avg-mass/

Parameters:

Name Type Description Default
structure str

A molfile. ChEBI does not accept SMILES here.

required

Returns:

Type Description
Optional[str]

The average mass as text, e.g. '46.069', or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> from rdkit import Chem
>>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
>>> chebi.calculate_avg_mass(molfile)
'46.069'
Source code in src/provesid/chebi.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
def calculate_avg_mass(self, structure: str) -> Optional[str]:
    """
    Calculate the average mass from a structure (a molfile).

    Endpoint: ``POST /structure-calculations/avg-mass/``

    Args:
        structure: A molfile. ChEBI does not accept SMILES here.

    Returns:
        The average mass as text, e.g. ``'46.069'``, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> from rdkit import Chem
        >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
        >>> chebi.calculate_avg_mass(molfile)  # doctest: +SKIP
        '46.069'
    """
    try:
        return self._post_text("structure-calculations/avg-mass/", structure)
    except ChEBIError as e:
        self.logger.warning(f"avg-mass calculation failed: {e}")
        return None
calculate_avg_mass_from_formula(formula)

Calculate the average mass from a molecular formula.

Endpoint: POST /structure-calculations/avg-mass/from-formula/

Parameters:

Name Type Description Default
formula str

A molecular formula, e.g. 'C2H6O'.

required

Returns:

Type Description
Optional[str]

The average mass as text, or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> chebi.calculate_avg_mass_from_formula('C2H6O')
'46.069'
Source code in src/provesid/chebi.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
def calculate_avg_mass_from_formula(self, formula: str) -> Optional[str]:
    """
    Calculate the average mass from a molecular formula.

    Endpoint: ``POST /structure-calculations/avg-mass/from-formula/``

    Args:
        formula: A molecular formula, e.g. ``'C2H6O'``.

    Returns:
        The average mass as text, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> chebi.calculate_avg_mass_from_formula('C2H6O')  # doctest: +SKIP
        '46.069'
    """
    try:
        return self._post_text("structure-calculations/avg-mass/from-formula/", formula)
    except ChEBIError as e:
        self.logger.warning(f"avg-mass-from-formula calculation failed: {e}")
        return None
calculate_mol_formula(structure)

Calculate the molecular formula from a structure (a molfile).

Endpoint: POST /structure-calculations/mol-formula/

Parameters:

Name Type Description Default
structure str

A molfile. ChEBI does not accept SMILES here.

required

Returns:

Type Description
Optional[str]

The formula as text, or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> from rdkit import Chem
>>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
>>> chebi.calculate_mol_formula(molfile)
'C2H6O'
Source code in src/provesid/chebi.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def calculate_mol_formula(self, structure: str) -> Optional[str]:
    """
    Calculate the molecular formula from a structure (a molfile).

    Endpoint: ``POST /structure-calculations/mol-formula/``

    Args:
        structure: A molfile. ChEBI does not accept SMILES here.

    Returns:
        The formula as text, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> from rdkit import Chem
        >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
        >>> chebi.calculate_mol_formula(molfile)  # doctest: +SKIP
        'C2H6O'
    """
    try:
        return self._post_text("structure-calculations/mol-formula/", structure)
    except ChEBIError as e:
        self.logger.warning(f"mol-formula calculation failed: {e}")
        return None
calculate_monoisotopic_mass(structure)

Calculate the monoisotopic mass from a structure (a molfile).

Endpoint: POST /structure-calculations/monoisotopic-mass/

Parameters:

Name Type Description Default
structure str

A molfile. ChEBI does not accept SMILES here.

required

Returns:

Type Description
Optional[str]

The monoisotopic mass as text, or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> from rdkit import Chem
>>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
>>> chebi.calculate_monoisotopic_mass(molfile)
'46.041864812'
Source code in src/provesid/chebi.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
def calculate_monoisotopic_mass(self, structure: str) -> Optional[str]:
    """
    Calculate the monoisotopic mass from a structure (a molfile).

    Endpoint: ``POST /structure-calculations/monoisotopic-mass/``

    Args:
        structure: A molfile. ChEBI does not accept SMILES here.

    Returns:
        The monoisotopic mass as text, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> from rdkit import Chem
        >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
        >>> chebi.calculate_monoisotopic_mass(molfile)  # doctest: +SKIP
        '46.041864812'
    """
    try:
        return self._post_text("structure-calculations/monoisotopic-mass/", structure)
    except ChEBIError as e:
        self.logger.warning(f"monoisotopic-mass calculation failed: {e}")
        return None
calculate_monoisotopic_mass_from_formula(formula)

Calculate the monoisotopic mass from a molecular formula.

Endpoint: POST /structure-calculations/monoisotopic-mass/from-formula/

Parameters:

Name Type Description Default
formula str

A molecular formula, e.g. 'C2H6O'.

required

Returns:

Type Description
Optional[str]

The monoisotopic mass as text, or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> chebi.calculate_monoisotopic_mass_from_formula('C2H6O')
'46.041864812'
Source code in src/provesid/chebi.py
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def calculate_monoisotopic_mass_from_formula(self, formula: str) -> Optional[str]:
    """
    Calculate the monoisotopic mass from a molecular formula.

    Endpoint: ``POST /structure-calculations/monoisotopic-mass/from-formula/``

    Args:
        formula: A molecular formula, e.g. ``'C2H6O'``.

    Returns:
        The monoisotopic mass as text, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> chebi.calculate_monoisotopic_mass_from_formula('C2H6O')  # doctest: +SKIP
        '46.041864812'
    """
    try:
        return self._post_text(
            "structure-calculations/monoisotopic-mass/from-formula/", formula,
        )
    except ChEBIError as e:
        self.logger.warning(f"monoisotopic-mass-from-formula calculation failed: {e}")
        return None
calculate_net_charge(structure)

Calculate the net charge from a structure (a molfile).

Endpoint: POST /structure-calculations/net-charge/

Parameters:

Name Type Description Default
structure str

A molfile. ChEBI does not accept SMILES here.

required

Returns:

Type Description
Optional[str]

The net charge as text, e.g. '-1', or None on error (a structure ChEBI cannot parse is HTTP 400, logged).

Examples:

>>> chebi = ChEBI()
>>> from rdkit import Chem
>>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
>>> chebi.calculate_net_charge(molfile)
'0'
Source code in src/provesid/chebi.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
def calculate_net_charge(self, structure: str) -> Optional[str]:
    """
    Calculate the net charge from a structure (a molfile).

    Endpoint: ``POST /structure-calculations/net-charge/``

    Args:
        structure: A molfile. ChEBI does not accept SMILES here.

    Returns:
        The net charge as text, e.g. ``'-1'``, or *None* on error (a structure ChEBI cannot parse is
        HTTP 400, logged).

    Examples:
        >>> chebi = ChEBI()
        >>> from rdkit import Chem
        >>> molfile = Chem.MolToMolBlock(Chem.MolFromSmiles("CCO"))
        >>> chebi.calculate_net_charge(molfile)  # doctest: +SKIP
        '0'
    """
    try:
        return self._post_text("structure-calculations/net-charge/", structure)
    except ChEBIError as e:
        self.logger.warning(f"net-charge calculation failed: {e}")
        return None
depict_structure(structure, *, width=300, height=300, transparent_bg=False)

Generate a PNG depiction of a structure using Indigo.

Endpoint: POST /structure-calculations/depict-indigo/

Parameters:

Name Type Description Default
structure str

Structure in SMILES or molfile format.

required
width int

Image width in pixels (default 300).

300
height int

Image height in pixels (default 300).

300
transparent_bg bool

Use transparent background (default False).

False

Returns:

Type Description
Optional[bytes]

PNG image data as bytes, or None on error.

Examples:

>>> png = ChEBI().depict_structure("CCO")
>>> png[:4]
b'‰PNG'
Source code in src/provesid/chebi.py
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def depict_structure(self, structure: str, *, width: int = 300,
                     height: int = 300,
                     transparent_bg: bool = False) -> Optional[bytes]:
    """
    Generate a PNG depiction of a structure using Indigo.

    Endpoint: ``POST /structure-calculations/depict-indigo/``

    Args:
        structure: Structure in SMILES or molfile format.
        width: Image width in pixels (default 300).
        height: Image height in pixels (default 300).
        transparent_bg: Use transparent background (default *False*).

    Returns:
        PNG image data as bytes, or *None* on error.

    Examples:
        >>> png = ChEBI().depict_structure("CCO")             # doctest: +SKIP
        >>> png[:4]                                           # doctest: +SKIP
        b'\x89PNG'
    """
    params: Dict[str, Any] = {
        "width": width,
        "height": height,
        "transbg": str(transparent_bg).lower(),
    }
    try:
        response = self._post_raw(
            "structure-calculations/depict-indigo/", structure, params=params,
        )
        return response.content
    except ChEBIError as e:
        self.logger.warning(f"depict-indigo failed: {e}")
        return None
batch_get_compounds(chebi_ids, pause_time=0.1)

Retrieve compound info for multiple ChEBI IDs one-by-one.

For small batches prefer get_compounds which uses the bulk endpoint. This method calls get_compound in a loop with an optional pause between requests.

Parameters:

Name Type Description Default
chebi_ids List[Union[int, str]]

List of ChEBI IDs.

required
pause_time float

Seconds to pause between requests (default 0.1).

0.1

Returns:

Type Description
Dict[str, Dict[str, Any]]

dict mapping CHEBI:<id> to compound data. IDs that could not be fetched are left out.

Examples:

>>> found = ChEBI().batch_get_compounds([15377, 15365])
>>> {key: record["name"] for key, record in found.items()}
{'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
Source code in src/provesid/chebi.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def batch_get_compounds(self, chebi_ids: List[Union[int, str]],
                        pause_time: float = 0.1) -> Dict[str, Dict[str, Any]]:
    """
    Retrieve compound info for multiple ChEBI IDs one-by-one.

    For small batches prefer
    [`get_compounds`][provesid.chebi.ChEBI.get_compounds] which uses the
    bulk endpoint.  This method calls
    [`get_compound`][provesid.chebi.ChEBI.get_compound] in a loop with an
    optional pause between requests.

    Args:
        chebi_ids: List of ChEBI IDs.
        pause_time: Seconds to pause between requests (default 0.1).

    Returns:
        dict mapping ``CHEBI:<id>`` to compound data. IDs that could not
        be fetched are left out.

    Examples:
        >>> found = ChEBI().batch_get_compounds([15377, 15365])  # doctest: +SKIP
        >>> {key: record["name"] for key, record in found.items()}  # doctest: +SKIP
        {'CHEBI:15377': 'water', 'CHEBI:15365': 'acetylsalicylic acid'}
    """
    results: Dict[str, Dict[str, Any]] = {}
    for chebi_id in chebi_ids:
        key = self._format_chebi_id(chebi_id)
        entity = self.get_compound(chebi_id)
        if entity:
            results[key] = entity
        if pause_time > 0:
            time.sleep(pause_time)
    return results
__repr__()

String representation of ChEBI client.

Source code in src/provesid/chebi.py
1035
1036
1037
def __repr__(self) -> str:
    """String representation of ChEBI client."""
    return f"ChEBI(base_url='{self.base_url}', timeout={self.timeout})"

Functions:

get_chebi_entity(chebi_id)

Convenience function to get ChEBI compound information.

Parameters:

Name Type Description Default
chebi_id Union[int, str]

ChEBI ID (with or without CHEBI: prefix).

required

Returns:

Type Description
Optional[Dict[str, Any]]

dict with compound data, or None if not found.

Examples:

>>> from provesid import get_chebi_entity
>>> water = get_chebi_entity(15377)
>>> water["default_structure"]["smiles"]
'[H]O[H]'
Source code in src/provesid/chebi.py
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
def get_chebi_entity(chebi_id: Union[int, str]) -> Optional[Dict[str, Any]]:
    """
    Convenience function to get ChEBI compound information.

    Args:
        chebi_id: ChEBI ID (with or without ``CHEBI:`` prefix).

    Returns:
        dict with compound data, or *None* if not found.

    Examples:
        >>> from provesid import get_chebi_entity
        >>> water = get_chebi_entity(15377)                   # doctest: +SKIP
        >>> water["default_structure"]["smiles"]              # doctest: +SKIP
        '[H]O[H]'
    """
    chebi = ChEBI()
    return chebi.get_compound(chebi_id)

search_chebi(search_text, max_results=10)

Convenience function to search ChEBI by name.

Parameters:

Name Type Description Default
search_text str

Text to search for.

required
max_results int

Maximum number of results to return.

10

Returns:

Type Description
List[Dict[str, Any]]

list of matching entity dicts.

Examples:

>>> from provesid import search_chebi
>>> results = search_chebi("paracetamol", max_results=1)
>>> results[0]["_source"]["name"]
'paracetamol'
Source code in src/provesid/chebi.py
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
def search_chebi(search_text: str, max_results: int = 10) -> List[Dict[str, Any]]:
    """
    Convenience function to search ChEBI by name.

    Args:
        search_text: Text to search for.
        max_results: Maximum number of results to return.

    Returns:
        list of matching entity dicts.

    Examples:
        >>> from provesid import search_chebi
        >>> results = search_chebi("paracetamol", max_results=1)  # doctest: +SKIP
        >>> results[0]["_source"]["name"]                         # doctest: +SKIP
        'paracetamol'
    """
    chebi = ChEBI()
    return chebi.search_by_name(search_text, size=max_results)