API Bundle API

flask_unchained.bundles.api

ApiBundle

The API Bundle.

flask_unchained.bundles.api.config

Config

Default config settings for the API Bundle.

flask_unchained.bundles.api.extensions

Api

The Api extension.

Marshmallow

The Marshmallow extension.

flask_unchained.bundles.api.hooks

RegisterModelResourcesHook

Registers ModelResources and configures ModelSerializers on them.

RegisterModelSerializersHook

Registers ModelSerializers.

flask_unchained.bundles.api.model_resource

ModelResource

Base class for model resources.

flask_unchained.bundles.api.model_serializer

ModelSerializer

Base class for SQLAlchemy model serializers.

ApiBundle

class flask_unchained.bundles.api.ApiBundle[source]

The API Bundle.

name: str = 'api_bundle'

The name of the API Bundle.

resources_by_model = None

Lookup of resource classes by class name.

serializers = None

Lookup of serializer classes by class name.

serializers_by_model = None

Lookup of serializer classes by model class name

create_by_model = None

Lookup of serializer classes by model class name, as set by @ma.serializer(create=True) (see serializer())

many_by_model = None

Lookup of serializer classes by model class name, as set by @ma.serializer(many=True) (see serializer())

after_init_app(app: flask_unchained.flask_unchained.FlaskUnchained)[source]

Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models.

Config

class flask_unchained.bundles.api.config.Config[source]

Default config settings for the API Bundle.

API_OPENAPI_VERSION = '3.0.2'
API_REDOC_SOURCE_URL = 'https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js'
API_TITLE = None
API_VERSION = 1
API_DESCRIPTION = None
API_APISPEC_PLUGINS = None
DUMP_KEY_FN()

An optional function to use for converting keys when dumping data to send over the wire. By default, we convert snake_case to camelCase.

LOAD_KEY_FN()

An optional function to use for converting keys received over the wire to the backend’s representation. By default, we convert camelCase to snake_case.

ACCEPT_HANDLERS = {'application/json': <function jsonify>}

Functions to use for converting response data for Accept headers.

Extensions

Api

class flask_unchained.bundles.api.Api[source]

The Api extension:

from flask_unchained.bundles.api import api

Allows interfacing with apispec.

register_serializer(serializer, name=None, **kwargs)[source]

Method to manually register a Serializer with APISpec.

Parameters
  • serializer

  • name

  • kwargs

register_model_resource(resource: flask_unchained.bundles.api.model_resource.ModelResource)[source]

Method to manually register a ModelResource with APISpec.

Parameters

resource

register_field(field, *args)[source]

Register custom Marshmallow field.

Registering the Field class allows the Schema parser to set the proper type and format when documenting parameters from Schema fields.

Parameters

field (Field) – Marshmallow Field class

Param

args: - a pair of the form (type, format) to map to - a core marshmallow field type (then that type’s mapping is used)

Examples:

# Map to ('string', 'UUID')
api.register_field(UUIDField, 'string', 'UUID')
# Map to ('string')
api.register_field(URLField, 'string', None)
# Map to ('integer, 'int32')
api.register_field(CustomIntegerField, ma.fields.Integer)

Marshmallow

class flask_unchained.bundles.api.Marshmallow[source]

The Marshmallow extension:

from flask_unchained.bundles.api import ma

Allows decorating a ModelSerializer with serializer() to specify it should be used for creating objects, listing them, or as the fallback.

Also provides aliases from the following modules:

flask_unchained.bundles.api

ModelSerializer(*args, **kwargs)

Base class for SQLAlchemy model serializers.

marshmallow.decorators

pre_load([fn, pass_many])

Register a method to invoke before deserializing an object.

post_load([fn, pass_many, pass_original])

Register a method to invoke after deserializing an object.

pre_dump([fn, pass_many])

Register a method to invoke before serializing an object.

post_dump([fn, pass_many, pass_original])

Register a method to invoke after serializing an object.

validates(field_name)

Register a field validator.

validates_schema([fn, pass_many, …])

Register a schema-level validator.

marshmallow.exceptions

ValidationError(message[, field_name, data, …])

Raised when validation fails on a field or schema.

marshmallow.fields

Bool

alias of marshmallow.fields.Boolean

Boolean(*[, truthy, falsy])

A boolean field.

Constant(constant, **kwargs)

A field that (de)serializes to a preset constant.

Date([format])

ISO8601-formatted date string.

DateTime([format])

A formatted datetime string.

NaiveDateTime([format, timezone])

A formatted naive datetime string.

AwareDateTime([format, default_timezone])

A formatted aware datetime string.

Decimal([places, rounding, allow_nan, as_string])

A field that (de)serializes to the Python decimal.Decimal type.

Dict([keys, values])

A dict field.

Email(*args, **kwargs)

An email field.

Field(*[, default, missing, data_key, …])

Basic field from which other fields should extend.

Float(*[, allow_nan, as_string])

A double as an IEEE-754 double precision string.

Function([serialize, deserialize])

A field that takes the value returned by a function.

Int

alias of marshmallow.fields.Integer

Integer(*[, strict])

An integer field.

List(cls_or_instance, **kwargs)

A list field, composed with another Field class or instance.

Mapping([keys, values])

An abstract class for objects with key-value pairs.

Method([serialize, deserialize])

A field that takes the value returned by a Schema method.

Nested(nested, *[, default, only, exclude, …])

Allows you to nest a Schema inside a field.

Number(*[, as_string])

Base class for number fields.

Pluck(nested, field_name, **kwargs)

Allows you to replace nested data with one of the data’s fields.

Raw(*[, default, missing, data_key, …])

Field that applies no formatting.

Str

alias of marshmallow.fields.String

String(*[, default, missing, data_key, …])

A string field.

Time([format])

A formatted time string.

