Data Models¶
Here are a collection of basic data structures to be used when making requests with the API clients.
Basic Models¶
- clsBaseModel.construct (inherited)
- clsBaseModel.from_orm (inherited)
- clsBaseModel.parse_file (inherited)
- clsBaseModel.parse_obj (inherited)
- clsBaseModel.parse_raw (inherited)
- clsBaseModel.schema (inherited)
- clsBaseModel.schema_json (inherited)
- defcopy (inherited)
- defdict (inherited)
- defjson (inherited)
- 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.
- __config__¶
The configuration class for the model.
Tip
See this example for information on how to create the model config.
- Type
- 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
dictrepresentation 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 toFalseexclude_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 toFalse.exclude_none¶ (Optional[
bool]) – Whether of not to include fields which are equal toNone. Defaults toFalse.
- Returns
- 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_dictoption toFalseto 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
encoderargument. 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 toFalseexclude_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 toFalse.exclude_none¶ (Optional[
bool]) – Whether of not to include fields which are equal toNone. Defaults toFalse.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 defaultjsoncannot normally handle, like adatetime.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 toTrue.**dumps_kwargs¶ – Any extra keyword arguments are passed to
json.dumps()directly, such as theindentargument, which will pretty-print the resultingstr, using indentations ofindentspaces.
- 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 todict.update().deep¶ (Optional[
bool]) – Whether to make a deep copy of the object, or a shallow copy. Defaults toFalse.
- 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.
- classmethod parse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)¶
- This classmethod inherits from pydantic.BaseModel.parse_raw.
Takes a
strorbytesand parses it to a JSON structure, then passes that toparse_obj()to load it into the model. This can also handle loadingpickledata directly via thecontent_typeargument.- Parameters
b¶ (Union[
str,bytes]) – The content to load into the model. This should be either a JSON serializedstr, or apickle.dumps()object.- Keyword Arguments
content_type¶ (Optional[
str]) – The content type of thebdata passed. Should either beapplication/jsonorapplication/pickle, if provided. Defaults to`None.encoding¶ (Optional[
str]) – If abytesobject is passed with a content type ofjson, it must be decoded using the same method it was encoded in. This defaults toutf8.proto¶ (Optional[
pydantic.Protocol]) – Another method of more directly specifying thecontent_typeof the data passed. This should bepydantic.Protocol.jsonorpydantic.Protocol.pickleif given. Otherwise, if neither thecontent_typeor this argument are passed, this is defaulted toProtocol.json.allow_pickle¶ (Optional[
bool]) – Whether or not to allow reading of pickled input. If thecontent_typeorprotocolare set to apickledata type, this must be set toTrue. Defaults toFalse
- Raises
pydantic.ValidationError – Raised if the
bcannot be used to instantiate the model, or if thecontent_typeis set toaplication/picklewithout settingallow_pickletoTrue.pickle.UnpicklingError – Raised when Pickle fails to load an object.
- Returns
- 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 loadingpickledata directly via thecontent_typeargument.- 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 givenpath. Should either beapplication/jsonorapplication/pickle, if provided. Defaults toNone.encoding¶ (Optional[
str]) – If abytesobject is passed with a content type ofjson, it must be decoded using the same method it was encoded in. This defaults toutf8.proto¶ (Optional[
pydantic.Protocol]) – Another method of more directly specifying thecontent_typeof the data passed. This should bepydantic.Protocol.jsonorpydantic.Protocol.pickleif given. Otherwise, if neither thecontent_typeor this argument are passed, this is defaulted toProtocol.json.allow_pickle¶ (Optional[
bool]) – Whether or not to allow reading of pickled input. If thecontent_typeorprotocolare set to apickledata type, this must be set toTrue. Defaults toFalse
- Raises
pydantic.ValidationError – Raised if the
pathcannot be used to instantiate the model.FileNotFoundError – Raised when the
pathprovided could not be used to open a file.TypeError – Raised when trying to decode with pickle without setting
allow_pickletoTrue.
- Returns
- 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 propertyorm_modemust be set toTrue.- 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_modeset toTruein 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 toTrue.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 theref_templatetemplate 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 theindexargument, 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 toTrue.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 theref_templatetemplate provided inside the parent model.
- Returns
- 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 around30xfaster 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]) – Asetofstrfield 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
dictthat you want to pass, and you can do so by usingBaseModel.construct(**my_dict). To create a model from another model, you can useBaseModel.construct(**model_instance.dict()).
Response Models¶
These models are used to define what a response that you receive is expected to look like.
Response¶
- clsBaseModel.construct (inherited)
- clsBaseModel.from_orm (inherited)
- clsBaseModel.parse_file (inherited)
- clsBaseModel.parse_obj (inherited)
- clsBaseModel.parse_raw (inherited)
- clsBaseModel.schema (inherited)
- clsBaseModel.schema_json (inherited)
- defcopy (inherited)
- defdict (inherited)
- defjson (inherited)
- 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
uriandtimeattributes of this response method will not be included in any output methods for the model. They are purely intended for programmatic usage.- time¶
The time that the response was received at.
- Type
Paginated Response¶
- clsBaseModel.construct (inherited)
- clsBaseModel.from_orm (inherited)
- clsBaseModel.parse_file (inherited)
- clsBaseModel.parse_obj (inherited)
- clsBaseModel.parse_raw (inherited)
- clsBaseModel.schema (inherited)
- clsBaseModel.schema_json (inherited)
- defcopy (inherited)
- defdict (inherited)
- defend
- defis_paginating
- defjson (inherited)
- defnext
- defprevious
- defstart
- 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
abstractclass, 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, returnFalse. 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_numberfield, you would returnself.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, andstartfor navigating pagination, should callis_paginating()and returnNoneif 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_numberfield, you would returnself.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_countfield, you would want to returnself.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
1for the first page.- Returns
Optional[Any] – Some identifier for navigating to the first page in the pagination.