Skip to content

oapi.client

SSLContext

SSLContext(check_hostname: bool = True)

Bases: ssl.SSLContext

This class is a wrapper for ssl.SSLContext which makes it possible to connect to hosts which have an unverified SSL certificate.

Source code in src/oapi/client.py
857
858
859
860
861
862
863
864
865
866
def __init__(
    self,
    check_hostname: bool = True,  # noqa: FBT001 FBT002
) -> None:
    if check_hostname:
        self.load_default_certs()
    else:
        self.check_hostname: bool = False
        self.verify_mode: ssl.VerifyMode = ssl.CERT_NONE
    super().__init__()

__reduce__

__reduce__() -> tuple

A pickled instance of this class will just be an entirely new instance.

Source code in src/oapi/client.py
868
869
870
871
872
873
def __reduce__(self) -> tuple:
    """
    A pickled instance of this class will just be an entirely new
    instance.
    """
    return SSLContext, (self.check_hostname,)

Client

Client(
    url: str | None = None,
    *,
    user: str | None = None,
    password: str | None = None,
    bearer_token: str | None = None,
    api_key: str | None = None,
    api_key_in: typing.Literal[
        "header", "query", "cookie"
    ] = "header",
    api_key_name: str = "X-API-KEY",
    oauth2_client_id: str | None = None,
    oauth2_client_secret: str | None = None,
    oauth2_username: str | None = None,
    oauth2_password: str | None = None,
    oauth2_authorization_url: str | None = None,
    oauth2_token_url: str | None = None,
    oauth2_scope: str | tuple[str, ...] | None = None,
    oauth2_refresh_url: str | None = None,
    oauth2_flows: (
        tuple[
            typing.Literal[
                "authorizationCode",
                "implicit",
                "password",
                "clientCredentials",
                "accessCode",
                "application",
            ],
            ...,
        ]
        | None
    ) = None,
    open_id_connect_url: str | None = None,
    headers: (
        collections.abc.Mapping[str, str]
        | collections.abc.Sequence[tuple[str, str]]
    ) = (
        ("Accept", "application/json"),
        ("Content-type", "application/json"),
    ),
    timeout: int = 0,
    retry_number_of_attempts: int = 1,
    retry_for_errors: tuple[
        type[Exception], ...
    ] = oapi.client.DEFAULT_RETRY_FOR_ERRORS,
    retry_hook: typing.Callable[
        [Exception], bool
    ] = oapi.client.default_retry_hook,
    verify_ssl_certificate: bool = True,
    logger: logging.Logger | None = None,
    echo: bool = False
)

A base class for OpenAPI clients.

Parameters:

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

    The base URL for API requests.

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

    A user name for use with HTTP basic authentication.

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

    A password for use with HTTP basic authentication.

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

    A token for use with HTTP bearer authentication.

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

    An API key with which to authenticate requests.

  • api_key_in (typing.Literal['header', 'query', 'cookie'], default: 'header' ) –

    Where the API key should be conveyed: "header", "query" or "cookie".

  • api_key_name (str, default: 'X-API-KEY' ) –

    The name of the header, query parameter, or cookie parameter in which to convey the API key.

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

    An OAuth2 client ID.

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

    An OAuth2 client secret.

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

    A username for the "password" OAuth2 grant type.

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

    A password for the "password" OAuth2 grant type.

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

    The authorization URL to use for an OAuth2 flow. Can be relative to url.

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

    The token URL to use for OAuth2 authentication. Can be relative to url.

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

    The URL to be used for obtaining refresh tokens for OAuth2 authentication.

  • oauth2_flows (tuple[typing.Literal['authorizationCode', 'implicit', 'password', 'clientCredentials', 'accessCode', 'application'], ...] | None, default: None ) –

    A tuple containing one or more of the following: "authorizationCode", "implicit", "password" and/or "clientCredentials".

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

    An OpenID connect URL where a JSON web token containing OAuth2 information can be found.

  • headers (collections.abc.Mapping[str, str] | collections.abc.Sequence[tuple[str, str]], default: (('Accept', 'application/json'), ('Content-type', 'application/json')) ) –

    Default headers to include with all requests. Method-specific header arguments will override or modify these, where applicable, as will dynamically modified headers such as content-length, authorization, cookie, etc.

  • timeout (int, default: 0 ) –

    The number of seconds before a request will timeout and throw an error. If this is 0 (the default), the system default timeout will be used.

  • retry_number_of_attempts (int, default: 1 ) –

    The number of times to retry a request which results in an error.

  • retry_for_errors (tuple[type[Exception], ...], default: oapi.client.DEFAULT_RETRY_FOR_ERRORS ) –

    A tuple of one or more exception types on which to retry a request. To retry for all errors, pass (Exception,) for this argument.

  • retry_hook (typing.Callable[[Exception], bool], default: oapi.client.default_retry_hook ) –

    A function, accepting one argument (an Exception), and returning a boolean value indicating whether to retry the request (if retries have not been exhausted). This hook applies only for exceptions which are a sub-class of an exception included in retry_for_errors.

  • verify_ssl_certificate (bool, default: True ) –

    If True, SSL certificates are verified, per usual. If False, SSL certificates are not verified.

  • logger (logging.Logger | None, default: None ) –

    A logging.Logger to which requests should be logged.

  • echo (bool, default: False ) –

    If True, requests/responses are printed as they occur.