TimeDelta([precision])

A field that (de)serializes a datetime.timedelta object to an integer and vice versa.

Tuple(tuple_fields, *args, **kwargs)

A tuple field, composed of a fixed number of other Field classes or instances

UUID(*[, default, missing, data_key, …])

A UUID field.

Url(*[, relative, schemes, require_tld])

An URL field.

URL

alias of marshmallow.fields.Url

flask_marshmallow.fields

AbsoluteUrlFor

alias of flask_marshmallow.fields.AbsoluteURLFor

AbsoluteURLFor(endpoint[, values])

Field that outputs the absolute URL for an endpoint.

UrlFor

alias of flask_marshmallow.fields.URLFor

URLFor(endpoint[, values])

Field that outputs the URL for an endpoint.

Hyperlinks(schema, **kwargs)

Field that outputs a dictionary of hyperlinks, given a dictionary schema with URLFor objects as values.

flask_marshmallow.sqla

HyperlinkRelated(endpoint[, url_key, external])

Field that generates hyperlinks to indicate references between models, rather than primary keys.

serializer(create=False, many=False)[source]

Decorator to mark a Serializer subclass for a specific purpose, ie, to be used during object creation or for serializing lists of objects.

Parameters
  • create – Whether or not this serializer is for object creation.

  • many – Whether or not this serializer is for lists of objects.

Hooks

RegisterModelResourcesHook

class flask_unchained.bundles.api.hooks.RegisterModelResourcesHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Registers ModelResources and configures ModelSerializers on them.

name: str = 'model_resources'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['views']

The default module this hook loads from.

Override by setting the model_resources_module_names attribute on your bundle class.

process_objects(app, objects)[source]

Configures ModelSerializers on ModelResources.

type_check(obj)[source]

Returns True if obj is a subclass of ModelResource.

RegisterModelSerializersHook

class flask_unchained.bundles.api.hooks.RegisterModelSerializersHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Registers ModelSerializers.

name: str = 'model_serializers'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['serializers']

The default module this hook loads from.

Override by setting the model_serializers_module_names attribute on your bundle class.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, serializers: Dict[str, Type[flask_unchained.bundles.api.model_serializer.ModelSerializer]]) → None[source]

Registers model serializers onto the API Bundle instance.

type_check(obj: Any) → bool[source]

Returns True if obj is a subclass of ModelSerializer.

update_shell_context(ctx: Dict[str, Any]) → None[source]

Adds model serializers to the CLI shell context.

ModelResource

class flask_unchained.bundles.api.ModelResource[source]

Base class for model resources. This is intended for building RESTful APIs with SQLAlchemy models and Marshmallow serializers.

list(instances)[source]

List model instances.

Parameters

instances – The list of model instances.

Returns

The list of model instances.

create(instance, errors)[source]

Create an instance of a model.

Parameters
  • instance – The created model instance.

  • errors – Any errors.

Returns

The created model instance, or a dictionary of errors.

get(instance)[source]

Get an instance of a model.

Parameters

instance – The model instance.

Returns

The model instance.

patch(instance, errors)[source]

Partially update a model instance.

Parameters
  • instance – The model instance.

  • errors – Any errors.

Returns

The updated model instance, or a dictionary of errors.

put(instance, errors)[source]

Update a model instance.

Parameters
  • instance – The model instance.

  • errors – Any errors.

Returns

The updated model instance, or a dictionary of errors.

delete(instance)[source]

Delete a model instance.

Parameters

instance – The model instance.

Returns

HTTPStatus.NO_CONTENT

created(instance, commit=True)[source]

Convenience method for saving a model (automatically commits it to the database and returns the object with an HTTP 201 status code)

deleted(instance)[source]

Convenience method for deleting a model (automatically commits the delete to the database and returns with an HTTP 204 status code)

updated(instance)[source]

Convenience method for updating a model (automatically commits it to the database and returns the object with with an HTTP 200 status code)

ModelSerializer

class flask_unchained.bundles.api.ModelSerializer(*args, **kwargs)[source]

Base class for SQLAlchemy model serializers. This is pretty much a stock flask_marshmallow.sqla.ModelSchema, except:

  • dependency injection is set up automatically on ModelSerializer

  • when loading to update an existing instance, validate the primary keys are the same

  • automatically make fields named slug, model.Meta.created_at, and model.Meta.updated_at dump-only

For example:

from flask_unchained.bundles.api import ModelSerializer
from flask_unchained.bundles.security.models import Role

class RoleSerializer(ModelSerializer):
    class Meta:
        model = Role

Is roughly equivalent to:

from marshmallow import Schema, fields

class RoleSerializer(Schema):
    id = fields.Integer(dump_only=True)
    name = fields.String()
    description = fields.String()
    created_at = fields.DateTime(dump_only=True)
    updated_at = fields.DateTime(dump_only=True)
OPTIONS_CLASS

alias of ModelSerializerOptionsClass

is_create()[source]

Check if we’re creating a new object. Note that this context flag must be set from the outside, ie when the class gets instantiated.

load(data: Mapping, *, many: bool = None, partial: Union[bool, Sequence[str], Set[str]] = None, unknown: str = None, **kwargs)[source]

Deserialize a dict to an object defined by this ModelSerializer’s fields.

A ValidationError is raised if invalid data is passed.

Parameters
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

Returns

Deserialized data

dump(obj, *, many: bool = None)[source]

Serialize an object to native Python data types according to this ModelSerializer’s fields.

Parameters
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns

A dict of serialized data

Return type

dict

handle_error(error: marshmallow.exceptions.ValidationError, data: Any, **kwargs) → None[source]

Customize the error messages for required/not-null validators with dynamically generated field names. This is definitely a little hacky (it mutates state, uses hardcoded strings), but unsure how better to do it