RestApiRepository

Bases: Generic[DomainModel]

Implementation of ApiRepository that interacts with a RESTful API using the requests library.

This repository provides methods for common CRUD operations (Create, Read, Update, Delete). It handles the construction of API URLs, serialization/ deserialization of domain models, and interaction with the requests library. It also allows for flexible configuration of the API endpoints, session management, and response handling. The repository can be easily extended or customized for specific API requirements.

Generic
The type of the domain model that this repository will manage. This
allows for type safety and better integration with the rest of the
application.
Source code in src/alpha/repositories/rest_api_repository.py
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
class RestApiRepository(Generic[DomainModel]):
    """Implementation of `ApiRepository` that interacts with a RESTful API
    using the `requests` library.

    This repository provides methods for common CRUD operations (Create, Read,
    Update, Delete). It handles the construction of API URLs, serialization/
    deserialization of domain models, and interaction with the `requests`
    library. It also allows for flexible configuration of the API endpoints,
    session management, and response handling. The repository can be easily
    extended or customized for specific API requirements.

    Generic
    -------
        The type of the domain model that this repository will manage. This
        allows for type safety and better integration with the rest of the
        application.
    """

    def __init__(
        self,
        host: str,
        scheme: str | None = None,
        base_path: str = "",
        endpoint: str = "",
        default_model: DomainModel | None = None,
        use_factory: bool = True,
        serialize: bool = True,
        model_factory_method_name: str = "from_dict",
        model_serialization_method_name: str = "to_dict",
        client: HTTPClient | None = None,
        session: HTTPClient | None = None,
        request_headers: dict[str, str] | None = None,
        request_cookies: dict[str, str] | None = None,
        response_data_attribute: str | None = None,
    ) -> None:
        """Initialize the REST API repository.

        Parameters
        ----------
        host
            The base URL of the API.
        scheme
            The URL scheme to use (e.g., "http" or "https"). This is only used
            if the host does not already include a scheme, by default "https"
        base_path
            The base path of the API, by default ""
        endpoint
            The default endpoint for the API. This value is used when no
            specific endpoint is provided in the method calls, by default ""
        default_model
            The default model to use for serialization/deserialization,
            by default None
        use_factory
            Whether to use the model factory method for creating models from
            response data, by default True
        serialize
            Whether to serialize objects before sending them in requests,
            by default True
        model_factory_method_name
            The name of the class method to use for creating models from
            dictionaries, by default "from_dict"
        model_serialization_method_name
            The name of the method to use for serializing models to
            dictionaries, by default "to_dict"
        client
            An HTTP client to use for context management, by default None.
            If None, a new `requests.sessions.Session` will be created and
            used. This allows for flexibility in using different HTTP client
            implementations that conform to the `HTTPClient` protocol, while
            still providing a default option with `requests`.
        session
            Deprecated: An HTTP client session to use for making requests, by
            default None. Use `client` instead. This parameter is still
            supported for backward compatibility.
        request_headers
            Default headers to include in every request, by default None
        request_cookies
            Default cookies to include in every request, by default None
        response_data_attribute
            The attribute in the response data to extract the relevant data
            from, by default None
        """
        self._host = host
        self._scheme = scheme or "https"
        self._base_path = base_path
        self._endpoint = endpoint
        self._default_model = default_model
        self._use_factory = use_factory
        self._serialize = serialize
        self._model_factory_method_name = model_factory_method_name
        self._model_serialization_method_name = model_serialization_method_name

        client_obj = client or session or requests.sessions.Session()
        # Expose the underlying client publicly for consistency with other
        # repositories
        self.client = client_obj
        # Preserve the deprecated public session alias for backward
        # compatibility
        self.session = client_obj
        # Preserve the existing private attribute for backward compatibility
        self._session = client_obj

        self._request_headers = request_headers or {}
        self._request_cookies = request_cookies or {}
        self._response_data_attribute = response_data_attribute
        # Update client with default headers and cookies
        self.client.headers.update(request_headers or {})
        cookiejar_from_dict(
            request_cookies or {},
            cookiejar=self.client.cookies,
            overwrite=True,
        )

    def add(
        self,
        obj: DomainModel,
        return_obj: bool = True,
        serialize: bool | None = None,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> DomainModel | dict[str, Any] | None:
        """Add a new resource.

        Parameters
        ----------
        obj
            The object to add.
        return_obj
            Whether to return the added object or not.
        serialize
            Whether to serialize the object before sending it in the API
            request.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            The added object if `return_obj` is `True`, otherwise `None`.
        """
        if self._determine_serialization(serialize):
            obj = self._serialize_object(obj)

        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            **params,
        )

        response_data = self._post(
            url=url,
            data=obj,
            additional_request_params=additional_request_params,
        )

        if return_obj is False:
            return None

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_object(response_data, model)

    def add_all(
        self,
        objs: list[DomainModel],
        return_objs: bool = True,
        serialize: bool | None = None,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        one_by_one: bool = False,
        **params: Any,
    ) -> list[DomainModel] | list[dict[str, Any]] | None:
        """Add multiple new resources.

        Parameters
        ----------
        objs
            The objects to add.
        return_objs
            Whether to return the added objects or not.
        serialize
            Whether to serialize the objects before sending it in the API
            request.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the objects should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        one_by_one
            Whether to add the objects one by one (i.e. make a separate API
            call for each object).
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            A list of added objects if `return_objs` is `True`, otherwise
            `None`.
        """
        if one_by_one:
            results: list[DomainModel] | list[dict[str, Any]] = []
            for obj in objs:
                result = self.add(
                    obj=obj,
                    return_obj=return_objs,
                    serialize=serialize,
                    use_factory=use_factory,
                    endpoint=endpoint,
                    parent_endpoint=parent_endpoint,
                    parent_param=parent_param,
                    model=model,
                    additional_request_params=additional_request_params,
                    **params,
                )
                if result is not None:
                    results.append(result)  # type: ignore
            return results if return_objs else None

        if self._determine_serialization(serialize):
            objs = [self._serialize_object(obj) for obj in objs]

        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            **params,
        )

        response_data = self._post(
            url=url,
            data=objs,
            additional_request_params=additional_request_params,
        )

        if return_objs is False:
            return None

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_array(response_data, model)

    def get(
        self,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> DomainModel | dict[str, Any]:
        """Retrieve a single resource.

        Parameters
        ----------
        endpoint
            The API endpoint from which to retrieve the resource.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        param
            The parameter to identify the specific resource. This could be an
            ID or a unique identifier. The parameter will be appended to the
            endpoint to form the full URL for the GET request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            The retrieved object.
        """
        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            param=param,
            **params,
        )

        response_data: dict[str, Any] = self._get(
            url=url,
            additional_request_params=additional_request_params,
        )

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_object(response_data, model)

    def get_all(
        self,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> list[DomainModel] | list[dict[str, Any]]:
        """Retrieve multiple resources.

        Parameters
        ----------
        endpoint
            The API endpoint from which to retrieve the resource.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        param
            The parameter to identify the specific resource. This could be an
            ID or a unique identifier. The parameter will be appended to the
            endpoint to form the full URL for the GET request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            The retrieved objects.
        """
        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            param=param,
            **params,
        )

        response_data: list[dict[str, Any]] = self._get(
            url=url,
            additional_request_params=additional_request_params,
        )

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_array(response_data, model)

    def patch(
        self,
        patch: JsonPatch,
        return_obj: bool = True,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> DomainModel | dict[str, Any] | None:
        """Update a resource.

        Parameters
        ----------
        patch
            The JSON Patch object containing the changes to be applied to the
            resource. This object should conform to the JSON Patch
            specification.
        return_obj
            Whether to return the updated object or not.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        param
            The parameter to identify the specific resource. This could be an
            ID or a unique identifier. The parameter will be appended to the
            endpoint to form the full URL for the GET request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            The updated object if `return_obj` is `True`, otherwise `None`.
        """
        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            param=param,
            **params,
        )

        response_data: dict[str, Any] = self._patch(
            url=url,
            data=patch.patch,
            additional_request_params=additional_request_params,
        )

        if return_obj is False:
            return None

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_object(response_data, model)

    def remove(
        self,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        param: str | int | UUID | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> None:
        """Remove a resource.

        Parameters
        ----------
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        param
            The parameter to identify the specific resource. This could be an
            ID or a unique identifier. The parameter will be appended to the
            endpoint to form the full URL for the GET request.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.
        """
        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            param=param,
            **params,
        )

        self._delete(
            url=url,
            additional_request_params=additional_request_params,
        )

    def update(
        self,
        obj: DomainModel,
        return_obj: bool = True,
        serialize: bool | None = None,
        use_factory: bool | None = None,
        endpoint: str | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        param: str | int | UUID | None = None,
        model: DomainModel | None = None,
        additional_request_params: dict[str, Any] | None = None,
        **params: Any,
    ) -> DomainModel | dict[str, Any] | None:
        """Update a resource.

        Parameters
        ----------
        obj
            The object to add.
        return_obj
            Whether to return the added object or not.
        serialize
            Whether to serialize the object before sending it in the API
            request.
        use_factory
            Whether to use the model factory method for creating models from
            response data.
        endpoint
            The API endpoint to which the object should be added.
        parent_endpoint
            The parent API endpoint, if the resource is nested under a parent
            resource.
        parent_param
            The parameter to identify the parent resource, if applicable. This
            could be an ID or a unique identifier. The parameter will be
            appended to the parent endpoint to form the full URL for the API
            request.
        param
            The parameter to identify the specific resource. This could be an
            ID or a unique identifier. The parameter will be appended to the
            endpoint to form the full URL for the GET request.
        model
            The model to use for serialization/deserialization.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        **params
            Additional query parameters to include in the API request.

        Returns
        -------
            The updated object if `return_obj` is `True`, otherwise `None`.
        """
        if self._determine_serialization(serialize):
            obj = self._serialize_object(obj)

        url = self._build_url(
            endpoint,
            parent_endpoint=parent_endpoint,
            parent_param=parent_param,
            param=param,
            **params,
        )

        response_data: dict[str, Any] = self._put(
            url=url,
            data=obj,
            additional_request_params=additional_request_params,
        )

        if return_obj is False:
            return None

        if not self._determine_use_factory(use_factory):
            return response_data

        return self._map_response_object(response_data, model)

    def _get(
        self,
        url: str,
        additional_request_params: dict[str, Any] | None = None,
    ) -> Any:
        """Call the GET method of the API.

        Parameters
        ----------
        url
            A fully constructed URL to which the GET request should be sent.
            This URL should include any necessary query parameters. The URL is
            expected to be properly formatted and ready for use in an API
            request.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.

        Returns
        -------
            The data retrieved from the API response.
        """
        response = self.client.get(
            url=url,
            **(additional_request_params or {}),
        )

        return self._handle_response(response)

    def _post(
        self,
        url: str,
        data: Any,
        additional_request_params: dict[str, Any] | None = None,
    ) -> Any:
        """Call the POST method of the API.

        Parameters
        ----------
        url
            A fully constructed URL to which the POST request should be sent.
            This URL should include any necessary query parameters. The URL is
            expected to be properly formatted and ready for use in an API
            request.
        data
            The data to be sent in the body of the POST request. This data is
            expected to be in a format that can be serialized to JSON, as it
            will be sent as JSON in the request body.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.

        Returns
        -------
            The data retrieved from the API response.
        """
        response = self.client.post(
            url=url,
            json=data,
            **(additional_request_params or {}),
        )

        return self._handle_response(response)

    def _patch(
        self,
        url: str,
        data: Any,
        additional_request_params: dict[str, Any] | None = None,
    ) -> Any:
        """Call the PATCH method of the API.

        Parameters
        ----------
        url
            A fully constructed URL to which the PATCH request should be sent.
            This URL should include any necessary query parameters. The URL is
            expected to be properly formatted and ready for use in an API
            request.
        data
            The data to be sent in the body of the PATCH request. This data is
            expected to be in a format that can be serialized to JSON, as it
            will be sent as JSON in the request body.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.

        Returns
        -------
            The data retrieved from the API response.
        """
        response = self.client.patch(
            url=url,
            json=data,
            **(additional_request_params or {}),
        )

        return self._handle_response(response)

    def _put(
        self,
        url: str,
        data: Any,
        additional_request_params: dict[str, Any] | None = None,
    ) -> Any:
        """Call the PUT method of the API.

        Parameters
        ----------
        url
            A fully constructed URL to which the PUT request should be sent.
            This URL should include any necessary query parameters. The URL is
            expected to be properly formatted and ready for use in an API
            request.
        data
            The data to be sent in the body of the PUT request. This data is
            expected to be in a format that can be serialized to JSON, as it
            will be sent as JSON in the request body.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.

        Returns
        -------
            The data retrieved from the API response.
        """
        response = self.client.put(
            url=url,
            json=data,
            **(additional_request_params or {}),
        )

        return self._handle_response(response)

    def _delete(
        self, url: str, additional_request_params: dict[str, Any] | None = None
    ) -> dict[str, Any] | None:
        """Call the DELETE method of the API.

        Parameters
        ----------
        url
            A fully constructed URL to which the DELETE request should be sent.
            This URL should include any necessary query parameters. The URL is
            expected to be properly formatted and ready for use in an API
            request.
        additional_request_params
            Additional parameters to include in the function call which handles
            the API request. This allows for flexibility in specifying
            parameters such as headers, authentication tokens, or other request
            options that may be needed for the API call.
        """
        response = self.client.delete(
            url=url,
            **(additional_request_params or {}),
        )

        return self._handle_response(response)

    def _map_response_object(self, response: Any, model: T | None) -> T:
        """Map a single object from the API response to a model instance.

        Parameters
        ----------
        response
            The API response containing the data to be mapped.
        model
            The model class to which the data should be mapped. If None, the
            default model for the repository will be used.

        Returns
        -------
            An instance of the model populated with the data from the API
            response.
        """
        model_to_use = self._determine_model(model)

        return getattr(model_to_use, self._model_factory_method_name)(response)

    def _map_response_array(
        self, response: list[Any], model: T | None
    ) -> list[T]:
        """Map an array of objects from the API response to model instances.

        Parameters
        ----------
        response
            The API response containing the data to be mapped.
        model
            The model class to which the data should be mapped. If None, the
            default model for the repository will be used.

        Returns
        -------
            A list of model instances populated with the data from the API
            response.
        """
        model_to_use = self._determine_model(model)

        return [
            getattr(model_to_use, self._model_factory_method_name)(item)
            for item in response
        ]

    def _build_url(
        self,
        endpoint: str | None = None,
        param: str | int | UUID | None = None,
        parent_endpoint: str | None = None,
        parent_param: str | int | UUID | None = None,
        **params: Any,
    ) -> str:
        """Build an URL to use for HTTP requests.

        The method constructs the URL based on the provided endpoint and
        parameter, as well as the base host, scheme, and base path configured
        for the repository. The endpoint and parameter are optional, allowing
        for flexible URL construction. The method ensures that the URL is
        properly formatted and can be used for making API requests.

        The method detects if the scheme is provided and constructs the URL
        accordingly. If a scheme is provided, it will be included in the URL.
        If not, the URL will be constructed without a scheme, allowing for
        relative URLs or URLs with a different scheme. If the scheme is already
        included in the host, it will not be replaced.

        An optional parent endpoint and parameter can be included in the URL,
        which is useful for nested resources. The parent parameter will be
        appended after the parent endpoint, and the main parameter will be
        appended after the main endpoint.

        Parameters
        ----------
        endpoint
            The endpoint to use for the URL, by default None
        param
            The parameter to append to the URL, by default None
        parent_endpoint
            An optional parent endpoint to include in the URL, by default None
        parent_param
            An optional parameter to append after the parent endpoint,
            by default None
        **params
            Additional parameters that can be used for query parameters.

        Returns
        -------
            The constructed URL as a string
        """
        if self._scheme and not self._host.__contains__("://"):
            url = f"{self._scheme}://{self._host}"
        else:
            url = self._host

        endpoint = endpoint or self._endpoint

        if self._base_path:
            url = urljoin(url, self._base_path.strip("/") + "/")

        if parent_endpoint:
            url = urljoin(url, parent_endpoint.lstrip("/"))

        if parent_param is not None:
            url = urljoin(url + "/", str(parent_param))

        if endpoint:
            url = urljoin(url + "/", endpoint.lstrip("/"))

        if param is not None:
            url = urljoin(url + "/", str(param))

        if params:
            url = url + "?" + urlencode(params, doseq=True)

        return url

    def _serialize_object(self, obj: Any) -> Any:
        """Serialize an object using the specified serialization method if it
        exists.

        Parameters
        ----------
        obj
            The object to be serialized.

        Returns
        -------
            The serialized object if the serialization method exists, otherwise
            the original object.
        """
        if hasattr(obj, self._model_serialization_method_name):
            return getattr(obj, self._model_serialization_method_name)()
        return obj

    def _get_data_from_response(
        self, response: Response
    ) -> dict[str, Any] | None:
        """Extract data from the API response. If the response_data_attribute
        is configured, it will return the value of that attribute. Otherwise,
        it will return the entire response data.

        Parameters
        ----------
        response
            The API response object.

        Returns
        -------
            The extracted data from the API response.
        """
        data: dict[str, Any] = response.json()
        if self._response_data_attribute:
            return data.get(self._response_data_attribute)
        return data

    def _determine_serialization(
        self,
        serialize: bool | None,
    ) -> bool:
        """Determine to use the serialize variable or self._serialize for
        deciding whether to serialize the object before sending it in the API
        request.

        Parameters
        ----------
        serialize
            Whether to serialize the object before sending it in the API
            request.

        Returns
        -------
            The value to use for deciding whether to serialize the object before
            sending it in the API request.
        """
        return serialize if serialize is not None else self._serialize

    def _determine_use_factory(
        self,
        use_factory: bool | None,
    ) -> bool:
        """Determine to use the use_factory variable or self._use_factory for
        deciding whether to use the model factory method for creating models.

        Parameters
        ----------
        use_factory
            Whether to use the model factory method for creating models from
            response data.

        Returns
        -------
            The value to use for deciding whether to use the model factory
            method for creating models from response data.
        """
        return use_factory if use_factory is not None else self._use_factory

    def _determine_model(self, model: T | None) -> T:
        """Determine the model to use for mapping response data.

        Parameters
        ----------
        model
            The model class to which the data should be mapped. If None, the
            default model for the repository will be used.

        Returns
        -------
             The model class to use for mapping response data.

        Raises
        ------
        ValueError
            If no model is provided and no default model is set for the
            repository.
        AttributeError
            If the determined model does not have the required factory method
            defined.
        """
        if not model and not self._default_model:
            raise ValueError(
                "No model provided for mapping response and no default model "
                "set for the repository."
            )

        model_to_use = cast(T, model or self._default_model)

        if not hasattr(model_to_use, self._model_factory_method_name):
            raise AttributeError(
                f"The model {model_to_use} does not have the factory method "
                f"'{self._model_factory_method_name}' defined. Please ensure "
                f"that the model has this method or set the correct "
                f"model_factory_method_name for the repository."
            )

        return model_to_use

    def _handle_response(self, response: Response) -> Any | None:
        """Handle the API response and extract the relevant data.

        In addition to extracting data from successful responses, this method
        also handles various HTTP error responses by raising appropriate
        exceptions based on the status code of the response. This ensures that
        the caller can handle different error scenarios in a structured way.

        Parameters
        ----------
        response
            The API response object to be processed.

        Returns
        -------
            The processed data extracted from the API response.

        Raises
        ------
        exceptions.BadRequestException
            If the API response indicates a bad request (HTTP status code 400).
        exceptions.UnauthorizedException
            If the API response indicates an unauthorized request (HTTP status
            code 401).
        exceptions.ForbiddenException
            If the API response indicates a forbidden request (HTTP status code
            403).
        exceptions.NotFoundException
            If the API response indicates that the requested resource was not
            found (HTTP status code 404).
        exceptions.MethodNotAllowedException
            If the API response indicates that the HTTP method is not allowed
            (HTTP status code 405).
        exceptions.NotAcceptableException
            If the API response indicates that the requested resource is not
            acceptable (HTTP status code 406).
        exceptions.ConflictException
            If the API response indicates a conflict with the current state of
            the resource (HTTP status code 409).
        exceptions.PayloadTooLargeException
            If the API response indicates that the request payload is too large
            (HTTP status code 413).
        exceptions.UnprocessableContentException
            If the API response indicates that the server cannot process the
            contained instructions (HTTP status code 422).
        exceptions.InternalServerErrorException
            If the API response indicates an internal server error (HTTP status
            code 500).
        exceptions.NotImplementedException
            If the API response indicates that the server does not support the
            functionality required to fulfill the request (HTTP status code
            501).
        exceptions.BadGatewayException
            If the API response indicates a bad gateway error (HTTP status code
            502).
        exceptions.ServiceUnavailableException
            If the API response indicates that the service is unavailable (HTTP
            status code 503).
        exceptions.GatewayTimeoutException
            If the API response indicates a gateway timeout error (HTTP status
            code 504).
        exceptions.ClientErrorException
            If the API response indicates a client error that is not
            specifically handled by the above exceptions.
        exceptions.ServerErrorException
            If the API response indicates a server error that is not
            specifically handled by the above exceptions.
        """
        match response.status_code:
            case 200 | 201 | 202:
                return self._get_data_from_response(response)
            case 204:
                return None
            case 400:
                raise exceptions.BadRequestException(
                    "Bad request: The server could not understand the request due "
                    "to invalid syntax."
                )
            case 401:
                raise exceptions.UnauthorizedException(
                    "Unauthorized: The client must authenticate itself to get the "
                    "requested response."
                )
            case 403:
                raise exceptions.ForbiddenException(
                    "Forbidden: The client does not have access rights to the "
                    "content."
                )
            case 404:
                raise exceptions.NotFoundException(
                    "Not Found: The server can not find the requested resource."
                )
            case 405:
                raise exceptions.MethodNotAllowedException(
                    "Method Not Allowed: The request method is known by the server "
                    "but is not supported by the target resource."
                )
            case 406:
                raise exceptions.NotAcceptableException(
                    "Not Acceptable: The server cannot produce a response matching "
                    "the list of acceptable values defined in the request's "
                    "proactive content negotiation headers."
                )
            case 409:
                raise exceptions.ConflictException(
                    "Conflict: The request could not be completed due to a conflict "
                    "with the current state of the target resource."
                )
            case 413:
                raise exceptions.PayloadTooLargeException(
                    "Payload Too Large: The request entity is larger than limits "
                    "defined by the server."
                )
            case 422:
                raise exceptions.UnprocessableContentException(
                    "Unprocessable Content: The server understands the content type "
                    "of the request entity, and the syntax of the request entity is "
                    "correct, but it was unable to process the contained instructions."
                )
            case 500:
                raise exceptions.InternalServerErrorException(
                    "Internal Server Error: The server has encountered a situation "
                    "it doesn't know how to handle."
                )
            case 501:
                raise exceptions.NotImplementedException(
                    "Not Implemented: The server does not support the functionality "
                    "required to fulfill the request."
                )
            case 502:
                raise exceptions.BadGatewayException(
                    "Bad Gateway: The server was acting as a gateway or proxy and "
                    "received an invalid response from the upstream server."
                )
            case 503:
                raise exceptions.ServiceUnavailableException(
                    "Service Unavailable: The server is not ready to handle the "
                    "request. Common causes are a server that is down for "
                    "maintenance or that is overloaded."
                )
            case 504:
                raise exceptions.GatewayTimeoutException(
                    "Gateway Timeout: The server was acting as a gateway or proxy and "
                    "did not receive a timely response from the upstream server."
                )
            case _:
                status_code = response.status_code
                if 300 <= status_code < 400:
                    # Unexpected redirect or other 3xx status not explicitly handled above.
                    raise exceptions.ClientErrorException(
                        f"Unexpected redirect or 3xx HTTP status code: {status_code}"
                    )
                if 400 <= status_code < 500:
                    # Generic client error for 4xx statuses not explicitly handled above.
                    raise exceptions.ClientErrorException(
                        f"An HTTP client error occurred (status code {status_code})."
                    )
                if 500 <= status_code < 600:
                    # Generic server error for 5xx statuses not explicitly handled above.
                    raise exceptions.ServerErrorException(
                        f"An HTTP server error occurred (status code {status_code})."
                    )
                # Any other unexpected status code (e.g., 1xx or outside normal ranges).
                raise exceptions.ClientErrorException(
                    f"Unexpected HTTP status code: {status_code}"
                )