Source code in src/oapi/client.py
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
def __init__(
    self,
    url: str | None = None,
    *,
    user: str | None = None,
    password: str | None = None,
    bearer_token: str | None = None,
    api_key: str | None = None,
    api_key_in: typing.Literal["header", "query", "cookie"] = "header",
    api_key_name: str = "X-API-KEY",
    oauth2_client_id: str | None = None,
    oauth2_client_secret: str | None = None,
    oauth2_username: str | None = None,
    oauth2_password: str | None = None,
    oauth2_authorization_url: str | None = None,
    oauth2_token_url: str | None = None,
    oauth2_scope: str | tuple[str, ...] | None = None,
    oauth2_refresh_url: str | None = None,
    oauth2_flows: tuple[
        typing.Literal[
            "authorizationCode",
            "implicit",
            "password",
            "clientCredentials",
            # OpenAPI 2.x Compatibility:
            "accessCode",
            "application",
        ],
        ...,
    ]
    | None = None,
    open_id_connect_url: str | None = None,
    headers: collections.abc.Mapping[str, str]
    | collections.abc.Sequence[tuple[str, str]] = (
        ("Accept", "application/json"),
        ("Content-type", "application/json"),
    ),
    timeout: int = 0,
    retry_number_of_attempts: int = 1,
    retry_for_errors: tuple[
        type[Exception], ...
    ] = DEFAULT_RETRY_FOR_ERRORS,
    retry_hook: typing.Callable[  # Force line-break retention
        [Exception], bool
    ] = default_retry_hook,
    verify_ssl_certificate: bool = True,
    logger: Logger | None = None,
    echo: bool = False,
) -> None:
    """
    Parameters:
        url: The base URL for API requests.
        user: A user name for use with HTTP basic authentication.
        password:  A password for use with HTTP basic authentication.
        bearer_token: A token for use with HTTP bearer authentication.
        api_key: An API key with which to authenticate requests.
        api_key_in: Where the API key should be conveyed:
            "header", "query" or "cookie".
        api_key_name: The name of the header, query parameter, or
            cookie parameter in which to convey the API key.
        oauth2_client_id: An OAuth2 client ID.
        oauth2_client_secret: An OAuth2 client secret.
        oauth2_username: A *username* for the "password" OAuth2 grant
            type.
        oauth2_password: A *password* for the "password" OAuth2 grant
            type.
        oauth2_authorization_url: The authorization URL to use for an
            OAuth2 flow. Can be relative to `url`.
        oauth2_token_url: The token URL to use for OAuth2
            authentication. Can be relative to `url`.
        oauth2_refresh_url: The URL to be used for obtaining refresh
            tokens for OAuth2 authentication.
        oauth2_flows: A tuple containing one or more of the
            following: "authorizationCode", "implicit", "password" and/or
            "clientCredentials".
        open_id_connect_url: An OpenID connect URL where a JSON
            web token containing OAuth2 information can be found.
        headers: Default headers to include with all requests.
            Method-specific header arguments will override or modify these,
            where applicable, as will dynamically modified headers such as
            content-length, authorization, cookie, etc.
        timeout: The number of seconds before a request will timeout
            and throw an error. If this is 0 (the default), the system
            default timeout will be used.
        retry_number_of_attempts: The number of times to retry
            a request which results in an error.
        retry_for_errors: A tuple of one or more exception types
            on which to retry a request. To retry for *all* errors,
            pass `(Exception,)` for this argument.
        retry_hook: A function, accepting one argument (an Exception),
            and returning a boolean value indicating whether to retry the
            request (if retries have not been exhausted). This hook applies
            *only* for exceptions which are a sub-class of an exception
            included in `retry_for_errors`.
        verify_ssl_certificate: If `True`, SSL certificates
            are verified, per usual. If `False`, SSL certificates are *not*
            verified.
        logger:
            A `logging.Logger` to which requests should be logged.
        echo: If `True`, requests/responses are printed as
            they occur.
    """
    message: str
    # Ensure the API key location is valid
    if api_key_in not in ("header", "query", "cookie"):
        message = (
            f"Invalid input for `api_key_in`:  {api_key_in!r}\n"
            'Valid values are "header", "query" or "cookie".'
        )
        raise ValueError(message)
    # Translate OpenAPI 2x OAuth2 flow names
    if oauth2_flows:
        flow: str
        oauth2_flows = tuple(
            (
                "authorizationCode"
                if flow == "accessCode"
                else "clientCredentials"
                if flow == "application"
                else flow
            )
            for flow in oauth2_flows
        )
    # Ensure OAuth2 flows are valid
    if oauth2_flows and not all(
        flow
        in {
            "authorizationCode",
            "implicit",
            "password",
            "clientCredentials",
        }
        for flow in oauth2_flows
    ):
        message = (
            f"Invalid value(s) for `oauth2_flows`:  {api_key_in!r}\n"
            'Valid values are "authorizationCode", "implicit", '
            '"password", or "clientCredentials".'
        )
        raise ValueError(message)
    # Ensure URLs are HTTP/HTTPS (security concern) *or* are relative URLs
    url_: str | None
    for url_ in (
        url,
        oauth2_authorization_url,
        oauth2_token_url,
        oauth2_refresh_url,
        open_id_connect_url,
    ):
        if url_ and (
            url_.lower().rpartition(":")[0] not in ("http", "https", "")
        ):
            raise ValueError(url_)
    # Set properties
    self.url: str | None = url
    self.user: str | None = user
    self.password: str | None = password
    self.bearer_token: str | None = bearer_token
    self.api_key: str | None = api_key
    self.api_key_in: typing.Literal["header", "query", "cookie"] = (
        api_key_in
    )
    self.api_key_name: str = api_key_name
    self.oauth2_client_id: str | None = oauth2_client_id
    self.oauth2_client_secret: str | None = oauth2_client_secret
    self.oauth2_username: str | None = oauth2_username
    self.oauth2_password: str | None = oauth2_password
    self.oauth2_authorization_url: str | None = oauth2_authorization_url
    self.oauth2_token_url: str | None = oauth2_token_url
    self.oauth2_scope: str | tuple[str, ...] | None = oauth2_scope
    self.oauth2_refresh_url: str | None = oauth2_refresh_url
    self.oauth2_flows: (
        typing.Literal[
            "authorizationCode",
            "implicit",
            "password",
            "clientCredentials",
        ]
        | None
    ) = oauth2_flows  # type: ignore
    self.open_id_connect_url: str | None = open_id_connect_url
    self.headers: dict[str, str] = dict(headers)
    self.timeout: int = timeout
    self.retry_number_of_attempts: int = retry_number_of_attempts
    self.retry_for_errors: tuple[type[Exception], ...] = retry_for_errors
    self.retry_hook: typing.Callable[[Exception], bool] = retry_hook
    self.verify_ssl_certificate: bool = verify_ssl_certificate
    self.logger: Logger | None = logger
    self.echo: bool = echo
    # Support for persisting cookies
    self._cookie_jar: CookieJar = CookieJar()
    self.__opener: OpenerDirector | None = None
    self._oauth2_authorization_expires: int = 0

