Built-in Plugins

apispec.ext.marshmallow

marshmallow plugin for apispec. Allows passing a marshmallow Schema to spec.components.schema, spec.components.parameter, spec.components.response (for response and headers schemas) and spec.path (for responses and response headers).

Requires marshmallow>=2.15.2.

MarshmallowPlugin maps marshmallow Field classes with OpenAPI types and formats.

It inspects field attributes to automatically document properties such as read/write-only, range and length constraints, etc.

OpenAPI properties can also be passed as metadata to the Field instance if they can’t be inferred from the field attributes (description,…), or to override automatic documentation (readOnly,…). A metadata attribute is used in the documentation either if it is a valid OpenAPI property, or if it starts with "x-" (vendor extension).

Warning

MarshmallowPlugin infers the default property from the missing attribute of the Field (unless missing is a callable). In marshmallow 3, default values are entered in deserialized form, so the value is serialized by the Field instance. This may lead to inaccurate documentation in very specific cases. The default value to display in the documentation can be specified explicitly by passing doc_default as metadata.

from pprint import pprint
import datetime as dt

from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow import Schema, fields

spec = APISpec(
    title="Example App",
    version="1.0.0",
    openapi_version="3.0.2",
    plugins=[MarshmallowPlugin()],
)


class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str(description="The user's name")
    created = fields.DateTime(
        dump_only=True, default=dt.datetime.utcnow, doc_default="The current datetime"
    )


spec.components.schema("User", schema=UserSchema)
pprint(spec.to_dict()["components"]["schemas"])
# {'User': {'properties': {'created': {'default': 'The current datetime',
#                                      'format': 'date-time',
#                                      'readOnly': True,
#                                      'type': 'string'},
#                          'id': {'format': 'int32',
#                                 'readOnly': True,
#                                 'type': 'integer'},
#                          'name': {'description': "The user's name",
#                                   'type': 'string'}},
#           'type': 'object'}}
class apispec.ext.marshmallow.MarshmallowPlugin(schema_name_resolver=None)[source]

APISpec plugin for translating marshmallow schemas to OpenAPI/JSONSchema format.

Parameters

schema_name_resolver (callable) –

Callable to generate the schema definition name. Receives the Schema class and returns the name to be used in refs within the generated spec. When working with circular referencing this function must must not return None for schemas in a circular reference chain.

Example:

from apispec.ext.marshmallow.common import resolve_schema_cls

def schema_name_resolver(schema):
    schema_cls = resolve_schema_cls(schema)
    return schema_cls.__name__

Converter

alias of apispec.ext.marshmallow.openapi.OpenAPIConverter

Resolver

alias of apispec.ext.marshmallow.schema_resolver.SchemaResolver

init_spec(spec)[source]

Initialize plugin with APISpec object

Parameters

spec (APISpec) – APISpec object this plugin instance is attached to

map_to_openapi_type(*args)[source]

Decorator to set mapping for custom fields.

*args can be:

  • a pair of the form (type, format)

  • a core marshmallow field type (in which case we reuse that type’s mapping)

Examples:

@ma_plugin.map_to_openapi_type('string', 'uuid')
class MyCustomField(Integer):
    # ...

@ma_plugin.map_to_openapi_type(Integer)  # will map to ('integer', 'int32')
class MyCustomFieldThatsKindaLikeAnInteger(Integer):
    # ...
operation_helper(operations, **kwargs)[source]

May mutate operations.

Parameters
parameter_helper(parameter, **kwargs)[source]

Parameter component helper that allows using a marshmallow Schema in parameter definition.

Parameters

parameter (dict) – parameter fields. May contain a marshmallow Schema class or instance.

response_helper(response, **kwargs)[source]

Response component helper that allows using a marshmallow Schema in response definition.

Parameters

parameter (dict) – response fields. May contain a marshmallow Schema class or instance.

schema_helper(name, _, schema=None, **kwargs)[source]

Definition helper that allows using a marshmallow Schema to provide OpenAPI metadata.

Parameters

schema (type|Schema) – A marshmallow Schema class or instance.

warn_if_schema_already_in_spec(schema_key)[source]

Method to warn the user if the schema has already been added to the spec.

apispec.ext.marshmallow.resolver(schema)[source]

Default schema name resolver function that strips ‘Schema’ from the end of the class name.

apispec.ext.marshmallow.schema_resolver

