API

Spec/Plugin Objects

class specargs.WebargsAPISpec[source]

Bases: apispec.core.APISpec

Stores metadata that describes a RESTful API and generates an OpenAPI spec from that metadata

This class adds functionality to apispec.APISpec that allows for definition of reusable OpenAPI response and schema objects. This class also adds convenient extraction of operation metadata from components of the supported frameworks (e.g. Flask, Tornado, etc.).

__init__(title, version, openapi_version, plugins=(), **options)[source]

Initializes a WebargsAPISpec object

This accepts the same arguments as the constructor for apispec.APISpec

abstract create_paths(framework_obj: Any)[source]

Creates the paths section of the OpenAPI spec from the appropriate framework object

Parameters

framework_obj – The object corresponding to the framework being used.

The list of supported frameworks and accepted objects is as follows:

path(path: str | None = None, *, operations: dict[str, Any] | None = None, summary: str | None = None, description: str | None = None, parameters: list[dict] | None = None, **kwargs: Any) APISpec

Add a new path object to the spec.

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

Parameters
  • path (str|None) – URL path component

  • operations (dict|None) – describes the http methods and options for path

  • summary (str) – short summary relevant to all operations in this path

  • description (str) – long description relevant to all operations in this path

  • parameters (list|None) – list of parameters relevant to all operations in this path

  • kwargs – parameters used by any path helpers see register_path_helper()

response(response_id: str, response_or_argpoly: Union[specargs.oas.Response, marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Callable[[webargs.core.Request], marshmallow.schema.Schema], specargs.in_poly.InPoly], *, description: str = '', **headers: str) specargs.oas.Response[source]

Registers a resuable OAS response object and returns it as an oas.Response easy reuse

Parameters
  • response_id – The name of the response as it will appear in the OpenAPI spec

  • response_or_argpoly – A oas.Response object, an InPoly object, a marshmallow Schema class or instance, a dictionary of names to marshmallow Field objects, or None. Determines the content of the generated OpenAPI response object

  • description – The description of the generated OpenAPI response object. Ignored if response_or_argpoly is a Response object

  • **headers – Any keyword arguments not listed above are taken as response header names and values. Ignored if if response_or_argpoly is a oas.Response object

Returns

The value of response_or_argpoly if a Response object was provided. Otherwise, a new Response instance created from response_or_argpoly, description, and **headers

schema(schema_class_or_name: Union[Type[marshmallow.schema.Schema], str], custom_name: Optional[str] = None)[source]

Registers a marshmallow.Schema as an OpenAPI spec schema

This method can be used one of three ways:

  1. As a marshmallow.Schema class decorator with no arguments:

    spec = WebargsAPISpec(...)
    
    # This will result in an OAS schema with the name "Example"
    @spec.schema
    class ExampleSchema(marshmallow.Schema):
        ...
    
  2. As a marshmallow.Schema class decorator with arguments:

    spec = WebargsAPISpec(...)
    
    # This will result in an OAS schema with the name "CustomName"
    @spec.schema("CustomName")
    class ExampleSchema(marshmallow.Schema):
        ...
    
  3. As a method that accepts a marshmallow.Schema class and optionally a string name:

    spec = WebargsAPISpec(...)
    
    class ExampleSchema(marshmallow.Schema):
        ...
    
    # This will result in an OAS schema with the name "Example"
    spec.schema(ExampleSchema)
    # This will result in an OAS schema with the name "CustomName"
    spec.schema(ExampleSchema, "CustomName")
    
Parameters
  • schema_class_or_name – A marshmallow.Schema class or, if used as decorator, a string containing the name of the OpenAPI schema that will be generated

  • custom_name – The name of the generated OpenAPI schema when this method is not used as a decorator

tag(tag: dict) apispec.core.APISpec

Store information about a tag.

Parameters

tag (dict) – the dictionary storing information about the tag.

to_dict() dict[str, Any]
to_yaml(yaml_dump_kwargs: Any | None = None) str

Render the spec to YAML. Requires PyYAML to be installed.

Parameters

yaml_dump_kwargs (dict) – Additional keyword arguments to pass to yaml.dump

class specargs.WebargsPlugin[source]

Generates OpenAPI specification components from decorated view functions/methods

An instance of this class should be given to an instance of WebargsAPISpec in order for an OpenAPI spec to be generated from decorated view functions/methods. This class does not need to be interacted with otherwise.

View Function/Method Decorators

specargs.use_args(argpoly: Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema], specargs.in_poly.InPoly], *args, location: str = 'json', **kwargs) Callable[[...], Callable][source]