request

request(
    path: str,
    method: str,
    *,
    json: str | bytes | sob.abc.Model | None = None,
    data: (
        collections.abc.Mapping[
            str, sob.abc.MarshallableTypes
        ]
        | collections.abc.Sequence[
            tuple[str, sob.abc.MarshallableTypes]
        ]
    ) = (),
    query: (
        collections.abc.Mapping[
            str, sob.abc.MarshallableTypes
        ]
        | collections.abc.Sequence[
            tuple[str, sob.abc.MarshallableTypes]
        ]
        | str
    ) = (),
    headers: (
        collections.abc.Mapping[
            str, sob.abc.MarshallableTypes
        ]
        | collections.abc.Sequence[
            tuple[str, sob.abc.MarshallableTypes]
        ]
    ) = (),
    multipart: bool = False,
    multipart_data_headers: (
        collections.abc.Mapping[
            str, collections.abc.MutableMapping[str, str]
        ]
        | collections.abc.Sequence[
            tuple[
                str,
                collections.abc.MutableMapping[str, str],
            ]
        ]
    ) = (),
    timeout: int = 0
) -> sob.abc.Readable

Construct and submit an HTTP request and return the response (an instance of http.client.HTTPResponse).

Parameters:

  • path (str) –

    This is the path of the request, relative to the server base URL

  • query (collections.abc.Mapping[str, sob.abc.MarshallableTypes] | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]] | str, default: () ) –
  • json (str | bytes | sob.abc.Model | None, default: None ) –

    JSON data to be conveyed in the body of the request

  • data (collections.abc.Mapping[str, sob.abc.MarshallableTypes] | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]], default: () ) –

    Form data to be conveyed in the body of the request

  • multipart (bool, default: False ) –

    If True, data should be conveyed as a multipart request.

  • query (collections.abc.Mapping[str, sob.abc.MarshallableTypes] | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]] | str, default: () ) –

    A dictionary from which to assemble the query string.

  • headers (collections.abc.Mapping[str, sob.abc.MarshallableTypes] | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]], default: () ) –
  • multipart_data_headers (collections.abc.Mapping[str, collections.abc.MutableMapping[str, str]] | collections.abc.Sequence[tuple[str, collections.abc.MutableMapping[str, str]]], default: () ) –
  • timeout (int, default: 0 ) –
Source code in src/oapi/client.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
def request(
    self,
    path: str,
    method: str,
    *,
    json: str | bytes | sob.abc.Model | None = None,
    data: collections.abc.Mapping[str, sob.abc.MarshallableTypes]
    | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]] = (),
    query: collections.abc.Mapping[str, sob.abc.MarshallableTypes]
    | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]]
    | str = (),
    headers: collections.abc.Mapping[str, sob.abc.MarshallableTypes]
    | collections.abc.Sequence[tuple[str, sob.abc.MarshallableTypes]] = (),
    multipart: bool = False,
    multipart_data_headers: collections.abc.Mapping[
        str, collections.abc.MutableMapping[str, str]
    ]
    | collections.abc.Sequence[
        tuple[str, collections.abc.MutableMapping[str, str]]
    ] = (),
    timeout: int = 0,
) -> sob.abc.Readable:
    """
    Construct and submit an HTTP request and return the response
    (an instance of `http.client.HTTPResponse`).

    Parameters:
        path: This is the path of the request, relative to the server
            base URL
        query:
        json: JSON data to be conveyed in the body of the request
        data: Form data to be conveyed
            in the body of the request
        multipart: If `True`, `data` should be conveyed
            as a multipart request.
        query: A dictionary from which to assemble the
            query string.
        headers:
        multipart_data_headers:
        timeout:
    """
    # For backwards compatibility...
    if isinstance(data, (str, bytes, sob.abc.Model)) or (data is None):
        json = data
        data = ()
    request: typing.Callable[
        [
            str,
            str,
            str | bytes | sob.abc.Model | None,
            collections.abc.Mapping[str, sob.abc.MarshallableTypes]
            | collections.abc.Sequence[
                tuple[str, sob.abc.MarshallableTypes]
            ],
            collections.abc.Mapping[str, sob.abc.MarshallableTypes]
            | collections.abc.Sequence[
                tuple[str, sob.abc.MarshallableTypes]
            ]
            | str,
            collections.abc.Mapping[str, sob.abc.MarshallableTypes]
            | collections.abc.Sequence[
                tuple[str, sob.abc.MarshallableTypes]
            ],
            bool,
            collections.abc.Mapping[
                str, collections.abc.MutableMapping[str, str]
            ]
            | collections.abc.Sequence[
                tuple[str, collections.abc.MutableMapping[str, str]]
            ],
            int,
        ],
        sob.abc.Readable,
    ] = self._request
    # Wrap the _request method with a retry decorator if more
    # than one attempt is specified in the config
    if self.retry_number_of_attempts > 1:
        request = retry(
            errors=self.retry_for_errors,
            number_of_attempts=self.retry_number_of_attempts,
            retry_hook=self.retry_hook,
            logger=self.logger,
        )(self._request)
    return request(
        path,
        method,
        json,
        data,
        query,
        headers,
        multipart,
        multipart_data_headers,
        timeout,
    )

