API Reference¶
Resource¶
restfulchemy.resource¶
Base classes for building resources and model resources.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
exception
restfulchemy.resource.BadRequestException[source]¶ Exception for when a request is unable to be processed.
-
class
restfulchemy.resource.BaseModelResource(session, schema_context=None, page_max_size=None, gettext=None)[source]¶ Model API Resources should inherit from this object.
-
class
Meta[source]¶ Options object for a Resource.
Example usage:
class Meta: schema_class = MyModelSchema
Available options:
schema_class: The model schema this resource is built around.
-
BaseModelResource.OPTIONS_CLASS¶ alias of
ModelResourceOpts
-
BaseModelResource.convert_key_name(key)[source]¶ Given a dumped key name, convert to the name of the field.
Parameters: key (str) – Name of the field as it was serialized, using dot notation for nested fields.
-
BaseModelResource.delete(ident)[source]¶ Delete the identified resource.
Parameters: ident – A value used to identify this resource. See get()for more info.Raises: ResourceNotFoundError – If no such resource exists. Returns: None
-
BaseModelResource.delete_collection(filters=None, session=None)[source]¶ Delete all filter matching members of the collection.
Parameters: - filters (dict or None) – MQLAlchemy style filters.
- session (
SessionorQuery) – Seeget()for more info.
Returns: None
-
BaseModelResource.get(ident, fields=None, embeds=None, session=None, strict=True)[source]¶ Get the identified resource.
Parameters: - ident – A value used to identify this resource. If the
schema associated with this resource has multiple
id_keys, this value may be a list or tuple. - fields (list or None) – Names of fields to be included in the result.
- embeds (list or None) – A list of relationship and relationship field names to be included in the result.
- session (
SessionorQuery) – Optional sqlalchemy session override. May also be a partially formed SQLAlchemy query, allowing for sub-resource queries by using :meth:~`sqlalchemy.orm.query.Query.with_parent`. - strict (bool) – If True, will raise an exception when bad parameters are passed. If False, will quietly ignore any bad input and treat it as if none was provided.
Raises: - ResourceNotFoundError – If no such resource exists.
- BadRequestException – Invalid fields or embeds will result in a raised exception if strict is set to True.
Returns: The resource itself if found.
Return type: - ident – A value used to identify this resource. If the
schema associated with this resource has multiple
-
BaseModelResource.get_collection(filters=None, fields=None, embeds=None, sorts=None, offset=None, limit=None, session=None, strict=True)[source]¶ Get a collection of resources.
Parameters: - filters (list or None) – MQLAlchemy filters to be applied on this query.
- fields (list or None) – Names of fields to be included in the result.
- embeds (list or None) – A list of relationship and relationship field names to be included in the result.
- sorts (list of
SortInfo, or None) – Sorts to be applied to this query. - offset (int or None) – Standard SQL offset to be applied to the query.
- limit (int or None) – Standard SQL limit to be applied to the query.
- session (
SessionorQuery) – Optional sqlalchemy session override. Seeget()for more info. - strict (bool) – If True, will raise an exception when bad parameters are passed. If False, will quietly ignore any bad input and treat it as if none was provided.
Raises: BadRequestException – Invalid filters, sorts, fields, embeds, offset, or limit will result in a raised exception if strict is set to True.
Returns: Resources meeting the supplied criteria.
Return type:
-
BaseModelResource.model¶ Get the model class associated with this resource.
-
BaseModelResource.page_max_size¶ Get the max number of resources to return.
-
BaseModelResource.patch(ident, data)[source]¶ Update the identified resource with the supplied data.
Parameters: Raises: - ResourceNotFoundError – If no such resource exists.
- UnprocessableEntityError – If the supplied data cannot be processed.
Returns: The updated resource.
Return type:
-
BaseModelResource.patch_collection(data)[source]¶ Update a collection of resources.
Individual items may be updated accordingly as part of the request as well.
Parameters: data (list) – A list of object data. If the object contains a key $opset to"add", the object will be added to the collection; otherwise the object must already be in the collection. If$opis set to"remove", it is accordingly removed from the collection.Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: None
-
BaseModelResource.post(data)[source]¶ Create a new resource and store it in the db.
Parameters: data (dict) – Data used to create a new resource. Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: The created resource. Return type: dict
-
BaseModelResource.post_collection(data)[source]¶ Create multiple resources in the collection of resources.
Parameters: data (list) – List of resources to be created. Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: None
-
BaseModelResource.put(ident, data)[source]¶ Replace the current object with the supplied one.
Parameters: Raises: - ResourceNotFoundError – If no such resource exists.
- UnprocessableEntityError – If the supplied data cannot be processed.
Returns: The replaced resource.
Return type:
-
BaseModelResource.schema_class¶ Get the schema class associated with this resource.
-
BaseModelResource.schema_context¶ Return the schema context for this resource.
-
BaseModelResource.session¶ Get a db session to use for this request.
-
BaseModelResource.whitelist(key)[source]¶ Determine whether a field is valid to be queried.
Uses the load_only property for the resource’s schema fields to determine whether the field should be queryable. Also handles nested queries without issue.
Parameters: key (str) – Dot notation field name. For example, if trying to query an album, this may look something like "tracks.playlists.track_id".
-
class
-
class
restfulchemy.resource.ModelResource(session, schema_context=None, page_max_size=None, gettext=None)[source]¶ Model API Resources should inherit from this object.
-
class
restfulchemy.resource.ModelResourceMeta(name, bases, attrs)[source]¶ Meta class inherited by ModelResource.
This is ultimately responsible for attaching an
optsobject toModelResource, as well as registering that class with theresource_class_registry.
-
class
restfulchemy.resource.ModelResourceOpts(meta)[source]¶ Meta class options for use with a ModelResource.
A
schema_classoption must be provided.Example usage:
class UserResource(ModelResource): class Meta: schema_class = UserSchema
-
class
restfulchemy.resource.ResourceABC[source]¶ Abstract resource base class.
-
delete(ident)[source]¶ Delete the identified resource.
Parameters: ident – Identifying info for the resource. Raises: ResourceNotFoundError – If no such resource exists. Returns: None
-
get(ident)[source]¶ Get an instance of this resource.
Parameters: ident – Identifying info for the resource. Returns: The resource itself if found. Raises: ResourceNotFoundError – If no such resource exists.
-
patch(ident, data)[source]¶ Update the identified resource with the supplied data.
Parameters: - ident – Identifying info for the resource.
- data – Data used to update the resource.
Raises: - ResourceNotFoundError – If no such resource exists.
- UnprocessableEntityError – If the supplied data cannot be processed.
Returns: The updated resource.
-
patch_collection(data)[source]¶ Update the collection of resources.
Parameters: data – Data used to update the collection of resources. Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: None
-
post(data)[source]¶ Create a resource with the supplied data.
Parameters: data – Data used to create the resource. Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: The created resource.
-
post_collection(data)[source]¶ Create multiple resources in the collection of resources.
Parameters: data – Data used to create the collection of resources. Raises: UnprocessableEntityError – If the supplied data cannot be processed. Returns: None
-
put(ident, data)[source]¶ Replace the identified resource with the supplied one.
Parameters: - ident – Identifying info for the resource.
- data – Data used to replace the resource.
Raises: - ResourceNotFoundError – If no such resource exists.
- UnprocessableEntityError – If the supplied data cannot be processed.
Returns: The replaced resource.
-
Schema¶
restfulchemy.schema¶
Classes for building REST API friendly, model based schemas.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
class
restfulchemy.schema.ModelResourceSchema(*args, **kwargs)[source]¶ Schema meant to be used with a ModelResource.
Enables sub-resource embedding, context processing, error translation, and more.
-
OPTIONS_CLASS¶ alias of
ModelResourceSchemaOpts
-
api_endpoint_base¶ Get the api resource endpoint name for this resource.
-
embed(items)[source]¶ Embed the list of field names provided.
Parameters: items (list) – A list of embeddable sub resources or sub resource fields.
-
get_instance(data)[source]¶ Retrieve an existing record by primary key(s).
Parameters: data (dict) – Data associated with this instance.
-
handle_error(error, data)[source]¶ Modifies error messages.
Parameters: - error (
ValidationError) – The exception instance to be raised. The error messages are modified in place rather than a new error being created. - data (dict) – The provided data to be deserialized.
- error (
-
id_keys¶ Get the fields used to identify a resource instance.
-
load(data, session=None, instance=None, *args, **kwargs)[source]¶ Deserialize the provided data into a SQLAlchemy object.
Parameters: - data (dict) – Data to be loaded into an instance.
- session (
Session) – Optional database session. Will be used in place ofself.sessionif provided. - instance – SQLAlchemy model instance data should be loaded
into. If None is provided at this point or when the
class was initialized, an instance will either be determined
using the provided data via
get_instance(), or if that fails a new instance will be created.
Returns: An instance with the provided data loaded into it.
-
-
class
restfulchemy.schema.ModelResourceSchemaOpts(meta)[source]¶ Meta class options for use with a ModelResourceSchema.
Defaults
model_convertertoModelResourceConverter.Defaults
id_keysto None, resulting in the model’s primary keys being used as identifier fields.Example usage:
class UserSchema(ModelResourceSchema): class Meta: # Use username to identify a user resource # rather than user_id. id_keys = ["username"] # Alternate converter to dump/load with camel case. model_converter = CamelModelResourceConverter
Model Converters¶
restfulchemy.converter¶
Convert SQLAlchemy models into Marshmallow schemas.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
class
restfulchemy.convert.CamelModelResourceConverter(schema_cls=None)[source]¶ Convert a model to a schema that uses camelCase field names.
-
class
restfulchemy.convert.ModelResourceConverter(schema_cls=None)[source]¶ Convert a model’s fields for use in a ModelResourceSchema.
-
fields_for_model(model, include_fk=False, fields=None, exclude=None)[source]¶ Generate fields for the provided model.
Parameters: Returns: Generated fields corresponding to each model property.
Return type:
-
property2field(prop, instance=True, **kwargs)[source]¶ Parameters: - prop (
ColumnPropertyorRelationshipProperty) – A column or relationship property used to determine a corresponding field. - instance – True if this method should return an actual instance of a field, False to return the actual field class.
- kwargs – Keyword args to be used in the construction of the field.
Returns: Depending on the value of
instance, either a field or a field class.Return type: Fieldor type- prop (
-
Fields¶
restfulchemy.fields¶
Marshmallow fields used in model resource schemas.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
class
restfulchemy.fields.APIUrl(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ Text field, displays the url of the resource it’s attached to.
-
class
restfulchemy.fields.EmbeddedField(default_field, embedded_field, embedded=False, *args, **kwargs)[source]¶ Contains a default field and an embeddable field.
Member or method access will use the default field provided if the current state isn’t embedded, or the embedded field provided if the current state is embedded.
A common use case is to have a default field be a
RelationshipUrl, and the embedded field be aNestedRelatedfield.-
active_field¶ Return the embedded field if embedded, else the default.
-
allow_none¶ Get the
active_field.allow_noneproperty.
-
attribute¶ Get the
active_field.attributeproperty.
-
context¶ Use the active_field implementation of context.
-
default¶ Get the
active_field.defaultproperty.
-
default_field¶ Return the default, non embedded field.
-
deserialize(value, attr=None, data=None)[source]¶ Call
active_field.deserialize.Parameters: Raises: ValidationError – If an invalid value is passed or if a required value is missing.
Returns: The deserialized value.
-
dump_only¶ Get the
active_field.dump_onlyproperty.
-
dump_to¶ Get the
active_field.dump_toproperty.
-
embedded¶ Return
Trueif the embedded field is currently active.
-
embedded_field¶ Get the embedded field, regardless of if it is embedded.
-
error_messages¶ Get the
active_field.error_messagesproperty.
-
fail(key, **kwargs)[source]¶ Call
active_field.fail.Parameters: - key (str) – The type of failure, used to choose which error message to include in the raised exception.
- kwargs – Key word args used for string replacement fields in the error message.
Raises: ValidationError – In all cases, raises an exception.
-
get_value(attr, obj, accessor=None, default=<marshmallow.missing>)[source]¶ Call
active_field.get_value.Parameters: - attr (str) – Name of the attribute containing the desired value.
- obj – A generic object that contains the desired value.
- accessor (callable or None) – Function used to pull values from
obj. Defaults toget_value(). - default – The default value to return if the attr can not be accessed in the obj.
Returns: The value of the object’s attr.
-
load_from¶ Get the
active_field.load_fromproperty.
-
load_only¶ Get the
active_field.load_onlyproperty.
-
metadata¶ Get the
active_field.metadataproperty.
-
missing¶ Get the
active_field.missingproperty.
-
name¶ Get the
active_field.nameproperty.
-
parent¶ Get the
active_field.parentproperty.
-
required¶ Get the
active_field.requiredproperty.
-
root¶ Use the active_field implementation of root.
-
serialize(attr, obj, accessor=None)[source]¶ Call
active_field.serialize.Parameters: Raises: ValidationError – In case of formatting problem.
Returns: The serialized value.
-
validate¶ Get the
active_field.validateproperty.
-
validators¶ Get the
active_field.validatorsproperty.
-
-
class
restfulchemy.fields.NestedRelated(nested, default=<marshmallow.missing>, exclude=(), only=None, many=False, column=None, **kwargs)[source]¶ A nested relationship field for use in a ModelSchema.
-
model¶ The model associated with this relationship.
Gets a list of id keys associated with this nested obj.
Note the hierarchy of id keys to return:
- If the attached schema for this nested field has an id_keys attr, use those keys.
- Else, if this field had a columns arg passed when initialized, use those column names.
- Else, use the primary key columns.
-
schema¶ The schema corresponding to this relationship.
-
-
class
restfulchemy.fields.RelationshipUrl(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, resource=None, **metadata)[source]¶ Text field, displays the sub resource url of a relationship.
-
resource_class¶ Get the nested resource class.
-
Param Parsing¶
restfulchemy.parser¶
Functions for parsing query info from url parameters.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
exception
restfulchemy.parser.InvalidSortInfoException[source]¶ Generic exception class for invalid sort info applying.
-
class
restfulchemy.parser.OffsetLimitInfo(offset, limit)¶ -
limit¶ Alias for field number 1
-
offset¶ Alias for field number 0
-
-
exception
restfulchemy.parser.OffsetLimitParseError[source]¶ Generic exception class for query parsing errors.
-
class
restfulchemy.parser.SortInfo(attr, direction)¶ -
attr¶ Alias for field number 0
-
direction¶ Alias for field number 1
-
-
restfulchemy.parser.parse_embeds(query_params, embeds_query_name='embeds')[source]¶ Parse sub-resource embeds from query params.
Parameters: Returns: A list of embeds to include in the response.
Return type: list of str
-
restfulchemy.parser.parse_fields(query_params, fields_query_name='fields')[source]¶ Parse from query params the fields to include in the response.
Parameters: Returns: A list of fields to be included in the response.
Return type: list of str
-
restfulchemy.parser.parse_filters(model_class, query_params, complex_query_name='query', only_parse_complex=False, convert_key_names_func=<type 'str'>, strict=True, gettext=None)[source]¶ Convert request params into MQLAlchemy friendly search.
Parameters: - model_class – The SQLAlchemy class being queried.
- query_params (dict) – A dict of query params in which filters may be supplied.
- complex_query_name (str) – The name of the key used to check for
a complex query value in the provided
query_params. Note that the complex query should be a json dumped dictionary value. - only_parse_complex (bool) – Set to True if all simple filters in the query params should be ignored.
- convert_key_names_func (callable or None) – If provided, should take in a dot
separated attr name and transform it such that the result is
the corresponding dot separated attribute in the
model_classbeing queried. Useful if, for example, you want to allow users to provide an attr name in one format (say camelCase) and convert it to the naming format used for your model objects (likely underscore). - strict (bool) – If True, exceptions will be raised for invalid input. Otherwise, invalid input will be ignored.
- gettext (callable or None) – Optionally may provide a gettext function to handle error message translations.
Raises: InvalidMQLException – Malformed complex queries or invalid
query_paramswill result in anInvalidMQLExceptionbeing raised ifstrictis True.Returns: A dictionary containing filters that can be passed to mqlalchemy for query filtering.
Return type:
-
restfulchemy.parser.parse_offset_limit(query_params, page_max_size=None, page_query_name='page', offset_query_name='offset', limit_query_name='limit', strict=True, gettext=None)[source]¶ Parse offset and limit from the provided query params.
Parameters: - query_params (dict) – A dictionary in which a limit or offset may be specified.
- page_max_size (int or None) – If page is provided,
page_max_sizelimits the number of results returned. Otherwise, if using limit and offset values from thequery_params,page_max_sizesets a max number of records to allow. - page_query_name (str) – The name of the key used to check for a
page value in the provided
query_params. If page is provided, it is used along with thepage_max_sizeto determine the offset that should be applied to the query. If a page number other than 1 is provided, apage_max_sizemust also be provided. - offset_query_name (str) – The name of the key used to check for
an offset value in the provided
query_params. - limit_query_name (str) – The name of the key used to check for a
limit value in the provided
query_params. - strict – If True, exceptions will be raised for invalid input. Otherwise, invalid input will be ignored.
- gettext – Optional function to be used for any potential error translation.
Raises: OffsetLimitParseError – Applicable if using strict mode only. If the provided limit is greater than page_max_size, or an invalid page, offset, or limit value is provided, then a
OffsetLimitParseErroris raised.Returns: An offset and limit value for this query.
Return type:
Query Builder¶
restfulchemy.query_builder¶
Functions for building SQLAlchemy queries.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
restfulchemy.query_builder.apply_load_options(query, model_class, embeds, strict=True, gettext=None)[source]¶ Given a list of embed names, determine SQLAlchemy joinedloads.
Parameters: - query (
Query) – SQLAlchemy query object. - model_class – SQLAlchemy model class being queried.
- embeds (list of str) – List of embedded relationships.
- strict (bool) – Will ignore encountered errors if False.
- gettext (callable or None) – Optionally may be provided to translate error messages.
Returns: An updated query object with load options applied to it.
Return type: Query- query (
-
restfulchemy.query_builder.apply_offset_and_limit(query, offset, limit)[source]¶ Applies offset and limit to the query if appropriate.
Parameters: - query (
Query) – Any desired filters must already have been applied. - offset (int or None) – Integer used to offset the query result.
- limit (int or None) – Integer used to limit the number of results returned.
Returns: A modified query object with an offset and limit applied.
Return type: Query- query (
-
restfulchemy.query_builder.apply_sorts(query, sorts, convert_key_names_func=<type 'str'>)[source]¶ Apply sorts to a provided query.
Parameters: - query (
Query) – A SQLAlchemy query; filters must already have been applied. - sorts (list of
SortInfo) – A list of sorts to apply to this query. - convert_key_names_func (callable) – Used to convert key names.
See
parse_filters().
Raises: - AttributeError – If a sort with an invalid attr name is provided.
- ValueError – If a sort not of type
SortInfois provided.
Returns: A modified version of the provided query object.
Return type: Query- query (
Automatic Routing¶
restfulchemy.router¶
Tools for automatically routing API url paths to resources.
Work in progress, should not be used as anything other than a proof of concept at this point.
| copyright: | (c) 2016 by Nicholas Repole and contributors. See AUTHORS for more details. |
|---|---|
| license: | MIT - See LICENSE for more details. |
-
restfulchemy.router.generic_api_router(method, path, api_resource, query_params, data=None, content_type='json', strict=True)[source]¶ Route requests based on path and resource.
Parameters: - path (str) – The resource path specified. This should not include
the root
/apior any versioning info. - api_resource (
ResourceABC) – An already initialized resource instance. - query_params (dict) – Dictionary of query parameters, likely provided as part of a request.
- strict (bool) – If True, faulty pagination info, fields, or embeds will result in an error being raised rather than silently ignoring them.
- path (str) – The resource path specified. This should not include
the root
-
restfulchemy.router.generic_api_router_get(path, api_resource, query_params, strict=True)[source]¶ Generic API router for GET requests.
Parameters: - path (str) – The resource path specified.
- api_resource (
ModelResource) – A resource instance. - query_params (dict) – Dictionary of query parameters.
- strict (bool) – If True, raise non fatal errors rather than ignoring them.
Returns: If this is a single entity query, an individual resource or None. If this is a collection query, a list of resources.
Resource Class Registry¶
Enables a registry of
Resource classes.
This allows for string lookup of resources, making it easier to reference them dynamically and avoid circular dependencies.
Warning
This module is treated as private API. Users should not need to use this module directly.
This module was taken directly from Marshmallow. The only difference is that it serves as a registry of resources rather than schemas. Please see below for the appropriate Marshmallow attribution.
Copyright 2015 Steven Loria
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
restfulchemy.resource_class_registry.get_class(classname, all=False)[source]¶ Retrieve a class from the registry.
Parameters: Raise: RegistryErrorif the class cannot be found or if there are multiple entries for the given class name andallis not True.Returns: The class matching the name provided if previously registered, or potentially a list of classes if
allis True.
-
restfulchemy.resource_class_registry.register(classname, cls)[source]¶ Add a class to the registry of resource classes.
When a class is registered, an entry for both its classname and its full, module-qualified path are added to the registry.
Example:
class MyClass: pass register('MyClass', MyClass) # Registry: # { # 'MyClass': [path.to.MyClass], # 'path.to.MyClass': [path.to.MyClass], # }
Parameters: - classname (str) – Name of the class to be registered.
- cls – The class to be registered.