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
932
933
934
935
936
937
938
939
940
941
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
943
944
945
946
947
948
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 = ".well-known/openid-configuration",
    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_scope (str | tuple[str, ...] | None, default: None ) –

    One or more OAuth2 scopes

  • 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, default: '.well-known/openid-configuration' ) –

    The URL where an OpenID Provider's configuration can be obtained.

  • 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
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
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 = ".well-known/openid-configuration",
    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_scope: One or more
            [OAuth2 scopes](https://oauth.net/2/scope/)
        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: The URL where an OpenID
            Provider's [configuration
            ](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
            can be obtained.
        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 (urlparse(url_).scheme 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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
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,
    module_docstring: str | None = None,
    class_docstring: str | None = None
)

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.

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

    A docstring to insert at the top of the module.

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

    A docstring to insert in the client class.

Source code in src/oapi/client.py
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
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,
    module_docstring: str | None = None,
    class_docstring: str | None = None,
) -> 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.
        module_docstring: A docstring to insert at the top of the module.
        class_docstring: A docstring to insert in the client class.
    """
    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
    self.module_docstring: str | None = module_docstring
    self.class_docstring: str | None = class_docstring

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
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
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(),
            (
                (
                    '    """',
                    sob.utilities.split_long_docstring_lines(
                        sob.utilities.indent(
                            self.class_docstring.strip(), start=0
                        )
                    ),
                    '    """',
                )
                if self.class_docstring
                else ()
            ),
            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())
    docstring: str = (
        f'"""\n{self.module_docstring}\n"""\n\n'
        if self.module_docstring
        else ""
    )
    return sob.utilities.suffix_long_lines(
        f"{docstring}{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
3924
3925
3926
3927
3928
3929
3930
3931
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 client_io:
        client_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
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
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,  # type: ignore
    )

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
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
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
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
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.)
    """
    content_type: str | None = request.headers.get("Content-type")
    if content_type:
        content_type = content_type.lower()
    content_encoding: str | None = request.headers.get("Content-encoding")
    is_json: bool = bool(
        content_type == "application/json"
        or (
            content_type
            and content_type.endswith("+json")
            and content_type.startswith("application/")
        )
    )
    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
            )
        )
    )
    if data and content_encoding:
        data = _decode_content(data, content_encoding)
    repr_data: str = ""
    if data:
        try:
            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
                )
            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
681
682
683
684
685
686
687
688
def default_retry_hook(error: Exception) -> bool:
    """
    By default, don't retry for HTTP 404 (NOT FOUND) errors
    and HTTP 401 (UNAUTHORIZED) errors.
    """
    return not (
        isinstance(error, HTTPError) and error.code in (404, 401, 409, 410)
    )

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
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
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,
    module_docstring: str | None = None,
    class_docstring: str | None = None
) -> 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.

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

    A docstring to insert at the top of the module.

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

    A docstring to insert in the client class.

Source code in src/oapi/client.py
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
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,
    module_docstring: str | None = None,
    class_docstring: str | None = None,
) -> 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.
        module_docstring: A docstring to insert at the top of the module.
        class_docstring: A docstring to insert in the client class.
    """
    locals_: dict[str, typing.Any] = dict(locals())
    locals_.pop("client_path")
    client_module: ClientModule = ClientModule(**locals_)
    client_module.save(client_path)