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.

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 handling marshmallow schemas

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:

def schema_name_resolver(schema):
    return schema.__name__

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.

resolve_schema(data)[source]

Function to resolve a schema in a parameter or response - modifies the corresponding dict to convert Marshmallow Schema object or class into dict

Parameters
  • spec (APISpec) – APISpec containing refs.

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

resolve_schema_in_request_body(request_body)[source]

Function to resolve a schema in a requestBody object - modifies then response dict to convert Marshmallow Schema object or class into dict

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 implementation of a schema name resolver function

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]

Converter 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.

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)[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

field2parameter(field, name='body', default_in='body')[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

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)[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

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='body')[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

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)[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

property2parameter(prop, name='body', required=False, multiple=False, location=None, default_in='body')[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 Open API 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

resolve_schema_class(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)

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

Example:

class UserSchema(Schema):
    _id = fields.Int()
    email = fields.Email(description='email address of the user')
    name = fields.Str()

    class Meta:
        title = 'User'
        description = 'A registered user'

oaic = OpenAPIConverter(openapi_version='3.0.2', schema_name_resolver=resolver, spec=spec)
pprint(oaic.schema2jsonschema(UserSchema))
# {'description': 'A registered user',
#  'properties': {'_id': {'format': 'int32', 'type': 'integer'},
#                 'email': {'description': 'email address of the user',
#                           'format': 'email',
#                           'type': 'string'},
#                 'name': {'type': 'string'}},
#  'title': 'User',
#  'type': 'object'}
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