API Reference

These are the most common structures that will be included in nearly every project.

Sync Client

class arya_api_framework.SyncClient(*args, **kwargs)

The core API framework client for synchronous API integration.

Warning

All of the configuration for this class and its subclasses are done through subclass parameters. This means that the __init__ method can be used for any extra setup for your specific use-case. The parameters shown below are for subclass parameters only.

Example:
class MyClient(
        SyncClient,
        uri="https://exampleurl.com",
        parameters={"arg1": "abc"}
):
    ...
Keyword Arguments
  • uri (Union[str, yarl.URL]) –

    • This is a keyword only argument.

    The base URI that will prepend all requests made using the client.

    Warning

    This should always be passed. If it is not given, an errors.ClientError exception will be raised.

  • headers (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    The default headers to pass with every request. Can be overridden by individual requests. Defaults to None.

  • cookies (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    The default cookies to pass with every request. Can be overridden by individual requests. Defaults to None.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    The default parameters to pass with every request. Can be overridden by individual requests. Defaults to None.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int error codes to BaseModel types to use when that error code is received. Defaults to None and raises default exceptions for error codes.

  • bearer_token (Optional[Union[str, pydantic.SecretStr]]) –

    • This is a keyword only argument.

    A bearer_token that will be sent with requests in the Authorization header. Defaults to None

  • rate_limit (Optional[Union[int, float]]) –

    • This is a keyword only argument.

    The number of requests to allow over rate_limit_interval seconds. Defaults to None

  • rate_limit_interval (Optional[Union[int, float]]) –

    • This is a keyword only argument.

    The period of time, in seconds, over which to apply the rate limit per every rate_limit requests. Defaults to 1 second.

closed
  • This is a read-only attribute.

Whether of not the internal requests.Session has been closed. If the session has been closed, the client will not allow any further requests to be made.

Type

bool

extensions
  • This is a read-only attribute.

A mapping of extensions by name to extension.

Type

Mapping[str, types.ModuleType]

subclients
  • This is a read-only attribute.

A mapping of sub-clients by name to sub-client.

Type

Mapping[str, SubClient]

uri
  • This is a read-only attribute.

The base URI that will prepend all requests made using the client.

Type

Optional[yarl.URL]

uri_root
  • This is a read-only attribute.

The root origin of the uri given to the client.

Type

Optional[yarl.URL]

uri_path
  • This is a read-only attribute.

The path from the uri_root to the uri path.

Type

Optional[yarl.URL]

headers

The default headers that will be passed into every request, unless overridden.

Type

Optional[dict]

bearer_token

The token used for the Authorization field of the headers attribute. Sets the Authorization header to Bearer {bearer_token}.

Type

Optional[str]

cookies

The default cookies that will be passed into every request, unless overridden.

Type

Optional[dict]

parameters

The default parameters that will be passed into every request, unless overridden.

Type

Optional[dict]

error_responses

A mapping of int error codes to either a BaseModel that should be used to represent them, or a function to be used as a handler for errors of that type.

Note

By default, an internal exception mapping is used. See Exception Hierarchy.

Type

Optional[dict]

rate_limit
  • This is a read-only attribute.

The number of requests per rate_limit_interval the client is allowed to send.

Type

Optional[Union[int, float]]

rate_limit_interval
  • This is a read-only attribute.

The interval, in seconds, over which to apply a rate limit for rate_limit requests per interval.

Type

Optional[Union[int, float]]

is_rate_limited
  • This is a read-only attribute.

Whether or not the client has a rate limit set.

Type

bool

request(method, path='', /, *, body=None, data=None, files=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a request to the path specified using the internal requests.Session.

Note

If the client has been closed (using close()), the request will not be processed. Instead, a warning will be logged, and this method will return None.

Parameters
  • method (str) –

    • This is a positional only argument.

    The request method to use for the request (see HTTP Request Methods).

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • files (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of str file names to file objects to send in the request.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

upload_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal requests.Session, which will upload a given file.

Tip

To stream larger file uploads, use the stream_file() method.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

stream_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal requests.Session, which will upload a given file.

Tip

This method is meant to upload larger files in a stream manner, while the upload_file() method uploads the file without streaming it.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

get(path='', *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a GET request to the path specified using the internal requests.Session.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the GET request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the GET request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the GET request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

post(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal requests.Session.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

patch(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a PATCH request to the path specified using the internal requests.Session.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

put(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a PUT request to the path specified using the internal requests.Session.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) – Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

delete(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a DELETE request to the path specified using the internal requests.Session.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw response object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, requests.Response]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response object.

close()

Closes the current requests.Session, if not already closed.

Unloads any loaded extensions and SubClients.

add_subclient(subclient)

Loads a SubClient as a child route of the primary client. Loaded sub-clients can be viewed through subclients.

Note

Any SubClient must meet a few requirements in order to be added to a parent:
  • The SubClient cannot already be loaded to a different parent.

  • The SubClient cannot already be loaded to the current parent.

  • The SubClient cannot be loaded to itself as a parent.

Parameters

subclient (SubClient) – The sub-client to add as a child of the parent client tree.

Raises
load_extension(name, *, package=None)

Loads an extension.

An extension is a separate python module (file) that contains a sub-group of requests.

Any extension module should include a function setup defined as the entry point for loading the extension, which takes a single argument of a client, either a SyncClient or an AsyncClient.

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
reload_extension(name, *, package=None)

Unloads, and then loads an extension.

This is the same as an unload_extension() followed by a load_extension(). If the reload fails, the client will roll-back to the previous working extension version.

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
  • ExtensionNotFound – The extension could not be found. This usually means that the extension file could not be found.

  • ExtensionNotLoaded – The extension is not loaded to the client, and therefore cannot be unloaded.

remove_subclient(name)

Removes a loaded child SubClient from the primary client. Loaded sub-clients can be viewed through subclients.

Parameters

name (str) – The name of the SubClient to remove as a child of the parent client tree. This should correspond to the :attr`name <SubClient.name>` attribute of the sub-client.

Returns

Optional[SubClient] – The SubClient that was unloaded, if one was.

tree(serialized=False, indent=None)

Gets meta-information about the client and all SubClients registered to the client. This includes information about endpoints attached to individual request methods using the @apiclient and @endpoint() decorators.

Parameters
  • serialized (bool) – Whether or not to serialized the resulting tree into a string. Defaults to False.

  • indent (int) – The indentation to use for pretty printing serialized data. Only applies if serialized is True. This parameter is directly passed to the json.dumps() indent parameter. Defaults to None, returning a single-line string.

Returns

Union[dict, str] – The client tree dictionary, or the serialized client tree dictionary.

unload_extension(name, *, package=None)

Unloads an extension.

Any sub-clients added in an extension will be removed from that extension when it is unloaded.

Optionally, an extension module can have a teardown function which will be called as a module is unloaded, which receives a single argument of a client, either a SyncClient or an AsyncClient, similar to setup from load_extension().

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
  • ExtensionNotFound – The extension could not be found. This usually means that the extension file could not be found.

  • ExtensionNotLoaded – The extension is not loaded to the client, and therefore cannot be unloaded.

Async Client

class arya_api_framework.AsyncClient(*args, **kwargs)

The core API framework client for asynchronous API integration.

Warning

All of the configuration for this class and its subclasses are done through subclass parameters. This means that the __init__ method can be used for any extra setup for your specific use-case. The parameters shown below are for subclass parameters only.

Example:
class MyClient(
        AsyncClient,
        uri="https://exampleurl.com",
        parameters={"arg1": "abc"}
):
    ...
Keyword Arguments
  • uri (Union[str, yarl.URL]) –

    • This is a keyword only argument.

    The base URI that will prepend all requests made using the client.

    Warning

    This should always be passed. If it is not given, an errors.ClientError exception will be raised.

  • headers (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    The default headers to pass with every request. Can be overridden by individual requests. Defaults to None.

  • cookies (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    The default cookies to pass with every request. Can be overridden by individual requests. Defaults to None.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    The default parameters to pass with every request. Can be overridden by individual requests. Defaults to None.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int error codes to BaseModel types to use when that error code is received. Defaults to None and raises default exceptions for error codes.

  • bearer_token (Optional[Union[str, pydantic.SecretStr]]) –

    • This is a keyword only argument.

    A bearer_token that will be sent with requests in the Authorization header. Defaults to None

  • rate_limit (Optional[Union[int, float]]) –

    • This is a keyword only argument.

    The number of requests to allow over rate_limit_interval seconds. Defaults to None

  • rate_limit_interval (Optional[Union[int, float]]) –

    • This is a keyword only argument.

    The period of time, in seconds, over which to apply the rate limit per every rate_limit requests. Defaults to 1 second.

closed
  • This is a read-only attribute.

Whether of not the internal requests.Session has been closed. If the session has been closed, the client will not allow any further requests to be made.

Type

bool

extensions
  • This is a read-only attribute.

A mapping of extensions by name to extension.

Type

Mapping[str, types.ModuleType]

subclients
  • This is a read-only attribute.

A mapping of sub-clients by name to sub-client.

Type

Mapping[str, SubClient]

uri
  • This is a read-only attribute.

The base URI that will prepend all requests made using the client.

Type

Optional[yarl.URL]

uri_root
  • This is a read-only attribute.

The root origin of the uri given to the client.

Type

Optional[yarl.URL]

uri_path
  • This is a read-only attribute.

The path from the uri_root to the uri path.

Type

Optional[yarl.URL]

headers

The default headers that will be passed into every request, unless overridden.

Type

Optional[dict]

cookies

The default cookies that will be passed into every request, unless overridden.

Type

Optional[dict]

parameters

The default parameters that will be passed into every request, unless overridden.

Type

Optional[dict]

error_responses

A mapping of int error codes to the BaseModel that should be used to represent them.

Note

By default, an internal exception mapping is used. See Exception Hierarchy.

Type

Optional[dict]

rate_limit
  • This is a read-only attribute.

The number of requests per rate_limit_interval the client is allowed to send.

Type

Optional[Union[int, float]]

rate_limit_interval
  • This is a read-only attribute.

The interval, in seconds, over which to apply a rate limit for rate_limit requests per interval.

Type

Optional[Union[int, float]]

is_rate_limited
  • This is a read-only attribute.

Whether or not the client has a rate limit set.

Type

bool

await request(method, path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a request to the path specified using the internal aiohttp.ClientSession.

Note

If the client has been closed (using close()), the request will not be processed. Instead, a warning will be logged, and this method will return None.

Parameters
  • method (str) –

    • This is a positional only argument.

    The request method to use for the request (see HTTP Request Methods).

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await upload_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal aiohttp.ClientSession, which will upload a given file.

Tip

To stream larger file uploads, use the stream_file() method.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await stream_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal aiohttp.ClientSession, which will upload a given file.

Tip

This method is meant to upload larger files in a stream manner, while the upload_file() method uploads the file without streaming it.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await get(path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a GET request to the path specified using the internal aiohttp.ClientSession.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the GET request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the GET request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the GET request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await post(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a POST request to the path specified using the internal aiohttp.ClientSession.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await patch(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a PATCH request to the path specified using the internal aiohttp.ClientSession.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await put(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a PUT request to the path specified using the internal aiohttp.ClientSession.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await delete(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

Sends a DELETE request to the path specified using the internal aiohttp.ClientSession.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s uri, to send the request to. If this is set to None, the request will be sent to the client’s uri.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[Union[dict, BaseModel]]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw aiohttp.ClientResponse object.

await close()

Closes the current aiohttp.ClientSession, if not already closed.

Unloads any loaded extensions and SubClients.

add_subclient(subclient)

Loads a SubClient as a child route of the primary client. Loaded sub-clients can be viewed through subclients.

Note

Any SubClient must meet a few requirements in order to be added to a parent:
  • The SubClient cannot already be loaded to a different parent.

  • The SubClient cannot already be loaded to the current parent.

  • The SubClient cannot be loaded to itself as a parent.

Parameters

subclient (SubClient) – The sub-client to add as a child of the parent client tree.

Raises
load_extension(name, *, package=None)

Loads an extension.

An extension is a separate python module (file) that contains a sub-group of requests.

Any extension module should include a function setup defined as the entry point for loading the extension, which takes a single argument of a client, either a SyncClient or an AsyncClient.

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
reload_extension(name, *, package=None)

Unloads, and then loads an extension.

This is the same as an unload_extension() followed by a load_extension(). If the reload fails, the client will roll-back to the previous working extension version.

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
  • ExtensionNotFound – The extension could not be found. This usually means that the extension file could not be found.

  • ExtensionNotLoaded – The extension is not loaded to the client, and therefore cannot be unloaded.

remove_subclient(name)

Removes a loaded child SubClient from the primary client. Loaded sub-clients can be viewed through subclients.

Parameters

name (str) – The name of the SubClient to remove as a child of the parent client tree. This should correspond to the :attr`name <SubClient.name>` attribute of the sub-client.

Returns

Optional[SubClient] – The SubClient that was unloaded, if one was.

tree(serialized=False, indent=None)

Gets meta-information about the client and all SubClients registered to the client. This includes information about endpoints attached to individual request methods using the @apiclient and @endpoint() decorators.

Parameters
  • serialized (bool) – Whether or not to serialized the resulting tree into a string. Defaults to False.

  • indent (int) – The indentation to use for pretty printing serialized data. Only applies if serialized is True. This parameter is directly passed to the json.dumps() indent parameter. Defaults to None, returning a single-line string.

Returns

Union[dict, str] – The client tree dictionary, or the serialized client tree dictionary.

unload_extension(name, *, package=None)

Unloads an extension.

Any sub-clients added in an extension will be removed from that extension when it is unloaded.

Optionally, an extension module can have a teardown function which will be called as a module is unloaded, which receives a single argument of a client, either a SyncClient or an AsyncClient, similar to setup from load_extension().

Registered extensions can be seen through the extensions property.

Parameters

name (str) – The name of the extension to load. This should be in the same format as a normal python import. For example, if you wanted to reference the extensions/submodule.py module, you would set the name parameter to extensions.submodule.

Keyword Arguments

package (Optional[str]) – The name of the package to load relative imports from. For example, if a name parameter is given as .submodule to reference the extensions/submodule.py extension, the package parameter would be extensions. Defaults to None.

Raises
  • ExtensionNotFound – The extension could not be found. This usually means that the extension file could not be found.

  • ExtensionNotLoaded – The extension is not loaded to the client, and therefore cannot be unloaded.

Sub Client

class arya_api_framework.SubClient(*args, **kwargs)

The secondary API framework client for itemizing and keeping code clean.

By creating “SubClients” that are subclassed from this class, it is possible to add modules to the overall API structure in a relatively simply way.

Additionally, sub-clients can be nested, allowing for a tree structure that can encompass an entire API interface. For more information on modular development with the library, see the SubClient Guide.

Warning

All of the configuration for this class and its subclasses are done through subclass parameters. This means that the __init__ method is free reign for you to use as you see fit. The parameters shown below are specifically for subclass parameters only.

Example:
class MySubClient(SubClient, name='sub_client_module', relative_path='/example'):
    pass
Parameters
  • name (Optional[str]) – The name to use for the class internally. This name must be a valid variable name. By using this, the name of each individual sub-client can be managed more directly then through the class name, maintaining proper code guidelines while also being user-friendly. By default, this is set to None, and the name parameter will reference the name of the class.

  • relative_path (Optional[str]) – The relative path from the root URI of the entire API client. For example, if the root URI is https://example.com/api, a SubClient with a relative_path set to /get will access the https://example.com/api/get route for all endpoints within that sub-client. Additionally, nested sub-clients will reference their relative paths according to the parent sub-client.

name
  • This is a read-only attribute.

The name of the sub-client. This is either the name subclass parameter, or the __name__ attribute of the class itself.

Type

str

qualified_name
  • This is a read-only attribute.

The full name of the sub-client, showing its location in the overall API structure using the . method, like subclient1.subclient2.this_subclient.

Type

str

relative_path
  • This is a read-only attribute.

A yarl URL that contains a relative url path from the parent client or sub-client. This is set in the relative_path subclass parameter, or set to the parent URI by default.

Type

yarl.URL

full_relative_path
  • This is a read-only attribute.

A yarl URL that contains the relative path from the base client’s SyncClient.uri attribute.

Type

yarl.URL

qualified_path
  • This is a read-only attribute.

A yarl URL that contains the full URL path to the resource, includig the root URL.

Type

yarl.URL

parent
  • This is a read-only attribute.

The parent client of the sub-client. This gets set automatically when calling add_subclient(). This is set to None by default, and gets reset to None if the module or client is ever unloaded.

Type

Union[SyncClient, AsyncClient, SubClient]

subclients
  • This is a read-only attribute.

A mapping of name to SubClient for all registered sub-clients of the current client. Registry is updated automatically when calling add_subclient() or remove_subclient().

Type

Mapping[str, SubClient]

request(method, path='', /, *, body=None, data=None, files=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.request() or AsyncClient.request(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters
  • method (str) –

    • This is a positional only argument.

    The request method to use for the request (see HTTP Request Methods).

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • files (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of str file names to file objects to send in the request.

  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

upload_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.upload_file() or AsyncClient.upload_file(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

stream_file(file, path='', /, *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.stream_file() or AsyncClient.stream_file(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters
  • file (str) –

    • This is a positional only argument.

    The path to the file to upload.

  • path (Optional[str]) –

    • This is a positional only argument.

    The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

get(path='', *, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.get() or AsyncClient.get(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

post(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.post() or AsyncClient.post(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

patch(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.patch() or AsyncClient.patch(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

put(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.put() or AsyncClient.put(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

delete(path='', /, *, body=None, data=None, headers=None, cookies=None, parameters=None, response_format=None, timeout=300, error_responses=None, raw=False)

This calls either SyncClient.delete() or AsyncClient.delete(), depending on whether the core client of the application is either of those types. For specifics, view those documentations.

Parameters

path (Optional[str]) –

  • This is a positional only argument.

The path, relative to the client’s relative_path, to send the request to. If this is not provided, the sub-client’s full_relative_path is used.

Keyword Arguments
  • body (Optional[Union[dict, BaseModel]) –

    • This is a keyword only argument.

    Optional data to send as a JSON structure in the body of the request. Defaults to None.

  • data (Optional[Any]) –

    • This is a keyword only argument.

    Optional data of any type to send in the body of the request, without any pre-processing. Defaults to None.

  • headers (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific headers to send with the request. Defaults to None and uses the default client headers.

  • cookies (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific cookies to send with the request. Defaults to None and uses the default client cookies.

  • parameters (Optional[dict, BaseModel]) –

    • This is a keyword only argument.

    Request-specific query string parameters to send with the request. Defaults to None and uses the default client parameters.

  • response_format (Optional[Type[Response]]) –

    • This is a keyword only argument.

    The model to use as the response format. This offers direct data validation and easy object-oriented implementation. Defaults to None, and the request will return a JSON structure.

  • timeout (Optional[int]) –

    • This is a keyword only argument.

    The length of time, in seconds, to wait for a response to the request before raising a timeout error. Defaults to 300 seconds, or 5 minutes.

  • error_responses (Optional[dict]) –

    • This is a keyword only argument.

    A mapping of int status codes to BaseModel models to use as error responses. Defaults to None, and uses the default error_responses attribute. If the error_responses is also None, or a status code does not have a specified response format, the default status code exceptions will be raised.

  • raw (Optional[bool]) –

    • This is a keyword only argument.

    Whether or not to return the raw requests.Response or aiohttp.ClientResponse object instead of parsing the results as a JSON response, or loading it to a BaseModel.

    New in version 0.3.5.

Returns

Optional[Union[dict, Response, aiohttp.ClientResponse]] – The request response JSON, loaded into the response_format model if provided, or as a raw dict otherwise. If raw is True, returns a raw requests.Response or aiohttp.ClientResponse object.

on_loaded()

A hook that is called when the SubClient is added to a parent. Has no implementation at default, so this is for any extra internal setup that a sub-client might need to do after gaining access to the parent client tree.

on_unloaded()

A hook that is called when the SubClient is removed from a parent. Has no implementation at default.

tree(serialized=False, indent=None, _root=True)

Gets meta-information about the sub-client and all SubClients registered to the client. This includes information about endpoints attached to individual request methods using the @apiclient and @endpoint() decorators.

Parameters
  • serialized (bool) – Whether or not to serialized the resulting tree into a string. Defaults to False.

  • indent (int) – The indentation to use for pretty printing serialized data. Only applies if serialized is True. This parameter is directly passed to the json.dumps() indent parameter. Defaults to None, returning a single-line string.

Returns

Union[dict, str] – The client tree dictionary, or the serialized client tree dictionary.

Data Models

Here are a collection of basic data structures to be used when making requests with the API clients.

Basic Models

The basic pydantic model that incorporates data validation. This usage of this model for requests is one of the reasons why this library is useful.

class arya_api_framework.BaseModel
This class inherits from pydantic.BaseModel.

These models include data validation on the attributes given to them, and allow for very direct control over response formats. Additionally, they allow to easily creating database-like structures, and outputting the data in a variety of formats.

__fields_set__

A set of names of fields which were set when the model was initialized.

Type

set

__fields__

A dict of the model’s fields.

Type

dict

__config__

The configuration class for the model.

Tip

See this example for information on how to create the model config.

Type

pydantic.BaseConfig

dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False)
This method inherits from pydantic.BaseModel.dict.

Generate a dict representation of the model, optionally specifying which fields to include or exclude. Look to the pydantic documentation for further details.

Keyword Arguments
  • include (Optional[Union[Set[str]], dict]]) – Fields to include in the returned dictionary. See this example.

  • exclude (Optional[Union[Set[str]], dict]]) – Fields to exclude from the returned dictionary. See this example.

  • by_alias (Optional[bool]) – Whether field aliases should be used as keys in the resulting dictionary. Defaults to False

  • exclude_unset (Optional[bool]) –

    Whether or not fields that were not specifically set upon creation of the model should be included in the dictionary. Defaults to False.

    Warning

    This was previously referred to as skip_defaults. This parameter is still accepted, but has been deprecated and is not recommended.

  • exclude_defaults (Optional[bool]) – Whether or not to include fields that are set to their default values. Even if a field is given a value when the model is instanced, if that value is equivalent to the default, it will not be included. Defaults to False.

  • exclude_none (Optional[bool]) – Whether of not to include fields which are equal to None. Defaults to False.

Returns

dict – A mapping of str field names to their values.

json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)
This method inherits from pydantic.BaseModel.json.

Serializes the model to a JSON string. Typically will call dict() and then serialize the result. As such, the parameters are very similar, except for a few extra options.

Tip

You can set the models_as_dict option to False to implement custom serialization for a model. See this example for more info.

Tip

It is possible to implement custom encoders for specific types within an individual model. This is helpful to avoid having to create an entire encoder for the encoder argument. See this example for more info.

Keyword Arguments
  • include (Optional[Union[Set[str]], dict]]) – Fields to include in the returned dictionary. See this example.

  • exclude (Optional[Union[Set[str]], dict]]) – Fields to exclude from the returned dictionary. See this example.

  • by_alias (Optional[bool]) – Whether field aliases should be used as keys in the resulting dictionary. Defaults to False

  • exclude_unset (Optional[bool]) –

    Whether or not fields that were not specifically set upon creation of the model should be included in the dictionary. Defaults to False.

    Warning

    This was previously referred to as skip_defaults. This parameter is still accepted, but has been deprecated and is not recommended.

  • exclude_defaults (Optional[bool]) – Whether or not to include fields that are set to their default values. Even if a field is given a value when the model is instanced, if that value is equivalent to the default, it will not be included. Defaults to False.

  • exclude_none (Optional[bool]) – Whether of not to include fields which are equal to None. Defaults to False.

  • encoder (Optional[Callable[Any, Any]]) – A custom encoder function that is given to json.dumps(). By default, a custom pydantic encoder is used, which can serialize many common types that the default json cannot normally handle, like a datetime.

  • models_as_dict (Optional[bool]) – Whether or not to serialize other models that are contained within the fields of the target model to json. This defaults to True.

  • **dumps_kwargs – Any extra keyword arguments are passed to json.dumps() directly, such as the indent argument, which will pretty-print the resulting str, using indentations of indent spaces.

Returns

str – A JSON serialized string.

copy(*, include=None, exclude=None, update=None, deep=False)
This method inherits from pydantic.BaseModel.copy.

Returns a duplicate of the model. This is very handy for use with immutable models.

Keyword Arguments
  • include (Optional[Union[Set[str]], dict]]) – Fields to include in the returned dictionary. See this example.

  • exclude (Optional[Union[Set[str]], dict]]) – Fields to exclude from the returned dictionary. See this example.

  • update (Optional[dict]) – A dictionary of values to update when creating the copied model. Very similar in concept to dict.update().

  • deep (Optional[bool]) – Whether to make a deep copy of the object, or a shallow copy. Defaults to False.

Returns

BaseModel – A copied instance of the model.

classmethod parse_obj(obj)
This classmethod inherits from pydantic.BaseModel.parse_obj.

Instantiates a model from a given dict.

Parameters

obj (Any) – The data to instantiate the class from. This should either be a dict or an object that can be cast as one using dict(obj).

Raises

pydantic.ValidationError – Raised if the obj parameter is not dict and cannot be made into one.

Returns

BaseModel – An instantiated model from the obj provided.

classmethod parse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)
This classmethod inherits from pydantic.BaseModel.parse_raw.

Takes a str or bytes and parses it to a JSON structure, then passes that to parse_obj() to load it into the model. This can also handle loading pickle data directly via the content_type argument.

Parameters

b (Union[str, bytes]) – The content to load into the model. This should be either a JSON serialized str, or a pickle.dumps() object.

Keyword Arguments
  • content_type (Optional[str]) – The content type of the b data passed. Should either be application/json or application/pickle, if provided. Defaults to `None.

  • encoding (Optional[str]) – If a bytes object is passed with a content type of json, it must be decoded using the same method it was encoded in. This defaults to utf8.

  • proto (Optional[pydantic.Protocol]) – Another method of more directly specifying the content_type of the data passed. This should be pydantic.Protocol.json or pydantic.Protocol.pickle if given. Otherwise, if neither the content_type or this argument are passed, this is defaulted to Protocol.json.

  • allow_pickle (Optional[bool]) – Whether or not to allow reading of pickled input. If the content_type or protocol are set to a pickle data type, this must be set to True. Defaults to False

Raises
  • pydantic.ValidationError – Raised if the b cannot be used to instantiate the model, or if the content_type is set to aplication/pickle without setting allow_pickle to True.

  • pickle.UnpicklingError – Raised when Pickle fails to load an object.

Returns

BaseModel – An instantiated model from the b provided.

classmethod parse_file(path, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)
This classmethod inherits from pydantic.BaseModel.parse_file.

Takes a file path and parses it to a JSON structure, then passes that to parse_raw() to load it into the model. This can also handle loading pickle data directly via the content_type argument.

Parameters

path (Union[str, pathlib.Path]) – A path to a file to load into the model.

Keyword Arguments
  • content_type (Optional[str]) – The content type of the date in the file at the given path. Should either be application/json or application/pickle, if provided. Defaults to None.

  • encoding (Optional[str]) – If a bytes object is passed with a content type of json, it must be decoded using the same method it was encoded in. This defaults to utf8.

  • proto (Optional[pydantic.Protocol]) – Another method of more directly specifying the content_type of the data passed. This should be pydantic.Protocol.json or pydantic.Protocol.pickle if given. Otherwise, if neither the content_type or this argument are passed, this is defaulted to Protocol.json.

  • allow_pickle (Optional[bool]) – Whether or not to allow reading of pickled input. If the content_type or protocol are set to a pickle data type, this must be set to True. Defaults to False

Raises
  • pydantic.ValidationError – Raised if the path cannot be used to instantiate the model.

  • FileNotFoundError – Raised when the path provided could not be used to open a file.

  • TypeError – Raised when trying to decode with pickle without setting allow_pickle to True.

Returns

BaseModel – An instantiated model from the file path.

classmethod from_orm(obj)
This classmethod inherits from pydantic.BaseModel.from_orm.

Instantiates the model from a given ORM class using ORM mode.

Warning

In order to use from_orm(), the config property orm_mode must be set to True.

Parameters

obj (Any) – The ORM object to construct the model from.

Raises
  • pydantic.ValidationError – Raised if the model could not be instantiated from the given ORM obj.

  • pydantic.ConfigError – Raised when the model does not have the orm_mode set to True in the config.

Returns

BaseModel – An instantiated model from the given ORM instance.

classmethod schema(by_alias=True, ref_template='#/definitions/{model}')
This classmethod inherits from pydantic.BaseModel.schema.

Converts the model into a dictionary schema.

Parameters
  • by_alias (Optional[bool]) – Whether or not to use aliased names for fields when outputting the data schema. See this example for creating field aliases. Defaults to True.

  • ref_template (Optional[str]) –

    The string template to use when outputting sub-models to the schema. The template should include {model} somewhere in it as a placeholder for the name of the sub-model. Defaults to #/definitions/{model}.

    Note

    When outputting the schema structure, all sub-models of the model will be output under the top-level JSON key definitions, and then referenced using the ref_template template provided inside the parent model.

Returns

dict – The model represented as a python dictionary.

classmethod schema_json(*, by_alias=True, ref_template='#/definitions/{model}', **dumps_kwargs)
This classmethod inherits from pydantic.BaseMode.schema_json.

Converts the model to a JSON serialized string.

Tip

Any extra keyword arguments passed to this method will be given to the json.dumps() function as keyword arguments. Using this, for example, means that you could pass the index argument, and cause the output string to be pretty-printed with indentation.

Keyword Arguments
  • by_alias (Optional[bool]) – Whether or not to use aliased names for fields when outputting the data schema. See this example for creating field aliases. Defaults to True.

  • ref_template (Optional[str]) –

    The string template to use when outputting sub-models to the schema. The template should include {model} somewhere in it as a placeholder for the name of the sub-model. Defaults to #/definitions/{model}.

    Note

    When outputting the schema structure, all sub-models of the model will be output under the top-level JSON key definitions, and then referenced using the ref_template template provided inside the parent model.

Returns

str – A JSON serialized str containing the model schema.

classmethod construct(_fields_set=None, **values)
This classmethod inherits from pydantic.BaseMode.construct.

Creates the model without running any validation. This can come in handy for slightly more performant code when creating models with data that has already been validated. Using construct() is usually around 30x faster than creating a model with complete validation. See an example here.

Warning

This method is capable of creating invalid data in the model, so it should only be used if the data has already been validated, or comes from another trusted source.

Parameters
  • _fields_set (Optional[set]) – A set of str field names to pass to the model’s __fields_set__ attribute.

  • **kwargs

    Any other keyword arguments given to the method will be processed as field names.

    Tip

    In many cases, you will likely have a dict that you want to pass, and you can do so by using BaseModel.construct(**my_dict). To create a model from another model, you can use BaseModel.construct(**model_instance.dict()).

Response Models

These models are used to define what a response that you receive is expected to look like.

class arya_api_framework.Response
This class inherits from BaseModel.

The basic class that all response models for a request should subclass. This class provides a few basic fields that are used in recording request responses.

Example

# Create your response structure:
class MyAPIResponse(Response):
    index: int
    first_name: str
    last_name: str

# Pass this into your requests:
response = my_client.get(..., response_model=MyAPIResponse)       # Sync
response = await my_client.get(..., response_mode=MyApiResponse)  # Async

# >>> response.dict()
{
    "request_base_": "url",
    "request_received_at_": datetime.datetime(...),
    "id": 123,
    "first_name": "First",
    "last_name": "Last"
}

Note

The uri and time attributes of this response method will not be included in any output methods for the model. They are purely intended for programmatic usage.

base_uri

The url of the original request this is holding the response to.

Type

Optional[str]

time

The time that the response was received at.

Type

datetime.datetime

Note

The uri and time properties are set by default when a Response is created. The default implementation is a timezone-aware UTC datetime.

class arya_api_framework.PaginatedResponse
This class inherits from Response.

This offers a few extra options for a request response to enable easier response pagination.

Often times when receiving a response for an API query which might include a significant amount of data (such as a list of products from an online shop), the API will limit the response to a set number of items. Taking this into account, this class can take advantage of the data structure to automatically give the necessary information about navigating this pagination.

Warning

This is an abstract class, which means that any subclasses must implement all methods from this class.

abstractmethod is_paginating()

A method that is intended to determine whether any given response is paginated or not.

If your response is always paginating, this should simply return True. Likewise, if the response is never paginating, return False. Otherwise, some logic should be implemented to determine whether the response is paginated.

Returns

bool – Whether the response is paginated.

abstractmethod next()

This will return an identifier for how to navigate to the next page in the paginated response.

For example, if a response has a page_number field, you would return self.page_number + 1. However, this can also be any return type, to allow for URLs to be returned directly, or some other implementation.

Tip

This method, as well as previous, end, and start for navigating pagination, should call is_paginating() and return None if the response is not paginating.

if not self.is_paginating():
    return
Returns

Optional[Any] – Some identifier for navigating to the next page in the pagination.

abstractmethod previous()

This will return an identifier for how to navigate to the previous page in the paginated response.

For example, if a response has a page_number field, you would return self.page_number - 1. However, this can also be any return type, to allow for URLs to be returned directly, or some other implementation.

Returns

Optional[Any] – Some identifier for navigating to the previous page in the pagination.

abstractmethod end()

This will return an identifier for how to navigate to the last page in the paginated response.

For example, if a response has a page_count field, you would want to return self.page_count. However, this can also be any return type, to allow for URLs to be returned directly, or some other implementation.

Returns

Optional[Any] – Some identifier for navigating to the last page in the pagination.

abstractmethod start()

This will return an identifier for how to navigate to the first page in the paginated response.

For example, if you were tracking pagination by numbering each page, you would simply return 1 for the first page.

Returns

Optional[Any] – Some identifier for navigating to the first page in the pagination.

Enums

enum arya_api_framework.constants.HTTPMethod(value)

A collection of all possible HTTP request methods.

Valid values are as follows:

GET = <HTTPMethod.GET: 'GET'>

The GET request method.

HEAD = <HTTPMethod.HEAD: 'HEAD'>

The HEAD request method.

POST = <HTTPMethod.POST: 'POST'>

The POST request method.

PUT = <HTTPMethod.PUT: 'PUT'>

The PUT request method.

DELETE = <HTTPMethod.DELETE: 'DELETE'>

The DELETE request method.

CONNECT = <HTTPMethod.CONNECT: 'CONNECT'>

The CONNECT request method.

OPTIONS = <HTTPMethod.OPTIONS: 'OPTIONS'>

The OPTIONS request method.

TRACE = <HTTPMethod.TRACE: 'TRACE'>

The TRACE request method.

PATCH = <HTTPMethod.PATCH: 'PATCH'>

The PATCH request method.

ANY = <HTTPMethod.ANY: 'ANY'>

Indicates that an endpoint accepts any request method.

Utility Functions

arya_api_framework.utils.flatten_obj(obj)

Flattens a given object into a dict.

This is mainly used for arguments where a dict or a BaseModel can be accepted as parameters.

Parameters

obj (Optional[Union[dict, BaseModel]]) – The object or model to flatten into a dict format.

Returns

dict – A mapping of str keys to Any values.

arya_api_framework.utils.merge_dicts(base_dict, update_dict)

Merges the base dict with the update dict, overriding any of the base dict’s values with the updated values from the update dict.

Parameters
  • base_dict (Optional[dict]) – The default dict to update.

  • update_dict (Optional[dict]) – The new dict to update the base_dict from.

Returns

dict – A mapping of str to Union[str, int, float] containing the merged dictionaries.

arya_api_framework.utils.validate_type(obj, target, err=True)

Validates that a given parameter is of a type, or is one of a collection of types.

Parameters
  • obj (Any) – A variable to validate the type of.

  • target (Union[Type, List[Type]]) – A type, or list of types, to check if the param is an instance of.

  • err (bool) – Whether or not to throw an error if a type is not validated.

Returns

bool – A boolean representing whether the type was validated.

@arya_api_framework.utils.apiclient

Decorates any SyncClient, AsyncClient, or SubClient to automatically read any methods decorated with an @endpoint decorator. The tree method is then populated using this metadata.

Example:
@apiclient
class MyClient(SyncClient, uri='https://example.com/api'):
    @endpoint(
        path='/',
        name='Get Example',
        href='https://example.com/api/docs/',
        method='GET'
    )
    def example(self):
        return self.get()
>>> client = MyClient()
>>> print(client.tree(serialize=True, indent=2))
{
  "root": {
    "__info__": {
      "uri": "https://example.com/api",
      "uri_root": "https://example.com"
    },
    "__endpoints__": {
      "example": {
        "path": "/",
        "name": "Get Example",
        "href": "https://example.com/api/docs/",
        "methods": [
          "GET"
        ]
      }
    },
    "__subclients__": {}
  }
}
@arya_api_framework.utils.endpoint(path, name=None, description=None, href=None, method=HTTPMethod.ANY, methods=None)

Attaches metadata to a request method in a SyncClient, AsyncClient, or SubClient. In order for this data to be applied to the client properly, the client must be decorated with a @apiclient decorator.

Note

To access the metadata attached to a method with @endpoint, use the tree method of any SyncClient, AsyncClient, or SubClient.

Parameters
  • path (str) – The relative path of the endpoint from the root URI of the client.

  • name (Optional[str]) – The name of the endpoint. If this is not provided, the function name is used.

  • href (Optional[str]) – A link to documentation for this endpoint. This will usually link to an API’s documentation.

  • method (Optional[Union[constants.HTTPMethod, str]]) – The request method that the endpoint makes use of.

  • methods (Optional[List[Union[constants.HTTPMethod, str]]]) –

    The request methods that an endpoint can make use of.

    Note

    The endpoint should include either method or methods or exclude them both.