ClientModule

ClientModule(
    open_api: (
        str | sob.abc.Readable | oapi.oas.model.OpenAPI
    ),
    model_path: str | pathlib.Path,
    *,
    class_name: str = "Client",
    base_class: type[
        oapi.client.Client
    ] = oapi.client.Client,
    imports: str | tuple[str, ...] = (),
    init_decorator: str = "",
    include_init_parameters: str | tuple[str, ...] = (),
    add_init_parameters: str | tuple[str, ...] = (),
    add_init_parameter_docs: str | tuple[str, ...] = (),
    init_parameter_defaults: (
        collections.abc.Mapping[str, typing.Any]
        | collections.abc.Sequence[tuple[str, typing.Any]]
    ) = (),
    init_parameter_defaults_source: (
        collections.abc.Mapping[str, typing.Any]
        | collections.abc.Sequence[tuple[str, typing.Any]]
    ) = (),
    get_method_name_from_path_method_operation: typing.Callable[
        [str, str, str | None], str
    ] = oapi.client.get_default_method_name_from_path_method_operation,
    use_operation_id: bool = False
)

This class parses an Open API document and outputs a module defining a client class for interfacing with the API described by an OpenAPI document.

Parameters:

  • open_api (str | sob.abc.Readable | oapi.oas.model.OpenAPI) –

    An OpenAPI document. This can be a URL, file-path, an HTTP response (http.client.HTTPResponse), a file object, or an instance of oapi.oas.model.OpenAPI.

  • model_path (str | pathlib.Path) –

    The file path where the data model for this client can be found. This must be a model generated using oapi.model, and must be part of the same project that this client will be saved into.

  • class_name (str, default: 'Client' ) –
  • base_class (type[oapi.client.Client], default: oapi.client.Client ) –

    The base class to use for the client. If provided, this must be a sub-class of oapi.client.Client.

  • imports (str | tuple[str, ...], default: () ) –

    One or more import statements to include (in addition to those generated automatically).

  • init_decorator (str, default: '' ) –

    A decorator to apply to the client class .__init__ method. If used, make sure to include any modules referenced in your imports. For example: "@decorator_function(argument_a=1, argument_b=2)".

  • include_init_parameters (str | tuple[str, ...], default: () ) –

    The name of all parameters to include for the client's .__init__ method.

  • add_init_parameters (str | tuple[str, ...], default: () ) –

    Additional parameter declarations to add to the client's .__init__ method. These should include a type hint and default value (not just the parameter name). For example: 'additional_parameter_name: str | None = None'. Note: additional parameters will not do anything without the use of a decorator which utilizes the additional parameters, so use of this parameter should be accompanied by an init_decorator.

  • add_init_parameter_docs (str | tuple[str, ...], default: () ) –
  • init_parameter_defaults (collections.abc.Mapping[str, typing.Any] | collections.abc.Sequence[tuple[str, typing.Any]], default: () ) –

    A mapping of parameter names to default values for the parameter.

  • init_parameter_defaults_source (collections.abc.Mapping[str, typing.Any] | collections.abc.Sequence[tuple[str, typing.Any]], default: () ) –

    A mapping of parameter names to default values for the parameter expressed as source code. This is to allow for the passing of imported constants, expressions, etc.