class apispec.ext.marshmallow.schema_resolver.SchemaResolver(openapi_version, converter)[source]

Resolve marshmallow Schemas in OpenAPI components and translate to OpenAPI schema objects, parameter objects or reference objects.

resolve_parameters(parameters)[source]

Resolve marshmallow Schemas in a list of OpenAPI Parameter Objects. Each parameter object that contains a Schema will be translated into one or more Parameter Objects.

If the value of a schema key is marshmallow Schema class, instance or a string that resolves to a Schema Class each field in the Schema will be expanded as a separate Parameter Object.

Example:

#Input
class UserSchema(Schema):
    name = fields.String()
    id = fields.Int()

[
    {"in": "query", "schema": "UserSchema"}
]

#Output
[
    {"in": "query", "name": "id", "required": False, "schema": {"type": "integer", "format": "int32"}},
    {"in": "query", "name": "name", "required": False, "schema": {"type": "string"}}
]

If the Parameter Object contains a content key a single Parameter Object is returned with the Schema translated into a Schema Object or Reference Object.

Example:

#Input
[{"in": "query", "name": "pet", "content":{"application/json": {"schema": "PetSchema"}} }]

#Output
[
    {
        "in": "query",
        "name": "pet",
        "content": {
            "application/json": {
                "schema": {"$ref": "#/components/schemas/Pet"}
            }
        }
    }
]
Parameters

parameters (list) – the list of OpenAPI parameter objects to resolve.

resolve_response(response)[source]

Resolve marshmallow Schemas in OpenAPI Response Objects. Schemas may appear in either a Media Type Object or a Header Object.

Example:

#Input
{
    "content": {"application/json": {"schema": "PetSchema"}},
    "description": "successful operation",
    "headers": {"PetHeader": {"schema": "PetHeaderSchema"}},
}

#Output
{
    "content": {
        "application/json":{"schema": {"$ref": "#/components/schemas/Pet"}}
    },
    "description": "successful operation",
    "headers": {
        "PetHeader": {"schema": {"$ref": "#/components/schemas/PetHeader"}}
    },
}
Parameters

response (dict) – the response object to resolve.

resolve_schema(data)[source]

Resolve marshmallow Schemas in an OpenAPI component or header - modifies the input dictionary to translate marshmallow Schemas to OpenAPI Schema Objects or Reference Objects.

OpenAPIv3 Components:

#Input
{
    "description": "user to add to the system",
    "content": {
        "application/json": {
            "schema": "UserSchema"
        }
    }
}

#Output
{
    "description": "user to add to the system",
    "content": {
        "application/json": {
            "schema": {
                "$ref": "#/components/schemas/User"
            }
        }
    }
}
Parameters

data (dict|str) – either a parameter or response dictionary that may contain a schema, or a reference provided as string

resolve_schema_dict(schema)[source]

Resolve a marshmallow Schema class, object, or a string that resolves to a Schema class or an OpenAPI Schema Object containing one of the above to an OpenAPI Schema Object or Reference Object.

If the input is a marshmallow Schema class, object or a string that resolves to a Schema class the Schema will be translated to an OpenAPI Schema Object or Reference Object.

Example:

#Input
"PetSchema"

#Output
{"$ref": "#/components/schemas/Pet"}

If the input is a dictionary representation of an OpenAPI Schema Object recursively search for a marshmallow Schemas to resolve. For "type": "array", marshmallow Schemas may appear as the value of the items key. For "type": "object" Marshmalow Schemas may appear as values in the properties dictionary.

Examples:

#Input
{"type": "array", "items": "PetSchema"}

#Output
{"type": "array", "items": {"$ref": "#/components/schemas/Pet"}}

#Input
{"type": "object", "properties": {"pet": "PetSchcema", "user": "UserSchema"}}

#Output
{
    "type": "object",
    "properties": {
        "pet": {"$ref": "#/components/schemas/Pet"},
        "user": {"$ref": "#/components/schemas/User"}
    }
}
Parameters

schema (string|Schema|dict) – the schema to resolve.

apispec.ext.marshmallow.openapi

Utilities for generating OpenAPI Specification (fka Swagger) entities from marshmallow Schemas and Fields.

Warning

This module is treated as private API. Users should not need to use this module directly.

class apispec.ext.marshmallow.openapi.OpenAPIConverter(openapi_version, schema_name_resolver, spec)[source]