Methods:

__init__

__init__(host, scheme=None, base_path='', endpoint='', default_model=None, use_factory=True, serialize=True, model_factory_method_name='from_dict', model_serialization_method_name='to_dict', client=None, session=None, request_headers=None, request_cookies=None, response_data_attribute=None)

Initialize the REST API repository.

Parameters:
  • host (str) –

    The base URL of the API.

  • scheme (str | None, default: None ) –

    The URL scheme to use (e.g., "http" or "https"). This is only used if the host does not already include a scheme, by default "https"

  • base_path (str, default: '' ) –

    The base path of the API, by default ""

  • endpoint (str, default: '' ) –

    The default endpoint for the API. This value is used when no specific endpoint is provided in the method calls, by default ""

  • default_model (DomainModel | None, default: None ) –

    The default model to use for serialization/deserialization, by default None

  • use_factory (bool, default: True ) –

    Whether to use the model factory method for creating models from response data, by default True

  • serialize (bool, default: True ) –

    Whether to serialize objects before sending them in requests, by default True

  • model_factory_method_name (str, default: 'from_dict' ) –

    The name of the class method to use for creating models from dictionaries, by default "from_dict"

  • model_serialization_method_name (str, default: 'to_dict' ) –

    The name of the method to use for serializing models to dictionaries, by default "to_dict"

  • client (HTTPClient | None, default: None ) –

    An HTTP client to use for context management, by default None. If None, a new requests.sessions.Session will be created and used. This allows for flexibility in using different HTTP client implementations that conform to the HTTPClient protocol, while still providing a default option with requests.

  • session (HTTPClient | None, default: None ) –

    Deprecated: An HTTP client session to use for making requests, by default None. Use client instead. This parameter is still supported for backward compatibility.

  • request_headers (dict[str, str] | None, default: None ) –

    Default headers to include in every request, by default None

  • request_cookies (dict[str, str] | None, default: None ) –

    Default cookies to include in every request, by default None

  • response_data_attribute (str | None, default: None ) –

    The attribute in the response data to extract the relevant data from, by default None