Source code in src/oapi/client.py
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
def __init__(
    self,
    open_api: str | sob.abc.Readable | OpenAPI,
    model_path: str | Path,
    *,
    class_name: str = "Client",
    base_class: type[Client] = Client,
    imports: str | tuple[str, ...] = (),
    init_decorator: str = "",
    include_init_parameters: str | tuple[str, ...] = (),
    add_init_parameters: str | tuple[str, ...] = (),
    add_init_parameter_docs: str | tuple[str, ...] = (),
    init_parameter_defaults: collections.abc.Mapping[str, typing.Any]
    | collections.abc.Sequence[tuple[str, typing.Any]] = (),
    init_parameter_defaults_source: collections.abc.Mapping[
        str, typing.Any
    ]
    | collections.abc.Sequence[tuple[str, typing.Any]] = (),
    get_method_name_from_path_method_operation: typing.Callable[
        [str, str, str | None], str
    ] = get_default_method_name_from_path_method_operation,
    use_operation_id: bool = False,
) -> None:
    """
    Parameters:
        open_api: An OpenAPI document. This can be a URL, file-path, an
            HTTP response (`http.client.HTTPResponse`), a file object, or
            an instance of `oapi.oas.model.OpenAPI`.
        model_path: The file path where the data model for this
            client can be found. This must be a model generated using
            `oapi.model`, and must be part of the same project that this
            client will be saved into.
        class_name:
        base_class: The base class to use for the client. If provided,
            this must be a sub-class of `oapi.client.Client`.
        imports: One or more import statements to include
            (in addition to those generated automatically).
        init_decorator:  A decorator to apply to the client class
            `.__init__` method. If used, make sure to include any modules
            referenced in your `imports`. For example:
            "@decorator_function(argument_a=1, argument_b=2)".
        include_init_parameters: The name of all parameters to
            include for the client's `.__init__` method.
        add_init_parameters: Additional parameter
            declarations to add to the client's `.__init__` method.
            These should include a type hint and default value (not just
            the parameter name). For example:
            'additional_parameter_name: str | None = None'. Note:
            additional parameters will not do anything without the use of a
            decorator which utilizes the additional parameters, so use of
            this parameter should be accompanied by an `init_decorator`.
        add_init_parameter_docs:
        init_parameter_defaults: A mapping of
            parameter names to default values for the parameter.
        init_parameter_defaults_source: A mapping of
            parameter names to default values for the parameter *expressed
            as source code*. This is to allow for the passing of imported
            constants, expressions, etc.
    """
    message: str
    if isinstance(model_path, Path):
        model_path = str(model_path)
    # Ensure a valid model path has been provided
    if not os.path.exists(model_path):
        raise ValueError(model_path)
    # Get an OpenAPI document
    if isinstance(open_api, str):
        if os.path.exists(open_api):
            open_api = _get_path_open_api(open_api)
        else:
            open_api = _get_url_open_api(open_api)
    elif isinstance(open_api, sob.abc.Readable):
        open_api = _get_io_open_api(open_api)
    elif not isinstance(open_api, OpenAPI):
        message = (
            f"`{sob.utilities.get_calling_function_qualified_name()}` "
            "requires an instance of `str`, "
            f"`{sob.utilities.get_qualified_name(OpenAPI)}`, or a "
            "file-like object for the `open_api` parameter--not "
            f"{open_api!r}"
        )
        raise TypeError(message)
    # Ensure all elements have URLs and JSON pointers
    sob.set_model_url(open_api, sob.get_model_url(open_api))
    sob.set_model_pointer(open_api, sob.get_model_pointer(open_api) or "")
    self.open_api: OpenAPI = open_api
    init_decorator = init_decorator.strip()
    if init_decorator and not init_decorator.startswith("@"):
        raise ValueError(init_decorator)
    self._init_decorator: str = init_decorator.strip()
    self._include_init_parameters: tuple[str, ...] = (
        (include_init_parameters,)
        if isinstance(include_init_parameters, str)
        else include_init_parameters
    )
    self._add_init_parameters: tuple[str, ...] = (
        (add_init_parameters,)
        if isinstance(add_init_parameters, str)
        else add_init_parameters
    )
    self._add_init_parameter_docs: tuple[str, ...] = (
        (add_init_parameter_docs,)
        if isinstance(add_init_parameter_docs, str)
        else add_init_parameter_docs
    )
    self._init_parameter_defaults: dict[str, typing.Any] = dict(
        init_parameter_defaults
    )
    self._init_parameter_defaults_source: dict[str, typing.Any] = dict(
        init_parameter_defaults_source
    )
    self._resolver: Resolver = Resolver(open_api)
    self._model_path: str = model_path
    self._base_class: type[Client] = base_class
    self._class_name: str = class_name
    # This keeps track of used names in the global namespace
    self._names: set[str] = {
        "sob",
        "oapi",
        "typing",
        "Logger",
        self._class_name,
    }
    self._imports: set[str] = {
        "from __future__ import annotations",
        "import typing",
        "import oapi",
        "import sob",
        "from logging import Logger",
    } | set(
        filter(None, (imports,) if isinstance(imports, str) else imports)
    )
    if "headers" not in self._iter_excluded_parameter_names():
        # `collections.abc` is only referenced if `headers` is used
        self._imports.add("import collections.abc")
        self._names.add("collections")
    self.get_method_name_from_path_method_operation = (
        get_method_name_from_path_method_operation
    )
    self.use_operation_id = use_operation_id

get_source

get_source(path: str | pathlib.Path) -> str

This generates source code for the client module.

Parameters:

  • path (str | pathlib.Path) –

    The file path for the client module. This is needed in order to determine the relative import for the model module.

Source code in src/oapi/client.py
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
def get_source(self, path: str | Path) -> str:
    """
    This generates source code for the client module.

    Parameters:
        path: The file path for the client module. This is needed
            in order to determine the relative import for the model module.
    """
    source: str = "\n".join(
        chain(
            self._iter_class_declaration_source(),
            self._iter_init_method_source(),
            self._iter_paths_operations_methods_source(),
            ("",),
        )
    )
    # The model module import couldn't be generated until we
    # knew the client module path, so we add it now
    self._imports |= {
        self._get_model_module_import(path),
        self._get_client_base_class_import(path),
    }
    # Imports need to be generated last
    imports: str = "\n".join(self._iter_imports())
    return sob.utilities.suffix_long_lines(
        f"{imports}\n\n\n{source.rstrip()}\n"
    )

save

save(path: str | pathlib.Path) -> None

This method will save the generated module to a given path.

Source code in src/oapi/client.py
3748
3749
3750
3751
3752
3753
3754
3755
def save(self, path: str | Path) -> None:
    """
    This method will save the generated module to a given path.
    """
    client_source: str = self.get_source(path=path)
    # Save the module
    with open(path, "w") as model_io:
        model_io.write(client_source)

urlencode

urlencode(
    query: (
        collections.abc.Mapping[str, typing.Any]
        | sob.abc.Dictionary
        | sob.abc.Object
        | collections.abc.Sequence[tuple[str, typing.Any]]
    ),
    doseq: bool = True,
    safe: str = oapi.client.URLENCODE_SAFE,
    encoding: str = "utf-8",
    errors: str = "",
    quote_via: typing.Callable[
        [str, bytes | str, str, str], str
    ] = urllib.parse.quote,
) -> str

This function wraps urllib.parse.urlencode, but has different default argument values. Additionally, when a mapping/dictionary is passed for a query value, that dictionary/mapping performs an update to the query dictionary.

