apispec-oneofschema

3.0.2 · active · verified Thu Apr 16

apispec-oneofschema is a plugin for apispec that extends its functionality to provide support for Marshmallow-OneOfSchema schemas. It enables the generation of OpenAPI documentation for polymorphic schemas defined using marshmallow-oneofschema. The current version is 3.0.2, and it is actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a polymorphic schema using `marshmallow-oneofschema.OneOfSchema` and then integrate it with `apispec` using `apispec-oneofschema.MarshmallowPlugin` to generate an OpenAPI specification. Ensure `openapi_version` is set to '3.0.0' or greater.

from apispec import APISpec
from marshmallow import Schema, fields
from marshmallow_oneofschema import OneOfSchema
from apispec_oneofschema import MarshmallowPlugin

class TreeSchema(Schema):
    leaves = fields.Int(required=True)

class FlowerSchema(Schema):
    blooming = fields.Bool(required=True)

class PlantSchema(OneOfSchema):
    type_schemas = {
        'tree': TreeSchema,
        'flower': FlowerSchema
    }

spec = APISpec(
    title='Botany',
    version='1.0.0',
    openapi_version='3.0.0', # Must be 3.0.0 or greater
    plugins=[
        MarshmallowPlugin(),
    ]
)

spec.components.schema('Plant', schema=PlantSchema)
spec.components.schema('Tree', schema=TreeSchema)
spec.components.schema('Flower', schema=FlowerSchema)

# Optional: Add schemas that are part of OneOfSchema directly to components
# spec.components.schema('Tree', schema=TreeSchema)
# spec.components.schema('Flower', schema=FlowerSchema)

print(spec.to_yaml())

view raw JSON →