Source code in src/alpha/repositories/rest_api_repository.py
def __init__(
    self,
    host: str,
    scheme: str | None = None,
    base_path: str = "",
    endpoint: str = "",
    default_model: DomainModel | None = None,
    use_factory: bool = True,
    serialize: bool = True,
    model_factory_method_name: str = "from_dict",
    model_serialization_method_name: str = "to_dict",
    client: HTTPClient | None = None,
    session: HTTPClient | None = None,
    request_headers: dict[str, str] | None = None,
    request_cookies: dict[str, str] | None = None,
    response_data_attribute: str | None = None,
) -> None:
    """Initialize the REST API repository.

    Parameters
    ----------
    host
        The base URL of the API.
    scheme
        The URL scheme to use (e.g., "http" or "https"). This is only used
        if the host does not already include a scheme, by default "https"
    base_path
        The base path of the API, by default ""
    endpoint
        The default endpoint for the API. This value is used when no
        specific endpoint is provided in the method calls, by default ""
    default_model
        The default model to use for serialization/deserialization,
        by default None
    use_factory
        Whether to use the model factory method for creating models from
        response data, by default True
    serialize
        Whether to serialize objects before sending them in requests,
        by default True
    model_factory_method_name
        The name of the class method to use for creating models from
        dictionaries, by default "from_dict"
    model_serialization_method_name
        The name of the method to use for serializing models to
        dictionaries, by default "to_dict"
    client
        An HTTP client to use for context management, by default None.
        If None, a new `requests.sessions.Session` will be created and
        used. This allows for flexibility in using different HTTP client
        implementations that conform to the `HTTPClient` protocol, while
        still providing a default option with `requests`.
    session
        Deprecated: An HTTP client session to use for making requests, by
        default None. Use `client` instead. This parameter is still
        supported for backward compatibility.
    request_headers
        Default headers to include in every request, by default None
    request_cookies
        Default cookies to include in every request, by default None
    response_data_attribute
        The attribute in the response data to extract the relevant data
        from, by default None
    """
    self._host = host
    self._scheme = scheme or "https"
    self._base_path = base_path
    self._endpoint = endpoint
    self._default_model = default_model
    self._use_factory = use_factory
    self._serialize = serialize
    self._model_factory_method_name = model_factory_method_name
    self._model_serialization_method_name = model_serialization_method_name

    client_obj = client or session or requests.sessions.Session()
    # Expose the underlying client publicly for consistency with other
    # repositories
    self.client = client_obj
    # Preserve the deprecated public session alias for backward
    # compatibility
    self.session = client_obj
    # Preserve the existing private attribute for backward compatibility
    self._session = client_obj

    self._request_headers = request_headers or {}
    self._request_cookies = request_cookies or {}
    self._response_data_attribute = response_data_attribute
    # Update client with default headers and cookies
    self.client.headers.update(request_headers or {})
    cookiejar_from_dict(
        request_cookies or {},
        cookiejar=self.client.cookies,
        overwrite=True,
    )

