Package: pyramid-marshmallow
pyramid-marshmallowpyramid-marshmallow is a simple Pyramid plugin that allows you to validate and
marshal a JSON HTTP request or response usingMarshmallowschemas.  You can then
leverage this to automatically generate an OpenAPI specification for your API.Version 0.5 and greater requires Marshmallow 3.x.  For Marshmallow 2.x, use
version 0.4.Basic usageInstall the project withpip install pyramid-marshmallow.Activate it by addingconfig.include('pyramid_marshmallow')into your config
function or addingpyramid.includes = pyramid_marshmallowinto your ini file.To validate incoming data, setvalidateto a Marshmallow schema in yourview_config.  The request body is parsed as JSON then passed through the
schema'sloadfunction.  You can access the processed data withrequest.data.frommarshmallowimportSchema,StringclassHelloSchema(Schema):name=String()@view_config(context=Root,name='hello',request_method='post',validate=HelloSchema(),)defhello(context,request):returnResponse(body='Hello,{}'.format(request.data['name']))For GET requests, the URL parameters are passed into the schema.  Value lists
are not currently supported.Settingmarshalin yourview_configwill run the view output through
marshmallow (i.e.Schema.dump) before going to the renderer.  You probably
will want to set the renderer tojson.@view_config(
    context=Root,
    name='hello',
    request_method='get',
    marshal=HelloSchema(),
    renderer='json',
)
def hello(context, request):
    name = fetch_name()
    return {
        'name': name,
    }validateandmarshaloperate independently, so can be used separately or
together.As a convenience, you can pass in a dictionary tovalidateormarshaland
pyramid-marshmallow will turn it into a schema for you.@view_config(context=Root,name='hello',request_method='post',validate={'name':String(),},)You can also get a schema made from a dictionary by using thepyramid_marshmallow.make_schemafunction.  This can be useful forNestedfields.Error handlingpyramid-marshmallow passes through exceptions from marshmallow.  So errors
during validation will raise amarshmallow.exceptions.ValidationErrorexception.
(Documentation)You may want to attach a view to this exception to expose the error messages to
the user.@view_config(context=ValidationError,renderer='json',)defvalidation_error(context,request):request.response.status=401# HTTP Bad Requestreturn{'errors':context.normalized_messages(),}OpenAPIBy adding validation and marshalling to your views, we have the opportunity to
utilize that data to generate documentation.  pyramid-marshmallow includes an
utility that usesapispecto
generate anOpenAPIspecification for
your application.First, you'll need to install some extra dependencies.pipinstallpyramid-marshmallow[openapi]Now you can generate your spec by simply passing in an ini file.
pyramid-marshmallow needs to run your application in order to inspect it, so
the ini file should contain all the necessary configuration to do so.generate-specdevelopment.iniThis will output the spec to stdout as JSON.  You can set the--outputflag
to output the results to a file.You can set--format yamlto output the spec as YAML instead or--format htmlto output the spec as an HTML file, powered byReDoc.By default, your spec will be titled "Untitled" and versioned "0.1.0".  You can
change this by settingopenapi.titleandopenapi.versionin your ini file.Documenting Your APIDocumentation will be autogenerated from the structure of your Pyramid app and
yourvalidateandmarshaldeclarations.  You can document schema fields by
setting thedescriptionproperty.classHello(Schema):name=String(required=True,description='Your first and last name.')The first line of a view callable's docstring will be used as thesummaryproperty.  The following lines will be used for thedescription.Documentation for the endpoint will be pulled from the view callable's
docstring.  The first line becomes thesummaryand the remaining lines become
thedescription.You can also a line with three hyphens followed by a YAML object.  This will be
merged with the auto-generatedoperation objectand can
be used to manually augment the spec.@view_config(context=WidgetResource,method='post',validate=WidgetSchema(),)defcreate_widget(context,request):"""Create new widgetCreates a new widget with an attached plumbus.---responses:201:description: Indicates the widget was successfully created."""widget.make()returnHTTPCreated()You can also pass a dictionary as theapi_specproperty toConfigurator.add_viewor@view_config, which will be merged with the spec
in the same way.  This can be advantageous if a single function services
multiple views.@view_config(context=WidgetResource,method='post',validate=WidgetSchema(),api_spec={'summary':'Create widget',},)@view_config(context=WidgetResource,method='put',validate=WidgetSchema(),api_spec={'summary':'Update widget',},)defcreate_widget(context,request):"""Create/update new widget---responses:201:description: Indicates the widget was successfully created."""widget.create_or_update()returnHTTPCreated()URL TraversalIf you're using Pyramid's URL traversal, the generated spec may be mostly
empty.  This is because pyramid-marshmallow has no way of knowing where in the
resource tree a resource is.  You can denote this by setting the__path__property on each resource.classWidget(Resource):__path__='/widget'Views attached to this resource will then be added to the spec.You can add parameters to your path via the__params__property.  You can
also tag all attached views via__tag__.  Once you define a tag in one
resource, you can use it elsewhere by setting__tag__to the tag name.classWidget(Resource):__path__='/widget/{widgetId}'__params__=[{'name':'widgetId','schema':{'type':'integer',},}]__tag__={'name':'widgets','description':'Endpoints for managing a widget.',}MergefileYou likely will wish to augment your API spec with a description, additional
components, and more.  This can be achieved with a mergefile.  Write a YAML
file with the parts of the spec you wish to augment and pass the filename as
the--mergeflag withgenerate-spec.  The file will be loaded and merged
into the generated spec.ZonesIt may be that not all endpoints are made available to all users.  For example,
you may have all endpoints available internally but only select ones available
publicly.  You would then want separate API docs for internal users versus
external users.  This can be achieved using zones.Tag each endpoint by settingapi_zoneinConfiguration.add_viewor@view_config.  By default, all endpoints regardless of zone will be added to
the spec.  Set the--zoneflag ingenerate-specto only put endpoints
assigned to that zone in the spec.Prior Artpyramid-apispecallows you to
augment view callable docstrings with OpenAPI definitions and can reference
Marshmallow schemas with the apispec Marshmallow plugin.  It does not support
validating input and marshalling output.  Schemas and routes must be manually
declared.Cornicesupports validation with Marshmallow schemas, however only on Cornice
resources, not arbitrary Pyramid endpoints.  It does not support
auto-generating OpenAPI documentation.