Adds methods for generating OpenAPI specification from marshmallow schemas and fields.

Parameters
  • openapi_version (str|OpenAPIVersion) – The OpenAPI version to use. Should be in the form ‘2.x’ or ‘3.x.x’ to comply with the OpenAPI standard.

  • schema_name_resolver (callable) – Callable to generate the schema definition name. Receives the Schema class and returns the name to be used in refs within the generated spec. When working with circular referencing this function must must not return None for schemas in a circular reference chain.

  • spec (APISpec) – An initalied spec. Nested schemas will be added to the spec

field2parameter(field, *, name, default_in)[source]

Return an OpenAPI parameter as a dict, given a marshmallow Field.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject

fields2jsonschema(fields, *, ordered=False, partial=None)[source]

Return the JSON Schema Object given a mapping between field names and Field objects.

Parameters
  • fields (dict) – A dictionary of field name field object pairs

  • ordered (bool) – Whether to preserve the order in which fields were declared

  • partial (bool|tuple) – Whether to override a field’s required flag. If True no fields will be set as required. If an iterable fields in the iterable will not be marked as required.

Return type

dict, a JSON Schema Object

fields2parameters(fields, *, default_in)[source]

Return an array of OpenAPI parameters given a mapping between field names and Field objects. If default_in is “body”, then return an array of a single parameter; else return an array of a parameter for each included field in the Schema.

In OpenAPI3, only “query”, “header”, “path” or “cookie” are allowed for the location of parameters. In OpenAPI 3, “requestBody” is used when fields are in the body.

This function always returns a list, with a parameter for each included field in the Schema.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject

get_ref_dict(schema)[source]

Method to create a dictionary containing a JSON reference to the schema in the spec

property2parameter(prop, *, name, required, multiple, location, default_in)[source]

Return the Parameter Object definition for a JSON Schema property.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject

Parameters
  • prop (dict) – JSON Schema property

  • name (str) – Field name

  • required (bool) – Parameter is required

  • multiple (bool) – Parameter is repeated

  • location (str) – Location to look for name

  • default_in (str) – Default location to look for name

Raise

TranslationError if arg object cannot be translated to a Parameter Object schema.

Return type

dict, a Parameter Object

resolve_nested_schema(schema)[source]

Return the OpenAPI representation of a marshmallow Schema.

Adds the schema to the spec if it isn’t already present.

Typically will return a dictionary with the reference to the schema’s path in the spec unless the schema_name_resolver returns None, in which case the returned dictoinary will contain a JSON Schema Object representation of the schema.

Parameters

schema – schema to add to the spec

schema2jsonschema(schema)[source]

Return the JSON Schema Object for a given marshmallow Schema instance. Schema may optionally provide the title and description class Meta options.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject

Parameters

schema (Schema) – A marshmallow Schema instance

Return type

dict, a JSON Schema Object

schema2parameters(schema, *, default_in='body', name='body', required=False, description=None)[source]

Return an array of OpenAPI parameters given a given marshmallow Schema. If default_in is “body”, then return an array of a single parameter; else return an array of a parameter for each included field in the Schema.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject

apispec.ext.marshmallow.field_converter

Utilities for generating OpenAPI Specification (fka Swagger) entities from Fields.

Warning

This module is treated as private API. Users should not need to use this module directly.

class apispec.ext.marshmallow.field_converter.FieldConverterMixin[source]

Adds methods for converting marshmallow fields to an OpenAPI properties.

add_attribute_function(func)[source]

Method to add an attribute function to the list of attribute functions that will be called on a field to convert it from a field to an OpenAPI property.

Parameters

func (func) – the attribute function to add The attribute function will be bound to the OpenAPIConverter instance. It will be called for each field in a schema with self and a field instance positional arguments and ret keyword argument. Must return a dictionary of OpenAPI properties that will be shallow merged with the return values of all other attribute functions called on the field. User added attribute functions will be called after all built-in attribute functions in the order they were added. The merged results of all previously called attribute functions are accessable via the ret argument.

dict2properties(field, **kwargs)[source]

Return a dictionary of properties from Dict fields.