add

add(obj, return_obj=True, serialize=None, use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, model=None, additional_request_params=None, **params)

Add a new resource.

Parameters:
  • obj (DomainModel) –

    The object to add.

  • return_obj (bool, default: True ) –

    Whether to return the added object or not.

  • serialize (bool | None, default: None ) –

    Whether to serialize the object before sending it in the API request.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • The added object if `return_obj` is `True`, otherwise `None`.
Source code in src/alpha/repositories/rest_api_repository.py
def add(
    self,
    obj: DomainModel,
    return_obj: bool = True,
    serialize: bool | None = None,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> DomainModel | dict[str, Any] | None:
    """Add a new resource.

    Parameters
    ----------
    obj
        The object to add.
    return_obj
        Whether to return the added object or not.
    serialize
        Whether to serialize the object before sending it in the API
        request.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        The added object if `return_obj` is `True`, otherwise `None`.
    """
    if self._determine_serialization(serialize):
        obj = self._serialize_object(obj)

    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        **params,
    )

    response_data = self._post(
        url=url,
        data=obj,
        additional_request_params=additional_request_params,
    )

    if return_obj is False:
        return None

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_object(response_data, model)

add_all

add_all(objs, return_objs=True, serialize=None, use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, model=None, additional_request_params=None, one_by_one=False, **params)