Parameters:

  • query (collections.abc.Mapping[str, typing.Any] | sob.abc.Dictionary | sob.abc.Object | collections.abc.Sequence[tuple[str, typing.Any]]) –
  • doseq (bool, default: True ) –
  • safe (str, default: oapi.client.URLENCODE_SAFE ) –
  • encoding (str, default: 'utf-8' ) –
  • errors (str, default: '' ) –
  • quote_via (typing.Callable[[str, bytes | str, str, str], str], default: urllib.parse.quote ) –
Source code in src/oapi/client.py
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
def urlencode(
    query: collections.abc.Mapping[str, typing.Any]
    | sob.abc.Dictionary
    | sob.abc.Object
    | collections.abc.Sequence[tuple[str, typing.Any]],
    doseq: bool = True,  # noqa: FBT001 FBT002
    safe: str = URLENCODE_SAFE,
    encoding: str = "utf-8",
    errors: str = "",
    quote_via: typing.Callable[[str, bytes | str, str, str], str] = quote,
) -> str:
    """
    This function wraps `urllib.parse.urlencode`, but has different default
    argument values. Additionally, when a mapping/dictionary is passed for a
    query value, that dictionary/mapping performs an update to the query
    dictionary.

    Parameters:
        query:
        doseq:
        safe:
        encoding:
        errors:
        quote_via:
    """
    items: list[tuple[str, typing.Any]] = []
    key: str
    value: typing.Any
    for key, value in _iter_items(query):
        if isinstance(value, _ITEMIZED_TYPES):
            # The only dictionaries/objects which should exist
            # for values which have been formatted are
            # intended to be bumped up into the top-level
            items.extend(_iter_items(value))
        else:
            items.append((key, value))
    return _urlencode(
        query=items,
        doseq=doseq,
        safe=safe,
        encoding=encoding,
        errors=errors,
        quote_via=quote_via,
    )

format_argument_value

format_argument_value(
    name: str,
    value: sob.abc.MarshallableTypes | typing.IO[bytes],
    style: str,
    *,
    explode: bool = False,
    multipart: bool = False
) -> (
    str
    | dict[str, str]
    | dict[str, str | list[str]]
    | collections.abc.Sequence[str]
    | collections.abc.Sequence[bytes]
    | bytes
    | collections.abc.Sequence[typing.IO[bytes]]
    | typing.IO[bytes]
    | None
)

Format an argument value for use in a path, query, cookie, header, etc.

Parameters:

  • value (sob.abc.MarshallableTypes | typing.IO[bytes]) –
  • style (str) –
  • explode (bool, default: False ) –
  • multipart (bool, default: False ) –

    Indicates the argument will be part of a multipart request

See: https://swagger.io/docs/specification/serialization/

Source code in src/oapi/client.py
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
def format_argument_value(  # noqa: C901
    name: str,
    value: sob.abc.MarshallableTypes | typing.IO[bytes],
    style: str,
    *,
    explode: bool = False,
    multipart: bool = False,
) -> (
    str
    | dict[str, str]
    | dict[str, str | list[str]]
    | collections.abc.Sequence[str]
    | collections.abc.Sequence[bytes]
    | bytes
    | collections.abc.Sequence[typing.IO[bytes]]
    | typing.IO[bytes]
    | None
):
    """
    Format an argument value for use in a path, query, cookie, header, etc.

    Parameters:
        value:
        style:
        explode:
        multipart: Indicates the argument will be part of a
            multipart request

    See: https://swagger.io/docs/specification/serialization/
    """
    if multipart and (
        isinstance(value, (bytes, sob.abc.Readable))
        or (
            value
            and (not isinstance(value, str))
            and isinstance(value, collections.abc.Sequence)
            and isinstance(value[0], (bytes, sob.abc.Readable))
        )
    ):
        # For multipart requests, we don't apply any formatting to `bytes`
        # objects, as they will be sent in binary format
        return value
    if isinstance(value, sob.abc.Model):
        value = sob.marshal(value)  # type: ignore
    if style == "simple":
        return _format_simple_argument_value(value, explode=explode)
    if style == "label":
        return _format_label_argument_value(value, explode=explode)
    if style == "matrix":
        return _format_matrix_argument_value(name, value, explode=explode)
    if style == "form":
        return _format_form_argument_value(value, explode=explode)
    if style == "spaceDelimited":
        return _format_space_delimited_argument_value(value, explode=explode)
    if style == "pipeDelimited":
        return _format_pipe_delimited_argument_value(value, explode=explode)
    if style == "deepObject":
        return _format_deep_object_argument_value(name, value, explode=explode)
    if style == "dotObject":
        return _format_dot_object_argument_value(name, value, explode=explode)
    raise ValueError(style)

get_request_curl

get_request_curl(
    request: urllib.request.Request,
    options: str = "-i",
    censored_headers: collections.abc.Iterable[str] = (
        "X-api-key",
        "Authorization",
    ),
    censored_parameters: tuple[str, ...] = (
        "client_secret",
    ),
) -> str

Render an instance of urllib.request.Request as a curl command.

Parameters:

  • options (str, default: '-i' ) –

    Any additional parameters to pass to curl, (such as "--compressed", "--insecure", etc.)