A wrapper around webargs’ use_args() decorator function

This attaches attributes to the wrapped view function that are later used to populate the operation data for the generated API spec.

Parameters
  • argpoly – A dictionary of webargs.fields, a marshmallow.Schema instance or class, or an object that inherits from InPoly to be used for request argument parsing

  • *args – Any other positional arguments accepted by webargs’ use_args()

  • location – Identical to the location argument of webargs’ use_args()

  • **kwargs – Any other keyword arguments accepted by webargs’ use_args()

Raises

ValueError – If argmap is an InPoly object and location is anything besides “json”

specargs.use_kwargs(*args, **kwargs) Callable[[...], Callable][source]

A decorator equivalent to use_args() with the keyword argument as_kwargs set to True

specargs.use_response(response_or_argpoly: Optional[Union[specargs.oas.Response, marshmallow.fields.Field, marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema], specargs.in_poly.InPoly]], *, status_code: Union[http.HTTPStatus, int] = HTTPStatus.OK, description: str = '', **headers: str) Callable[[...], Callable][source]

A decorator function used for registering a response to a view function/method

Parameters
  • response_or_argpoly – A Response object, an InPoly object, a marshmallow.Schema class or instance, a dictionary of names to marshmallow.fields, or None. Determines the content of the corresponding response clause in the generated OpenAPI spec and whether/how the data returned by the decorated view function/method is serialized

  • status_code – The status code under which the response is being listed in the generated OpenAPI spec. Also used as the status code for the decorated view function/method response. Defaults to http.HTTPStatus.OK

  • description – The response description. Defaults to an empty string. Ignored if response_or_argpoly is an oas.Response object

  • **headers – Any keyword arguments not listed above are taken as response header names and values. Ignored if response_or_argpoly is an oas.Response object

Raises
specargs.use_empty_response(**kwargs) Callable[[...], Callable][source]

Convenience decorator for registering an empty response to a view method

Parameters

**kwargs – Any keyword arguments accepted by use_response()

Schema Inheritance/Polymorphism

class specargs.in_poly.InPoly[source]

An abstract representation of the inheritance/polymorphism keywords of the OpenAPI Specification

Subclasses of this class not only enable generation of correpsonding OpenAPI Specification clauses, but also data deserialization when provided to use_args() or use_kwargs() and data serialization when provided to use_response().

__init__(*argmaps: Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema]])[source]

Initializes an InPoly instance

Parameters

*argmaps – Dictionaries of marshmallow Field instances or marshmallow Schema instances or classes provided as positional arguments. Converted into Schema instances and stored in schemas

Raises

TypeError – If any of the provided argmaps are InPoly objects

abstract dump(obj: Any, *, many: bool = False) dict[source]

Serializes the given object into a dictionary

This method mimics the behavior of the marshmallow.Schema.dump() method

schemas: Tuple[marshmallow.schema.Schema]

The marshmallow Schema instances that will be converted into members of the keyword and determine serialization and deserialization behavior

class specargs.OneOf[source]

Bases: specargs.in_poly.InPoly

A representation of the ‘oneOf’ OpenAPI Specification keyword

__init__(*argmaps: Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema]], unknown: str = 'exclude')[source]

Initializes a OneOf instance

Parameters
Raises

The same exceptions as in_poly.InPoly.__init__() for the same reasons

__call__(request: Any) marshmallow.schema.Schema[source]

Generates a marshmallow.Schema based on the given request object

Parameters

request – The request object which holds the data used to produce the marshmallow.Schema

Returns

The single marshmallow.Schema from OneOf.schemas that successfully validates the request data

Raises
dump(obj: Any, *, many: bool = False) dict[source]

Serializes the given object into a dictionary

This method mimics the behavior of marshmallow’s Schema.dump method

Parameters

obj – The object to serialize

Returns

The object serialization output of one of the OneOf.schemas

Raises
class specargs.AnyOf[source]

Bases: specargs.in_poly.InPoly

A representation of the ‘anyOf’ OpenAPI Spec keyword

__call__(request: Any) marshmallow.schema.Schema[source]

Generates a marshmallow Schema based on the given request object

Parameters

request – The request object which holds the data used to produce the Schema

Returns

A Schema that’s a combination of all AnyOf.schemas that successfully validate the request data

Raises
  • AnyOfConflictError – If the AnyOf.schemas that succesfully validate the request data produce differing values for a given key

  • AnyOfValidationError – If none of AnyOf.schemas succesfully validate the request data

dump(obj: Any, *, many: bool = False) dict[source]