Add multiple new resources.

Parameters:
  • objs (list[DomainModel]) –

    The objects to add.

  • return_objs (bool, default: True ) –

    Whether to return the added objects or not.

  • serialize (bool | None, default: None ) –

    Whether to serialize the objects before sending it in the API request.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the objects should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • one_by_one (bool, default: False ) –

    Whether to add the objects one by one (i.e. make a separate API call for each object).

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • A list of added objects if `return_objs` is `True`, otherwise

    None.

Source code in src/alpha/repositories/rest_api_repository.py
def add_all(
    self,
    objs: list[DomainModel],
    return_objs: bool = True,
    serialize: bool | None = None,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    one_by_one: bool = False,
    **params: Any,
) -> list[DomainModel] | list[dict[str, Any]] | None:
    """Add multiple new resources.

    Parameters
    ----------
    objs
        The objects to add.
    return_objs
        Whether to return the added objects or not.
    serialize
        Whether to serialize the objects before sending it in the API
        request.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the objects should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    one_by_one
        Whether to add the objects one by one (i.e. make a separate API
        call for each object).
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        A list of added objects if `return_objs` is `True`, otherwise
        `None`.
    """
    if one_by_one:
        results: list[DomainModel] | list[dict[str, Any]] = []
        for obj in objs:
            result = self.add(
                obj=obj,
                return_obj=return_objs,
                serialize=serialize,
                use_factory=use_factory,
                endpoint=endpoint,
                parent_endpoint=parent_endpoint,
                parent_param=parent_param,
                model=model,
                additional_request_params=additional_request_params,
                **params,
            )
            if result is not None:
                results.append(result)  # type: ignore
        return results if return_objs else None

    if self._determine_serialization(serialize):
        objs = [self._serialize_object(obj) for obj in objs]

    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        **params,
    )

    response_data = self._post(
        url=url,
        data=objs,
        additional_request_params=additional_request_params,
    )

    if return_objs is False:
        return None

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_array(response_data, model)

