Field types

Raw field class

class fields.Raw(schema, io='rw', default=None, attribute=None, nullable=False, title=None, description=None)

This is the base class for all field types, can be given any JSON-schema.

>>> f = fields.Raw({"type": "string"}, io="r")
>>> f.response
{'readOnly': True, 'type': 'string'}
Parameters:
  • io – one or more of “r” (read), “c” (create), “u” (update) and “w” (write), default: “rw”; used to control presence in fieldsets/parent schemas
  • schema – JSON-schema for field, or callable resolving to a JSON-schema when called
  • default – optional default value, must be JSON-convertible; may be a callable with no arguments
  • attribute – key on parent object, optional.
  • nullable – whether the field is nullable.
  • title – optional title for JSON schema
  • description – optional description for JSON schema
schema()

JSON schema representation

format(value)

Format a Python value representation for output in JSON. Noop by default.

convert(instance, update=False, validate=True)

Convert a JSON value representation to a Python object. Noop by default.

Reference field types

class fields.ToOne(resource, **kwargs)

Represents references between resources as json-ref objects.

Resource references can be one of the following:

  • Resource class
  • a string with a resource name
  • a string with a module name and class name of a resource
  • "self" — which resolves to the resource this field is bound to
Parameters:resource – a resource reference
class fields.ToMany(resource, **kwargs)

Like ToOne, but for arrays of references.

Basic field types

class fields.Any(**kwargs)

A field type that allows any value.

class fields.String(min_length=None, max_length=None, pattern=None, enum=None, format=None, **kwargs)
Parameters:
  • min_length (int) – minimum length of string
  • max_length (int) – maximum length of string
  • pattern (str) – regex pattern that the string must match
  • format (str) –

    a JSON Schema format string to validate against

    Warning

    The validation of format-strings is handled by jsonschema and may require additional package dependencies.

  • enum (list) – list of strings with enumeration
class fields.Integer(minimum=None, maximum=None, default=None, **kwargs)
class fields.PositiveInteger(maximum=None, **kwargs)

A Integer field that only accepts integers >=1.

class fields.Number(minimum=None, maximum=None, exclusive_minimum=False, exclusive_maximum=False, **kwargs)
class fields.Boolean(**kwargs)
class fields.Date(**kwargs)

A field for EJSON-style dates in the format:

{"$date": MILLISECONDS_SINCE_EPOCH}

Converts to datetime.date with UTC timezone.

class fields.DateTime(**kwargs)

A field for EJSON-style date-times in the format:

{"$date": MILLISECONDS_SINCE_EPOCH}

Converts to datetime.datetime with UTC timezone.

class fields.DateString(**kwargs)

A field for ISO8601-formatted date strings.

class fields.DateTimeString(**kwargs)

A field for ISO8601-formatted date-time strings.

class fields.Uri(**kwargs)
class fields.UUID(**kwargs)

A field for UUID strings in canonical form.

class fields.Object(properties=None, pattern=None, pattern_properties=None, additional_properties=None, **kwargs)

A versatile field for an object, containing either properties all of a single type, properties matching a pattern, or named properties matching some fields.

Raw.attribute is not used in pattern properties and additional properties.

Parameters:
  • properties – field class, instance, or dictionary of {property: field} pairs
  • pattern (str) – an optional regular expression that all property keys must match
  • pattern_properties (dict) – dictionary of {property: field} pairs
  • additional_properties (Raw) – field class or instance
class fields.Object(properties=None, pattern=None, pattern_properties=None, additional_properties=None, **kwargs)

A versatile field for an object, containing either properties all of a single type, properties matching a pattern, or named properties matching some fields.

Raw.attribute is not used in pattern properties and additional properties.

Parameters:
  • properties – field class, instance, or dictionary of {property: field} pairs
  • pattern (str) – an optional regular expression that all property keys must match
  • pattern_properties (dict) – dictionary of {property: field} pairs
  • additional_properties (Raw) – field class or instance
class fields.Custom(schema, converter=None, formatter=None, **kwargs)

A field type that can be passed any schema and optional formatter/converter transformers. It is a very thin wrapper over Raw.

Parameters:
  • schema (dict) – JSON-schema
  • converter (callable) – convert function
  • formatter (callable) – format function