Serializes the given object into a dictionary

This method mimics the behavior of marshmallow’s Schema.dump method

Parameters

obj – The object to serialize

Returns

The object serialization output of all of the AnyOf.schemas that successfully validate the object

Raises
  • AnyOfConflictError – If the AnyOf.schemas that succesfully validate the object produce differing values for a given key

  • AnyOfValidationError – If none of AnyOf.schemas succesfully validate the object

class specargs.AllOf[source]

Bases: specargs.in_poly.InPoly

A representation of the ‘allOf’ OpenAPI Spec keyword

__call__(request: Any) marshmallow.schema.Schema[source]

Generates a marshmallow Schema based on the given request object

Parameters

request – The request object which holds the data used to produce the Schema

Returns

A Schema that’s a combination of all AllOf.schemas

Raises
dump(obj: Any, *, many: bool = False) dict[source]

Serializes the given object into a dictionary

This method mimics the behavior of marshmallow’s Schema.dump method

Parameters

obj – The object to serialize

Returns

The combined object serialization output of all of the AllOf.schemas

Raises
  • AllOfConflictError – If the AllOf.schemas that succesfully validate the object produce differing values for a given key

  • AllOfValidationError – If none of AllOf.schemas succesfully validate the object

Response Construction

class specargs.ViewResponse[source]

An object used for specifying the data and status code returned by a view function/method

This class should be used when returning a non-default status code from a view function/method.

__init__(data: Any, status_code: Union[http.HTTPStatus, int])[source]

Initializes a Response object

Parameters
  • data – The data to be returned in the response. May be serialized depending on whether/how the returning view function/method has been decorated with use_response()

  • status_code – The status code of the response

Reusable OAS Components

class specargs.Response[source]

Stores metadata representing a reusable OpenAPI specification response object

This class should only be instantiated using the response() method of the WebargsAPISpec class.

The schema attribute of this class is also used for data serialization when provided to specargs.use_response().

__init__(argpoly_or_field: Optional[Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema], specargs.in_poly.InPoly, marshmallow.fields.Field]], *, description: str = '', headers: Optional[Dict[str, str]] = None)[source]

Initializes a Response object

Parameters
  • argpoly_or_field – An InPoly object, a marshmallow.Schema class or instance, a dictionary of names to marshmallow.fields, or None. Determines the content of the corresponding response clause in the generated OpenAPI spec and whether/how the data returned by the decorated view function/method is serialized

  • description – The response object description

  • headers – A dictionary of response header names to values

property content: dict

A dictionary that represents the content section of the generated OpenAPI response object

description: str

The response description

headers: Dict[str, str]

A dictionary of the Response header names to values

schema: Optional[Union[marshmallow.schema.Schema, specargs.in_poly.InPoly, marshmallow.fields.Field]]

A marshmallow.Schema, an InPoly object, or a marshmallow.fields.Field. Determines the content of the generated OpenAPI response object. Also determines serialization of response data when provided to specargs.use_response()

Exceptions

exception specargs.decorators.DuplicateResponseCodeError[source]

An exception that’s raised when a status code is registered to a single view function/method more than once

exception specargs.decorators.UnregisteredResponseCodeError[source]

An exception that’s raised when a view function/method returns an unregistered status code

The status code of a Response returned by a view function/method must be registered to the view function/method using use_response() or use_empty_response().

exception specargs.in_poly.AllOfConflictError[source]

An exception for AllOf serlialization/deserialization conflicts

This is raised when the schemas of an AllOf instance produce keys with conflicting values on serialization or deserialization.

exception specargs.in_poly.AllOfValidationError[source]

An exception for AllOf validation

This is raised when an object being serialized/deserialized by an AllOf is invalid for all schemas of that instance.

exception specargs.in_poly.AnyOfConflictError[source]

An exception for AnyOf serlialization/deserialization conflicts

This is raised when the schemas of an AnyOf instance produce keys with conflicting values on serialization or deserialization.

exception specargs.in_poly.AnyOfValidationError[source]

An exception for AnyOf validation

This is raised when an object being serialized/deserialized by an AnyOf is invalid for all schemas of that instance.

exception specargs.in_poly.OneOfConflictError[source]

An exception for OneOf serlialization/deserialization conflicts

This is raised when data that is being serialized or deserialized by a OneOf instance is valid for multiple schemas of that instance.

exception specargs.in_poly.OneOfValidationError[source]

An exception for OneOf validation

This is raised when data that is being serialized or deserialized by a OneOf instance is invalid for all schemas of that instance.