get

get(use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, param=None, model=None, additional_request_params=None, **params)

Retrieve a single resource.

Parameters:
  • endpoint (str | None, default: None ) –

    The API endpoint from which to retrieve the resource.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • param (str | int | UUID | None, default: None ) –

    The parameter to identify the specific resource. This could be an ID or a unique identifier. The parameter will be appended to the endpoint to form the full URL for the GET request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • The retrieved object.
Source code in src/alpha/repositories/rest_api_repository.py
def get(
    self,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> DomainModel | dict[str, Any]:
    """Retrieve a single resource.

    Parameters
    ----------
    endpoint
        The API endpoint from which to retrieve the resource.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    param
        The parameter to identify the specific resource. This could be an
        ID or a unique identifier. The parameter will be appended to the
        endpoint to form the full URL for the GET request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        The retrieved object.
    """
    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        param=param,
        **params,
    )

    response_data: dict[str, Any] = self._get(
        url=url,
        additional_request_params=additional_request_params,
    )

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_object(response_data, model)

get_all

get_all(use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, param=None, model=None, additional_request_params=None, **params)

Retrieve multiple resources.

Parameters:
  • endpoint (str | None, default: None ) –

    The API endpoint from which to retrieve the resource.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • param (str | int | UUID | None, default: None ) –

    The parameter to identify the specific resource. This could be an ID or a unique identifier. The parameter will be appended to the endpoint to form the full URL for the GET request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • The retrieved objects.