Only applicable for Marshmallow versions greater than 3. Will provide an additionalProperties property based on the field’s value_field attribute

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2choices(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for valid choices definition.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2default(field, **kwargs)[source]

Return the dictionary containing the field’s default value.

Will first look for a doc_default key in the field’s metadata and then fall back on the field’s missing parameter. A callable passed to the field’s missing parameter will be ignored.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2length(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a set of Length validators.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2nullable(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a nullable field.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2pattern(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a set of Range validators.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2property(field)[source]

Return the JSON Schema property definition given a marshmallow Field.

Will include field metadata that are valid properties of OpenAPI schema objects (e.g. “description”, “enum”, “example”).

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject

Parameters

field (Field) – A marshmallow field.

Return type

dict, a Property Object

field2range(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a set of Range validators.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2read_only(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a dump_only field.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2type_and_format(field, **kwargs)[source]

Return the dictionary of OpenAPI type and format based on the field type.

Parameters

field (Field) – A marshmallow field.

Return type

dict

field2write_only(field, **kwargs)[source]

Return the dictionary of OpenAPI field attributes for a load_only field.

Parameters

field (Field) – A marshmallow field.

Return type

dict

list2properties(field, **kwargs)[source]

Return a dictionary of properties from List fields.

Will provide an items property based on the field’s inner attribute

Parameters

field (Field) – A marshmallow field.

Return type

dict

map_to_openapi_type(*args)[source]

Decorator to set mapping for custom fields.

*args can be:

  • a pair of the form (type, format)

  • a core marshmallow field type (in which case we reuse that type’s mapping)

metadata2properties(field, **kwargs)[source]

Return a dictionary of properties extracted from field metadata.

Will include field metadata that are valid properties of OpenAPI schema objects (e.g. “description”, “enum”, “example”).

In addition, specification extensions are supported. Prefix x_ to the desired extension when passing the keyword argument to the field constructor. apispec will convert x_ to x- to comply with OpenAPI.

Parameters

field (Field) – A marshmallow field.

Return type

dict

nested2properties(field, ret)[source]

Return a dictionary of properties from Nested <marshmallow.fields.Nested fields.

Typically provides a reference object and will add the schema to the spec if it is not already present If a custom schema_name_resolver function returns None for the nested schema a JSON schema object will be returned

Parameters

field (Field) – A marshmallow field.

Return type

dict

apispec.ext.marshmallow.common

Utilities to get schema instances/classes

class apispec.ext.marshmallow.common.SchemaKey(SchemaClass, only, exclude, load_only, dump_only, partial)
property SchemaClass

Alias for field number 0

property dump_only

Alias for field number 4

property exclude

Alias for field number 2

property load_only

Alias for field number 3

property only

Alias for field number 1

property partial

Alias for field number 5

apispec.ext.marshmallow.common.filter_excluded_fields(fields, Meta, *, exclude_dump_only)[source]

Filter fields that should be ignored in the OpenAPI spec.

Parameters
  • fields (dict) – A dictionary of fields name field object pairs

  • Meta – the schema’s Meta class

  • exclude_dump_only (bool) – whether to filter fields in Meta.dump_only

apispec.ext.marshmallow.common.get_fields(schema, *, exclude_dump_only=False)[source]

Return fields from schema.

Parameters
  • schema (Schema) – A marshmallow Schema instance or a class object

  • exclude_dump_only (bool) – whether to filter fields in Meta.dump_only

Return type

dict, of field name field object pairs

apispec.ext.marshmallow.common.get_unique_schema_name(components, name, counter=0)[source]

Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec.

Parameters
  • components (Components) – instance of the components of the spec

  • name (string) – the name to use as a basis for the unique name

  • counter (int) – the counter of the number of recursions

Returns

the unique name

apispec.ext.marshmallow.common.resolve_schema_cls(schema)[source]

Return schema class for given schema (instance or class).

Parameters

type|Schema|str – instance, class or class name of marshmallow.Schema

Returns

schema class of given schema (instance or class)

apispec.ext.marshmallow.common.resolve_schema_instance(schema)[source]

Return schema instance for given schema (instance or class).

Parameters

schema (type|Schema|str) – instance, class or class name of marshmallow.Schema

Returns

schema instance of given schema (instance or class)

apispec.ext.marshmallow.common.warn_if_fields_defined_in_meta(fields, Meta)[source]

Warns user that fields defined in Meta.fields or Meta.additional will be ignored.

Parameters
  • fields (dict) – A dictionary of fields name field object pairs

  • Meta – the schema’s Meta class