Source code in src/oapi/client.py
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
def get_request_curl(
    request: Request,
    options: str = "-i",
    censored_headers: collections.abc.Iterable[str] = (
        "X-api-key",
        "Authorization",
    ),
    censored_parameters: tuple[str, ...] = ("client_secret",),
) -> str:
    """
    Render an instance of `urllib.request.Request` as a `curl` command.

    Parameters:
        options: Any additional parameters to pass to `curl`,
            (such as "--compressed", "--insecure", etc.)
    """
    is_json: bool = bool(
        request.headers.get("Content-Type", "").lower() == "application/json"
    )
    censored_headers = tuple(map(str.lower, censored_headers))

    def _get_request_curl_header_item(item: tuple[str, str]) -> str:
        key: str
        value: str
        key, value = item
        if key.lower() in censored_headers:
            value = "***"
        return "-H {}".format(shlex.quote(f"{key}: {value}"))

    data: bytes = (
        request.data
        if isinstance(request.data, bytes)
        else (
            request.data.read()  # type: ignore
            if isinstance(request.data, sob.abc.Readable)
            else (
                b"".join(request.data) if request.data else b""  # type: ignore
            )
        )
    )
    repr_data: str = ""
    if data:
        data_str = data.decode("utf-8")
        if censored_parameters and not is_json:
            query: dict[str, list[str]] = {}
            key: str
            value: list[str]
            for key, value in parse_qs(data_str).items():
                if key in censored_parameters:
                    query[key] = ["***"]
                else:
                    query[key] = value
            data_str = urlencode(query, safe=f"*{URLENCODE_SAFE}", doseq=True)
        try:
            repr_data = shlex.quote(data_str)
        except UnicodeDecodeError:
            # If the data can't be represented as a command-line argument,
            # use a placeholder
            repr_data = "***"
    return " ".join(
        filter(
            None,
            (
                f"curl -X {request.get_method()}",
                options,
                " ".join(
                    map(
                        _get_request_curl_header_item,
                        sorted(request.headers.items()),  # type: ignore
                    )
                ),
                (f"-d {repr_data}" if data else ""),
                shlex.quote(request.full_url),
            ),
        )
    )

default_retry_hook

default_retry_hook(error: Exception) -> bool

By default, don't retry for HTTP 404 (NOT FOUND) errors and HTTP 401 (UNAUTHORIZED) errors.

Source code in src/oapi/client.py
676
677
678
679
680
681
682
683
def default_retry_hook(error: Exception) -> bool:
    """
    By default, don't retry for HTTP 404 (NOT FOUND) errors
    and HTTP 401 (UNAUTHORIZED) errors.
    """
    if isinstance(error, HTTPError) and error.code in (404, 401, 409, 410):
        return False
    return True

retry

retry(
    errors: (
        tuple[type[Exception], ...] | type[Exception]
    ) = Exception,
    retry_hook: typing.Callable[
        [Exception], bool
    ] = oapi.client.default_retry_hook,
    number_of_attempts: int = 1,
    logger: logging.Logger | None = None,
) -> typing.Callable

This function decorates another, and causes the decorated function to be re-attempted a specified number of times, with exponential backoff, until the decorated function is successful or the maximum number of attempts is reached (in which case an exception is raised).

Parameters:

  • errors (tuple[type[Exception], ...] | type[Exception], default: Exception ) –

    A sub-class of Exception, or a tuple of one or more sub-classes of Exception. The default is Exception, causing all errors to trigger a retry.

  • retry_hook (typing.Callable[[Exception], bool], default: oapi.client.default_retry_hook ) –

    A function accepting as its only argument the handled exception, and returning a boolean value indicating whether or not to retry the function.

  • number_of_attempts (int, default: 1 ) –

    The maximum number of times to attempt execution of the function, including the first execution. Please note that, because the default for this parameter is 1, this decorator will do nothing if this argument is not provided.

Source code in src/oapi/client.py
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
def retry(
    errors: tuple[type[Exception], ...] | type[Exception] = Exception,
    retry_hook: typing.Callable[[Exception], bool] = default_retry_hook,
    number_of_attempts: int = 1,
    logger: Logger | None = None,
) -> typing.Callable:
    """
    This function decorates another, and causes the decorated function
    to be re-attempted a specified number of times, with exponential
    backoff, until the decorated function is successful or the maximum
    number of attempts is reached (in which case an exception is raised).

    Parameters:
        errors: A sub-class of `Exception`, or a tuple of one or more
            sub-classes of `Exception`. The default is `Exception`, causing
            *all* errors to trigger a retry.
        retry_hook: A function accepting as its only argument the handled
            exception, and returning a boolean value indicating whether or not
            to retry the function.
        number_of_attempts: The maximum number of times to attempt
            execution of the function, *including* the first execution. Please
            note that, because the default for this parameter is 1, this
            decorator will do *nothing* if this argument is not provided.
    """

    def decorating_function(function: typing.Callable) -> typing.Callable:
        attempt_number: int = 1

        @functools.wraps(function)
        def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
            nonlocal attempt_number
            nonlocal number_of_attempts
            if number_of_attempts - attempt_number:
                try:
                    return function(*args, **kwargs)
                except errors as error:
                    if not retry_hook(error):
                        raise
                    warning_message: str = (
                        f"Attempt # {attempt_number!s}:\n"
                        f"{sob.errors.get_exception_text()}"
                    )
                    warn(warning_message, stacklevel=2)
                    if logger is not None:
                        logger.warning(warning_message)
                    sleep(2**attempt_number)
                    attempt_number += 1
                    return wrapper(*args, **kwargs)
            return function(*args, **kwargs)

        return wrapper

    return decorating_function

write_client_module