Source code in src/alpha/repositories/rest_api_repository.py
def get_all(
    self,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> list[DomainModel] | list[dict[str, Any]]:
    """Retrieve multiple resources.

    Parameters
    ----------
    endpoint
        The API endpoint from which to retrieve the resource.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    param
        The parameter to identify the specific resource. This could be an
        ID or a unique identifier. The parameter will be appended to the
        endpoint to form the full URL for the GET request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        The retrieved objects.
    """
    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        param=param,
        **params,
    )

    response_data: list[dict[str, Any]] = self._get(
        url=url,
        additional_request_params=additional_request_params,
    )

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_array(response_data, model)

patch

patch(patch, return_obj=True, use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, param=None, model=None, additional_request_params=None, **params)

Update a resource.

Parameters:
  • patch (JsonPatch) –

    The JSON Patch object containing the changes to be applied to the resource. This object should conform to the JSON Patch specification.

  • return_obj (bool, default: True ) –

    Whether to return the updated object or not.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • param (str | int | UUID | None, default: None ) –

    The parameter to identify the specific resource. This could be an ID or a unique identifier. The parameter will be appended to the endpoint to form the full URL for the GET request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • The updated object if `return_obj` is `True`, otherwise `None`.
Source code in src/alpha/repositories/rest_api_repository.py
def patch(
    self,
    patch: JsonPatch,
    return_obj: bool = True,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> DomainModel | dict[str, Any] | None:
    """Update a resource.

    Parameters
    ----------
    patch
        The JSON Patch object containing the changes to be applied to the
        resource. This object should conform to the JSON Patch
        specification.
    return_obj
        Whether to return the updated object or not.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    param
        The parameter to identify the specific resource. This could be an
        ID or a unique identifier. The parameter will be appended to the
        endpoint to form the full URL for the GET request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        The updated object if `return_obj` is `True`, otherwise `None`.
    """
    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        param=param,
        **params,
    )

    response_data: dict[str, Any] = self._patch(
        url=url,
        data=patch.patch,
        additional_request_params=additional_request_params,
    )

    if return_obj is False:
        return None

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_object(response_data, model)

