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>=3.13.0.

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 load_default attribute of the Field (unless load_default is a callable). Since default values are entered in deserialized form, the value displayed in the doc 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 default as field 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(metadata={"description": "The user's name"})
    created = fields.DateTime(
        dump_only=True,
        dump_default=dt.datetime.utcnow,
        metadata={"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': {'readOnly': True,
#                                 'type': 'integer'},
#                          'name': {'description': "The user's name",
#                                   'type': 'string'}},
#           'type': 'object'}}
class apispec.ext.marshmallow.MarshmallowPlugin(schema_name_resolver: Callable[[type[Schema]], str] | None = 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 OpenAPIConverter

Resolver

alias of SchemaResolver

header_helper(header: dict, **kwargs: Any)[source]

Header component helper that allows using a marshmallow Schema in header definition.

Parameters:

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

init_spec(spec: APISpec) None[source]

Initialize plugin with APISpec object

Parameters:

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

map_to_openapi_type(field_cls, *args)[source]

Set mapping for custom field class.

Parameters:

field_cls (type) – Field class to set mapping for.

*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:

# Override Integer mapping
class Int32(Integer):
    # ...

ma_plugin.map_to_openapi_type(Int32, 'string', 'int32')

# Map to ('integer', None) like Integer
class IntegerLike(Integer):
    # ...

ma_plugin.map_to_openapi_type(IntegerLike, Integer)
operation_helper(path: str | None = None, operations: dict | None = None, **kwargs: Any) None[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: tuple) None[source]

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

apispec.ext.marshmallow.resolver(schema: type[Schema]) str[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_callback(callbacks)[source]

Resolve marshmallow Schemas in a dict mapping callback name to OpenApi `Callback Object https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#callbackObject`_.

This is done recursively, so it is possible to define callbacks in your callbacks.

Example:

#Input
{
    "userEvent": {
        "https://my.example/user-callback": {
            "post": {
                "requestBody": {
                    "content": {
                        "application/json": {
                            "schema": UserSchema
                        }
                    }
                }
            },
        }
    }
}

#Output
{
    "userEvent": {
        "https://my.example/user-callback": {
            "post": {
                "requestBody": {
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/User"
                            }
                        }
                    }
                }
            },
        }
    }
}
resolve_operations(operations, **kwargs)[source]

Resolve marshmallow Schemas in a dict mapping operation to OpenApi `Operation Object https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject`_

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"}},
    {"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 a schema reference 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: Version | str, schema_name_resolver, spec: APISpec)[source]

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

Parameters:
  • openapi_version (Version|str) – 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

add_parameter_attribute_function(func) None[source]

Method to add a field parameter function to the list of field parameter functions that will be called on a field to convert it to a field parameter.

Parameters:

func (func) – the field parameter 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. May mutate ret. User added field parameter functions will be called after all built-in field parameter functions in the order they were added.

field2required(field: Field, **kwargs: Any) dict[source]

Return the dictionary of OpenAPI parameter attributes for a required field.

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

fields2jsonschema(fields, *, 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

  • 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

get_ref_dict(schema)[source]

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

list2param(field: Field, **kwargs: Any) dict[source]

Return a dictionary of parameter properties from List <marshmallow.fields.List fields.

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

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 dictionary 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, *, location, name: str = 'body', required: bool = False, description: str | None = None)[source]

Return an array of OpenAPI parameters given a given marshmallow Schema. If location 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 OpenAPI 3, only “query”, “header”, “path” or “cookie” are allowed for the location of parameters. “requestBody” is used when fields are in the body.

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 accessible via the ret argument.

datetime2properties(field, **kwargs: Any) dict[source]

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

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

dict2properties(field, **kwargs: Any) dict[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

enum2properties(field, **kwargs: Any) dict[source]

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

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

field2choices(field: Field, **kwargs: Any) dict[source]

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

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

field2default(field: Field, **kwargs: Any) dict[source]

Return the dictionary containing the field’s default value.

Will first look for a 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: Field, **kwargs: Any) dict[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: Field, ret) dict[source]

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

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

field2pattern(field: Field, **kwargs: Any) dict[source]

Return the dictionary of OpenAPI field attributes for a Regexp validator.

If there is more than one such validator, only the first is used in the output spec.

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

field2property(field: Field) dict[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: Field, ret) dict[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: Field, **kwargs: Any) dict[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: Field, **kwargs: Any) dict[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: Field, **kwargs: Any) dict[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: Any) dict[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(field_cls, *args)[source]

Set mapping for custom field class.

Parameters:

field_cls (type) – Field class to set mapping for.

*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: Field, **kwargs: Any) dict[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: Field, ret) dict[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

pluck2properties(field, **kwargs: Any) dict[source]

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

Pluck effectively trans-includes a field from another schema into this, possibly wrapped in an array (many=True).

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

timedelta2properties(field, **kwargs: Any) dict[source]

Return a dictionary of properties from TimeDelta fields.

Adds a x-unit vendor property based on the field’s precision attribute

Parameters:

field (Field) – A marshmallow field.

Return type:

dict

apispec.ext.marshmallow.field_converter.make_min_max_attributes(validators, min_attr, max_attr) dict[source]

Return a dictionary of minimum and maximum attributes based on a list of validators. If either minimum or maximum values are not present in any of the validator objects that attribute will be omitted.

Parameters:
  • list (validators) – A list of Marshmallow validator objects. Each objct is inspected for a minimum and maximum values

  • string (max_attr) – The OpenAPI attribute for the minimum value

  • string – The OpenAPI attribute for the maximum value

apispec.ext.marshmallow.field_converter.make_type_list(types)[source]

Return a list of types from a type attribute

Since OpenAPI 3.1.0, “type” can be a single type as string or a list of types, including ‘null’. This function takes a “type” attribute as input and returns it as a list, be it an empty or single-element list. This is useful to factorize type-conditional code or code adding a type.

apispec.ext.marshmallow.common

Utilities to get schema instances/classes

apispec.ext.marshmallow.common.filter_excluded_fields(fields: dict[str, Field], Meta, *, exclude_dump_only: bool) dict[str, Field][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 dump_only fields

apispec.ext.marshmallow.common.get_fields(schema: type[Schema] | Schema, *, exclude_dump_only: bool = False) dict[str, Field][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: Components, name: str, counter: int = 0) str[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: type[Schema] | str | Schema) type[Schema] | list[type[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: type[Schema] | Schema | str) 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: dict[str, Field], 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