write_client_module(
    client_path: str | pathlib.Path,
    *,
    open_api: (
        str | sob.abc.Readable | oapi.oas.model.OpenAPI
    ),
    model_path: str | pathlib.Path,
    class_name: str = "Client",
    base_class: type[
        oapi.client.Client
    ] = oapi.client.Client,
    imports: str | tuple[str, ...] = (),
    init_decorator: str = "",
    include_init_parameters: str | tuple[str, ...] = (),
    add_init_parameters: str | tuple[str, ...] = (),
    add_init_parameter_docs: str | tuple[str, ...] = (),
    init_parameter_defaults: (
        collections.abc.Mapping[str, typing.Any]
        | collections.abc.Sequence[tuple[str, typing.Any]]
    ) = (),
    init_parameter_defaults_source: (
        collections.abc.Mapping[str, typing.Any]
        | collections.abc.Sequence[tuple[str, typing.Any]]
    ) = (),
    get_method_name_from_path_method_operation: typing.Callable[
        [str, str, str | None], str
    ] = oapi.client.get_default_method_name_from_path_method_operation,
    use_operation_id: bool = False
) -> None

This function parses an Open API document and outputs a module defining a client class for interfacing with the API described by an OpenAPI document.

Parameters:

  • client_path (str | pathlib.Path) –

    The file path where the client module will be saved (created or updated).

  • open_api (str | sob.abc.Readable | oapi.oas.model.OpenAPI) –

    An OpenAPI document. This can be a URL, file-path, an HTTP response (http.client.HTTPResponse), a file object, or an instance of oapi.oas.model.OpenAPI.

  • model_path (str | pathlib.Path) –

    The file path where the data model for this client can be found. This must be a model generated using oapi.model, and must be part of the same project that this client will be saved into.

  • class_name (str, default: 'Client' ) –
  • base_class (type[oapi.client.Client], default: oapi.client.Client ) –

    The base class to use for the client. If provided, this must be a sub-class of oapi.client.Client.

  • imports (str | tuple[str, ...], default: () ) –

    One or more import statements to include (in addition to those generated automatically).

  • init_decorator (str, default: '' ) –

    A decorator to apply to the client class .__init__ method. If used, make sure to include any modules referenced in your imports. For example: "@decorator_function(argument_a=1, argument_b=2)".

  • include_init_parameters (str | tuple[str, ...], default: () ) –

    The name of all parameters to include for the client's .__init__ method.

  • add_init_parameters (str | tuple[str, ...], default: () ) –

    Additional parameter declarations to add to the client's .__init__ method. These should include a type hint and default value (not just the parameter name). For example: 'additional_parameter_name: str | None = None'. Note: additional parameters will not do anything without the use of a decorator which utilizes the additional parameters, so use of this parameter should be accompanied by an init_decorator.

  • add_init_parameter_docs (str | tuple[str, ...], default: () ) –
  • init_parameter_defaults (collections.abc.Mapping[str, typing.Any] | collections.abc.Sequence[tuple[str, typing.Any]], default: () ) –

    A mapping of parameter names to default values for the parameter.

  • init_parameter_defaults_source (collections.abc.Mapping[str, typing.Any] | collections.abc.Sequence[tuple[str, typing.Any]], default: () ) –

    A mapping of parameter names to default values for the parameter expressed as source code. This is to allow for the passing of imported constants, expressions, etc.

Source code in src/oapi/client.py
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
def write_client_module(
    client_path: str | Path,
    *,
    open_api: str | sob.abc.Readable | OpenAPI,
    model_path: str | Path,
    class_name: str = "Client",
    base_class: type[Client] = Client,
    imports: str | tuple[str, ...] = (),
    init_decorator: str = "",
    include_init_parameters: str | tuple[str, ...] = (),
    add_init_parameters: str | tuple[str, ...] = (),
    add_init_parameter_docs: str | tuple[str, ...] = (),
    init_parameter_defaults: collections.abc.Mapping[str, typing.Any]
    | collections.abc.Sequence[tuple[str, typing.Any]] = (),
    init_parameter_defaults_source: collections.abc.Mapping[str, typing.Any]
    | collections.abc.Sequence[tuple[str, typing.Any]] = (),
    get_method_name_from_path_method_operation: typing.Callable[
        [str, str, str | None], str
    ] = get_default_method_name_from_path_method_operation,
    use_operation_id: bool = False,
) -> None:
    """
    This function parses an Open API document and outputs a module defining
    a client class for interfacing with the API described by an OpenAPI
    document.

    Parameters:
        client_path: The file path where the client module will be saved
            (created or updated).
        open_api: An OpenAPI document. This can be a URL, file-path, an
            HTTP response (`http.client.HTTPResponse`), a file object, or
            an instance of `oapi.oas.model.OpenAPI`.
        model_path: The file path where the data model for this
            client can be found. This must be a model generated using
            `oapi.model`, and must be part of the same project that this
            client will be saved into.
        class_name:
        base_class: The base class to use for the client. If provided,
            this must be a sub-class of `oapi.client.Client`.
        imports: One or more import statements to include
            (in addition to those generated automatically).
        init_decorator:  A decorator to apply to the client class
            `.__init__` method. If used, make sure to include any modules
            referenced in your `imports`. For example:
            "@decorator_function(argument_a=1, argument_b=2)".
        include_init_parameters: The name of all parameters to
            include for the client's `.__init__` method.
        add_init_parameters: Additional parameter
            declarations to add to the client's `.__init__` method.
            These should include a type hint and default value (not just
            the parameter name). For example:
            'additional_parameter_name: str | None = None'. Note:
            additional parameters will not do anything without the use of a
            decorator which utilizes the additional parameters, so use of
            this parameter should be accompanied by an `init_decorator`.
        add_init_parameter_docs:
        init_parameter_defaults: A mapping of
            parameter names to default values for the parameter.
        init_parameter_defaults_source: A mapping of
            parameter names to default values for the parameter *expressed
            as source code*. This is to allow for the passing of imported
            constants, expressions, etc.
    """
    locals_: dict[str, typing.Any] = dict(locals())
    locals_.pop("client_path")
    client_module: ClientModule = ClientModule(**locals_)
    client_module.save(client_path)