remove

remove(endpoint=None, parent_endpoint=None, parent_param=None, param=None, additional_request_params=None, **params)

Remove a resource.

Parameters:
  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • param (str | int | UUID | None, default: None ) –

    The parameter to identify the specific resource. This could be an ID or a unique identifier. The parameter will be appended to the endpoint to form the full URL for the GET request.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Source code in src/alpha/repositories/rest_api_repository.py
def remove(
    self,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    param: str | int | UUID | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> None:
    """Remove a resource.

    Parameters
    ----------
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    param
        The parameter to identify the specific resource. This could be an
        ID or a unique identifier. The parameter will be appended to the
        endpoint to form the full URL for the GET request.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.
    """
    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        param=param,
        **params,
    )

    self._delete(
        url=url,
        additional_request_params=additional_request_params,
    )

update

update(obj, return_obj=True, serialize=None, use_factory=None, endpoint=None, parent_endpoint=None, parent_param=None, param=None, model=None, additional_request_params=None, **params)

Update a resource.

Parameters:
  • obj (DomainModel) –

    The object to add.

  • return_obj (bool, default: True ) –

    Whether to return the added object or not.

  • serialize (bool | None, default: None ) –

    Whether to serialize the object before sending it in the API request.

  • use_factory (bool | None, default: None ) –

    Whether to use the model factory method for creating models from response data.

  • endpoint (str | None, default: None ) –

    The API endpoint to which the object should be added.

  • parent_endpoint (str | None, default: None ) –

    The parent API endpoint, if the resource is nested under a parent resource.

  • parent_param (str | int | UUID | None, default: None ) –

    The parameter to identify the parent resource, if applicable. This could be an ID or a unique identifier. The parameter will be appended to the parent endpoint to form the full URL for the API request.

  • param (str | int | UUID | None, default: None ) –

    The parameter to identify the specific resource. This could be an ID or a unique identifier. The parameter will be appended to the endpoint to form the full URL for the GET request.

  • model (DomainModel | None, default: None ) –

    The model to use for serialization/deserialization.

  • additional_request_params (dict[str, Any] | None, default: None ) –

    Additional parameters to include in the function call which handles the API request. This allows for flexibility in specifying parameters such as headers, authentication tokens, or other request options that may be needed for the API call.

  • **params (Any, default: {} ) –

    Additional query parameters to include in the API request.

Returns:
  • The updated object if `return_obj` is `True`, otherwise `None`.
Source code in src/alpha/repositories/rest_api_repository.py
def update(
    self,
    obj: DomainModel,
    return_obj: bool = True,
    serialize: bool | None = None,
    use_factory: bool | None = None,
    endpoint: str | None = None,
    parent_endpoint: str | None = None,
    parent_param: str | int | UUID | None = None,
    param: str | int | UUID | None = None,
    model: DomainModel | None = None,
    additional_request_params: dict[str, Any] | None = None,
    **params: Any,
) -> DomainModel | dict[str, Any] | None:
    """Update a resource.

    Parameters
    ----------
    obj
        The object to add.
    return_obj
        Whether to return the added object or not.
    serialize
        Whether to serialize the object before sending it in the API
        request.
    use_factory
        Whether to use the model factory method for creating models from
        response data.
    endpoint
        The API endpoint to which the object should be added.
    parent_endpoint
        The parent API endpoint, if the resource is nested under a parent
        resource.
    parent_param
        The parameter to identify the parent resource, if applicable. This
        could be an ID or a unique identifier. The parameter will be
        appended to the parent endpoint to form the full URL for the API
        request.
    param
        The parameter to identify the specific resource. This could be an
        ID or a unique identifier. The parameter will be appended to the
        endpoint to form the full URL for the GET request.
    model
        The model to use for serialization/deserialization.
    additional_request_params
        Additional parameters to include in the function call which handles
        the API request. This allows for flexibility in specifying
        parameters such as headers, authentication tokens, or other request
        options that may be needed for the API call.
    **params
        Additional query parameters to include in the API request.

    Returns
    -------
        The updated object if `return_obj` is `True`, otherwise `None`.
    """
    if self._determine_serialization(serialize):
        obj = self._serialize_object(obj)

    url = self._build_url(
        endpoint,
        parent_endpoint=parent_endpoint,
        parent_param=parent_param,
        param=param,
        **params,
    )

    response_data: dict[str, Any] = self._put(
        url=url,
        data=obj,
        additional_request_params=additional_request_params,
    )

    if return_obj is False:
        return None

    if not self._determine_use_factory(use_factory):
        return response_data

    return self._map_response_object(response_data, model)