Data Models

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

Basic Models

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 ina 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.

Response

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.

Paginated Response

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.