API
Contents
API¶
Spec/Plugin Objects¶
- class specargs.WebargsAPISpec[source]¶
Bases:
apispec.core.APISpecStores metadata that describes a RESTful API and generates an OpenAPI spec from that metadata
This class adds functionality to
apispec.APISpecthat 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
WebargsAPISpecobjectThis 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:
Flask:
flask.Flask
- 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.Responseeasy reuse- Parameters
response_id – The name of the response as it will appear in the OpenAPI spec
response_or_argpoly – A
oas.Responseobject, anInPolyobject, a marshmallow Schema class or instance, a dictionary of names to marshmallow Field objects, or None. Determines the content of the generated OpenAPI response objectdescription – The description of the generated OpenAPI response object. Ignored if response_or_argpoly is a
Responseobject**headers – Any keyword arguments not listed above are taken as response header names and values. Ignored if if response_or_argpoly is a
oas.Responseobject
- Returns
The value of response_or_argpoly if a
Responseobject was provided. Otherwise, a newResponseinstance 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.Schemaas an OpenAPI spec schemaThis method can be used one of three ways:
As a
marshmallow.Schemaclass decorator with no arguments:spec = WebargsAPISpec(...) # This will result in an OAS schema with the name "Example" @spec.schema class ExampleSchema(marshmallow.Schema): ...
As a
marshmallow.Schemaclass decorator with arguments:spec = WebargsAPISpec(...) # This will result in an OAS schema with the name "CustomName" @spec.schema("CustomName") class ExampleSchema(marshmallow.Schema): ...
As a method that accepts a
marshmallow.Schemaclass 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.Schemaclass or, if used as decorator, a string containing the name of the OpenAPI schema that will be generatedcustom_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.
- 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
WebargsAPISpecin 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 functionThis 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, amarshmallow.Schemainstance or class, or an object that inherits fromInPolyto 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
InPolyobject 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
Responseobject, anInPolyobject, amarshmallow.Schemaclass or instance, a dictionary of names tomarshmallow.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 serializedstatus_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.Responseobject**headers – Any keyword arguments not listed above are taken as response header names and values. Ignored if response_or_argpoly is an
oas.Responseobject
- Raises
DuplicateResponseCodeError – If a status code is registered to the same view function/method more than once
UnregisteredResponseCodeError – If the status code of a
Responsereturned by a view function/method has not be registered to the view function/method
- 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()oruse_kwargs()and data serialization when provided touse_response().- __init__(*argmaps: Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Type[marshmallow.schema.Schema]])[source]¶
Initializes an
InPolyinstance
- 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.InPolyA 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
OneOfinstance- Parameters
*argmaps – Dictionaries of
marshmallow.fieldsormarshmallow.Schemainstances or classes provided as positional arguments. Converted intomarshmallow.Schemainstances and stored inin_poly.InPoly.schemasunknown – Determines the behavior of unknown fields when serializing/deserializing. Defaults to
marshmallow.utils.EXCLUDE
- Raises
The same exceptions as
in_poly.InPoly.__init__()for the same reasons
- __call__(request: Any) marshmallow.schema.Schema[source]¶
Generates a
marshmallow.Schemabased on the given request object- Parameters
request – The request object which holds the data used to produce the
marshmallow.Schema- Returns
The single
marshmallow.SchemafromOneOf.schemasthat successfully validates the request data- Raises
OneOfConflictError – If more than one of
OneOf.schemassuccesfully validates the request dataOneOfValidationError – If none of
OneOf.schemassuccesfully 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 one of the
OneOf.schemas- Raises
OneOfConflictError – If more than one of
OneOf.schemassuccesfully validates the objectOneOfValidationError – If none of
OneOf.schemassuccesfully validate the object
- class specargs.AnyOf[source]¶
Bases:
specargs.in_poly.InPolyA 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.schemasthat successfully validate the request data- Raises
AnyOfConflictError – If the
AnyOf.schemasthat succesfully validate the request data produce differing values for a given keyAnyOfValidationError – If none of
AnyOf.schemassuccesfully 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.schemasthat successfully validate the object- Raises
AnyOfConflictError – If the
AnyOf.schemasthat succesfully validate the object produce differing values for a given keyAnyOfValidationError – If none of
AnyOf.schemassuccesfully validate the object
- class specargs.AllOf[source]¶
Bases:
specargs.in_poly.InPolyA 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
AllOfConflictError – If the
AllOf.schemasproduce differing values for a given keyAllOfValidationError – If any of
AllOf.schemasdon’t 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 combined object serialization output of all of the
AllOf.schemas- Raises
AllOfConflictError – If the
AllOf.schemasthat succesfully validate the object produce differing values for a given keyAllOfValidationError – If none of
AllOf.schemassuccesfully 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
Responseobject- 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 theWebargsAPISpecclass.The
schemaattribute of this class is also used for data serialization when provided tospecargs.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
Responseobject- Parameters
argpoly_or_field – An
InPolyobject, amarshmallow.Schemaclass or instance, a dictionary of names tomarshmallow.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 serializeddescription – 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
- schema: Optional[Union[marshmallow.schema.Schema, specargs.in_poly.InPoly, marshmallow.fields.Field]]¶
A
marshmallow.Schema, anInPolyobject, or amarshmallow.fields.Field. Determines thecontentof the generated OpenAPI response object. Also determines serialization of response data when provided tospecargs.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
Responsereturned by a view function/method must be registered to the view function/method usinguse_response()oruse_empty_response().
- exception specargs.in_poly.AllOfConflictError[source]¶
An exception for
AllOfserlialization/deserialization conflictsThis is raised when the
schemasof anAllOfinstance produce keys with conflicting values on serialization or deserialization.
- exception specargs.in_poly.AllOfValidationError[source]¶
An exception for
AllOfvalidationThis is raised when an object being serialized/deserialized by an
AllOfis invalid for allschemasof that instance.
- exception specargs.in_poly.AnyOfConflictError[source]¶
An exception for
AnyOfserlialization/deserialization conflictsThis is raised when the
schemasof anAnyOfinstance produce keys with conflicting values on serialization or deserialization.
- exception specargs.in_poly.AnyOfValidationError[source]¶
An exception for
AnyOfvalidationThis is raised when an object being serialized/deserialized by an
AnyOfis invalid for allschemasof that instance.