Composite field types

class fields.Array(cls_or_instance, min_items=None, max_items=None, unique=None, **kwargs)

A field for an array of a given field type.

Parameters:
  • cls_or_instance (Raw) – field class or instance
  • min_items (int) – minimum number of items
  • max_items (int) – maximum number of items
  • unique (bool) – if True, all values in the list must be unique
class fields.Object(properties=None, pattern=None, pattern_properties=None, additional_properties=None, **kwargs)

A versatile field for an object, containing either properties all of a single type, properties matching a pattern, or named properties matching some fields.

Raw.attribute is not used in pattern properties and additional properties.

Parameters:
  • properties – field class, instance, or dictionary of {property: field} pairs
  • pattern (str) – an optional regular expression that all property keys must match
  • pattern_properties (dict) – dictionary of {property: field} pairs
  • additional_properties (Raw) – field class or instance
class fields.AttributeMapped(cls_or_instance, mapping_attribute=None, **kwargs)

Maps property keys from a JSON object to a list of items using mapping_attribute. The mapping attribute is the name of the attribute where the value of the property key is set on the property values.

contrib.alchemy.fields.InlineModel is typically used with this field in a common SQLAlchemy pattern.

Parameters:
  • cls_or_instance (Raw) – field class or instance
  • pattern (str) – an optional regular expression that all property keys must match
  • mapping_attribute (str) – mapping attribute

SQLAlchemy-specific field types

class contrib.alchemy.fields.InlineModel

Changed in version 0.11: Renamed from fields.sa.InlineModel to contrib.alchemy.fields.InlineModel.

For creating SQLAlchemy models without having to give them their own resource.

Usage example:

class FooResource(Resource):
   class Meta:
      model = Foo

   class Schema:
      # Here, Foo.bars is a collection of Bar items
      bars = fields.List(fields.InlineModel({
          "name": fields.String(description="Bar name"),
          "height": fields.Integer(description="Height of bar")
      }, model=Bar))
Parameters:
  • properties (dict) – A dictionary of Raw objects
  • model – An SQLAlchemy model

Internal types

Field types

class fields.Inline(resource, patchable=False, **kwargs)

Formats and converts items in a ModelResource using the resource’s schema.

Parameters:
  • resource – a resource reference as in ToOne
  • patchable (bool) – whether to allow partial objects
class fields.ItemType(resource)

A string field that formats the name of a resource; read-only.

class fields.ItemUri(resource, attribute=None)

A string field that formats the url of a resource item; read-only.

Schema types

class schema.Schema

The base class for all types with a schema in Potion. Has response and a request attributes for the schema to be used, respectively, for serializing and de-serializing.

Any class inheriting from schema needs to implement schema().

response

JSON-schema used to represent data returned by the server.

request

JSON-schema used for validation of data sent to the server.

schema()

Abstract method returning the JSON schema used by both response and request.

Returns:a JSON-schema or a tuple of JSON-schemas in the formats (response_schema, request_schema) or (read_schema, create_schema, update_schema)
format(value)

Formats a python object for JSON serialization. Noop by default.

Parameters:value (object) –
Returns:
convert(instance, update=False)

Validates a deserialized JSON object against request and converts it into a python object.

Parameters:instance – JSON import
Raises:PotionValidationError – if validation failed
parse_request(request)

Parses a Flask request object, validates it the against request and returns the converted request data.

Parameters:request – Flask request object
Returns:
format_response(response)

Takes a response value, which can be a data object or a tuple (data, code) or (data, code, headers) and formats it using format().

Parameters:response – A response tuple.
Returns:A tuple in the form (data, code, headers)
class schema.FieldSet(fields, required_fields=None)

A schema representation of a dictionary of fields.Raw objects.

Uses the fields’ io attributes to determine whether they are read-only, write-only, or read-write.

Parameters:
  • fields (dict) – a dictionary of fields.Raw objects
  • required_fields – a list or tuple of field names that are required during parsing
convert(instance, update=False, pre_resolved_properties=None, patchable=False, strict=False)
Parameters:
  • instance – JSON-object
  • pre_resolved_properties – optional dictionary of properties that are already known
  • patchable (bool) – when True does not check for required fields
  • strict (bool) –
Returns: