Pint Class

class quart_openapi.Pint(*args, no_openapi=False, **kwargs)

Bases: quart_openapi.pint.BaseRest, quart.app.Quart

Use this instead of instantiating quart.Quart

This takes the place of instantiating a quart.Quart instance. It will forward any init arguments to Quart and takes arguments to fill out the metadata for the openapi documentation it generates that will automatically be accessible via the ‘/openapi.json’ route.

__init__(*args, no_openapi=False, **kwargs)[source]

Construct the Pint object, see BaseRest.__init__() for an explanation of the args and kwargs.

Parameters:
  • *args – non-keyword args passed to BaseRest
  • no_openapi (bool) – set this to True to disable the auto creation of the /openapi.json route in order to allow custom manipulation of the route
  • **kwargs – keyword args passed to BaseRest

If you pass no_openapi=True then you can customize the openapi route by creating it yourself:

app = Pint('Custom', no_openapi=True)

@app.route('/openapi.json')
# add other decorators if desired
async def openapi():
  # add other logic if desired
  return jsonify(app.__schema__)
Return type:None
base_model

The RefResolver created by processing the file or schema that was passed to __init__()

Return type:Optional[RefResolver]
create_ref_validator(name, category)

Use the base_model to resolve the component category and name and create a Draft4Validator

Parameters:
  • name (str) – The name of the model
  • category (str) – The category under ‘components’ to look in
Return type:

Validator

Returns:

The validator object

The resulting validator can be passed into decorators like param() or response() and will be used to create the schema in the openapi json output or passed into expect() to use it for actually validating a request against the schema. It will be output as a ‘$ref’ object in the resulting openapi json output.

See also

The expect() decorator

Todo

Ensure that models with the same name in different categories don’t conflict

create_validator(name, schema)

Create a validator from a schema

Parameters:
  • name (str) – The name of this validator
  • schema (Dict[str, Any]) – A dict which is a valid Openapi 3.0 schema
Return type:

Validator

Returns:

the validator object

You can use references to models that are in the base_model as that will be used to resolve any references such as #/components/requestBodies/sample.

Todo

Ensure that models with the same name in different categories don’t conflict with each other

See also

The expect() decorator

static default_id(resource, method)

function for creating a default operation id from a resource and method

Parameters:
  • resource (str) – name of the resource endpoint
  • method (str) – the HTTP verb
Return type:

str

Returns:

the id converting camel case to snake_case

doc(**kwargs)

Generic decorator for adding docs via keys pointing to dictionaries

Examples:

@app.route('/<string:table>')
@app.doc(params={'table': 'Table Description'})
class Table(Resource):
  async def get(self, table):
    ...
@app.route('/<int:table>')
class Table(Resource):
  @app.doc(params={'table': 'Table Desc'}, responses={HTTPStatus.OK: ('desc')})
  async def get(self, table):
    ...
Return type:Callable
expect(*inputs, **kwargs)

Define the expected request schema

Parameters:
  • *inputs – one or more inputs that are either a validator or a tuple of the form Tuple[validator, content_type, Dict of properties]. properly handles either 1, 2, or all 3 members existing.
  • **kwargs – currently only recognizes ‘validate’ as a keyword arg which can override the bool that was passed into __init__() to turn validation on or off for this particular request body

Code Example:

request = app.create_validator('sample', {
  'type': 'object',
  'properties': {
    'columns': {
      'type': 'array',
      'items': { 'type': 'string' }
    },
    'rows': {
      'type': 'array',
      'items': {
        'oneOf': [
          {'type': 'integer'},
          {'type': 'number'},
          {'type': 'string'}
        ]
      }
    }
  }
})
@app.route('/sample')
class Sample(Resource):
  @app.expect(request)
  async def post(self):
    # if the request body isn't json and doesn't match the above schema
    # we'll never even get here, it'll be rejected with a bad request status
    ...

Another Example:

stream = app.create_validator('binary_stream', {'type': 'string', 'format': 'binary'})
string_data = app.create_validator('string', {'type': 'string'})
@app.route('/sample')
class Sample(Resource):
  @app.expect((stream, 'application/octet-stream', {'example': '0xACDEFD'}),
              ('string', 'text/plain', {'examples': {
                                          'ex1': {
                                            'summary': 'example1',
                                            'value': 'foobar'
                                          }
                                       }}))
  async def post(self):
    # if the request doesn't have a Content-Type header set to 'application/octet-stream'
    # or 'text/plain' it will be rejected as a bad request.
    ...

In the above example, the examples will be in the openapi docs as per the openapi 3.0 spec.

Todo

figure out a good way to set the description for the requestBody itself, probably through the kwargs

Return type:Callable
get_validator(name)

Get a specific Draft4Validator instance by name

Parameters:name (str) – The validator name to lookup
Return type:Optional[Validator]
Returns:the Draft4Validator object or None
static handle_json_validation_exc(error)

Function to handle validation errors

The constructor will register this function to handle a ValidationError which is thrown by the jsonschema validation routines.

Parameters:error (ValidationError) – The exception that was raised
Return type:Dict[str, Union[str, Dict[str, str]]]
Returns:Json message with the validation error

See also

quart.Quart.register_error_handler()
Registering error handlers with quart
param(name, description=None, _in='query', **kwargs)

Decorator for describing parameters for a given resource or specific request method.

Parameters:
  • name (str) – Parameter name in documention
  • description (Optional[str]) – the description property of the parameter object
  • _in (str) – Location of the parameter: query, header, path, cookie
  • **kwargs – mapping of properties to forward for the openapi docs

If put at the class level, it’ll add the parameter to all method types. For path params you should use doc() instead which will automatically handle path params instead of having to manually set _in to ‘path’

See the following example:

@app.route('/header')
@app.param('Expected-Header', description='Header Parameter for all method types', _in='header')
class Simple(Resource):

  @app.param('id', description='query param id just for get method', schema={'type': 'integer'})
  async def get(self):
    hdr_value = request.headers['Expected-Header']
    id = request.args['id']
    return f"{id} with {hdr_value}"

  @app.param('foobar', description='foobar will show up for the post method, but not get',
             _in='cookie', style='form')
  async def post(self):
    # the openapi documentation will contain both the Expected-Header and
    # the 'foobar' cookie params in it
    ...
    return "Success"
Return type:Callable
resources

The list of resource tuples that have been added so far.

The tuple contains the object itself, the path and the list of methods it supports

Return type:Iterable[Tuple[Resource, str, Iterable[str]]]
response(code, description, validator=None, **kwargs)

Decorator for documenting the response from a route

Parameters:

Use this decorator for adding the documentation to describe a possible response from the route, can be called multiple times with different status codes to describe different responses.

@app.route('/sample')
class Sample(Resource):

  @app.response(HTTPStatus.OK, description="OK")
  @app.response(HTTPStatus.BAD_REQUEST, "json response failure", int, headers={'Foobar': 'foo'})
  async def get(self):
    ...
Return type:Callable
route(path, *args, methods=None, **kwargs)

Decorator for establishing routes

Parameters:
  • path (str) – the path to route on, should start with a /, may contain params converters
  • methods (Optional[Iterable[str]]) – list of HTTP verbs allowed to be routed
  • *args – will forward extra arguments to the base class route function

Ensures we add the route’s documentation to the openapi docs and merge the properties correctly, should work identically to using the base method.

See also

Base class version route()

Return type:Callable

PintBlueprint Class

class quart_openapi.PintBlueprint(*args, **kwargs)

Bases: quart_openapi.pint.BaseRest, quart.blueprints.Blueprint

Use this instead of quart.Blueprint objects to allow using Resource class objects with them

__init__(*args, **kwargs)[source]

Will forward all arguments and keyword arguments to Blueprints

Return type:None
base_model

The RefResolver created by processing the file or schema that was passed to __init__()

Return type:Optional[RefResolver]
create_ref_validator(name, category)

Use the base_model to resolve the component category and name and create a Draft4Validator

Parameters:
  • name (str) – The name of the model
  • category (str) – The category under ‘components’ to look in
Return type:

Validator

Returns:

The validator object

The resulting validator can be passed into decorators like param() or response() and will be used to create the schema in the openapi json output or passed into expect() to use it for actually validating a request against the schema. It will be output as a ‘$ref’ object in the resulting openapi json output.

See also

The expect() decorator

Todo

Ensure that models with the same name in different categories don’t conflict

create_validator(name, schema)

Create a validator from a schema

Parameters:
  • name (str) – The name of this validator
  • schema (Dict[str, Any]) – A dict which is a valid Openapi 3.0 schema
Return type:

Validator

Returns:

the validator object

You can use references to models that are in the base_model as that will be used to resolve any references such as #/components/requestBodies/sample.

Todo

Ensure that models with the same name in different categories don’t conflict with each other

See also

The expect() decorator

static default_id(resource, method)

function for creating a default operation id from a resource and method

Parameters:
  • resource (str) – name of the resource endpoint
  • method (str) – the HTTP verb
Return type:

str

Returns:

the id converting camel case to snake_case

doc(**kwargs)

Generic decorator for adding docs via keys pointing to dictionaries

Examples:

@app.route('/<string:table>')
@app.doc(params={'table': 'Table Description'})
class Table(Resource):
  async def get(self, table):
    ...
@app.route('/<int:table>')
class Table(Resource):
  @app.doc(params={'table': 'Table Desc'}, responses={HTTPStatus.OK: ('desc')})
  async def get(self, table):
    ...
Return type:Callable
expect(*inputs, **kwargs)

Define the expected request schema

Parameters:
  • *inputs – one or more inputs that are either a validator or a tuple of the form Tuple[validator, content_type, Dict of properties]. properly handles either 1, 2, or all 3 members existing.
  • **kwargs – currently only recognizes ‘validate’ as a keyword arg which can override the bool that was passed into __init__() to turn validation on or off for this particular request body

Code Example:

request = app.create_validator('sample', {
  'type': 'object',
  'properties': {
    'columns': {
      'type': 'array',
      'items': { 'type': 'string' }
    },
    'rows': {
      'type': 'array',
      'items': {
        'oneOf': [
          {'type': 'integer'},
          {'type': 'number'},
          {'type': 'string'}
        ]
      }
    }
  }
})
@app.route('/sample')
class Sample(Resource):
  @app.expect(request)
  async def post(self):
    # if the request body isn't json and doesn't match the above schema
    # we'll never even get here, it'll be rejected with a bad request status
    ...

Another Example:

stream = app.create_validator('binary_stream', {'type': 'string', 'format': 'binary'})
string_data = app.create_validator('string', {'type': 'string'})
@app.route('/sample')
class Sample(Resource):
  @app.expect((stream, 'application/octet-stream', {'example': '0xACDEFD'}),
              ('string', 'text/plain', {'examples': {
                                          'ex1': {
                                            'summary': 'example1',
                                            'value': 'foobar'
                                          }
                                       }}))
  async def post(self):
    # if the request doesn't have a Content-Type header set to 'application/octet-stream'
    # or 'text/plain' it will be rejected as a bad request.
    ...

In the above example, the examples will be in the openapi docs as per the openapi 3.0 spec.

Todo

figure out a good way to set the description for the requestBody itself, probably through the kwargs

Return type:Callable
get_validator(name)

Get a specific Draft4Validator instance by name

Parameters:name (str) – The validator name to lookup
Return type:Optional[Validator]
Returns:the Draft4Validator object or None
static handle_json_validation_exc(error)

Function to handle validation errors

The constructor will register this function to handle a ValidationError which is thrown by the jsonschema validation routines.

Parameters:error (ValidationError) – The exception that was raised
Return type:Dict[str, Union[str, Dict[str, str]]]
Returns:Json message with the validation error

See also

quart.Quart.register_error_handler()
Registering error handlers with quart
param(name, description=None, _in='query', **kwargs)

Decorator for describing parameters for a given resource or specific request method.

Parameters:
  • name (str) – Parameter name in documention
  • description (Optional[str]) – the description property of the parameter object
  • _in (str) – Location of the parameter: query, header, path, cookie
  • **kwargs – mapping of properties to forward for the openapi docs

If put at the class level, it’ll add the parameter to all method types. For path params you should use doc() instead which will automatically handle path params instead of having to manually set _in to ‘path’

See the following example:

@app.route('/header')
@app.param('Expected-Header', description='Header Parameter for all method types', _in='header')
class Simple(Resource):

  @app.param('id', description='query param id just for get method', schema={'type': 'integer'})
  async def get(self):
    hdr_value = request.headers['Expected-Header']
    id = request.args['id']
    return f"{id} with {hdr_value}"

  @app.param('foobar', description='foobar will show up for the post method, but not get',
             _in='cookie', style='form')
  async def post(self):
    # the openapi documentation will contain both the Expected-Header and
    # the 'foobar' cookie params in it
    ...
    return "Success"
Return type:Callable
register(app, options, *args, **kwargs)[source]

override the base register() method to add the resources to the app registering this blueprint, then call the parent register method

Return type:None
resources

The list of resource tuples that have been added so far.

The tuple contains the object itself, the path and the list of methods it supports

Return type:Iterable[Tuple[Resource, str, Iterable[str]]]
response(code, description, validator=None, **kwargs)

Decorator for documenting the response from a route

Parameters:

Use this decorator for adding the documentation to describe a possible response from the route, can be called multiple times with different status codes to describe different responses.

@app.route('/sample')
class Sample(Resource):

  @app.response(HTTPStatus.OK, description="OK")
  @app.response(HTTPStatus.BAD_REQUEST, "json response failure", int, headers={'Foobar': 'foo'})
  async def get(self):
    ...
Return type:Callable
route(path, *args, methods=None, **kwargs)

Decorator for establishing routes

Parameters:
  • path (str) – the path to route on, should start with a /, may contain params converters
  • methods (Optional[Iterable[str]]) – list of HTTP verbs allowed to be routed
  • *args – will forward extra arguments to the base class route function

Ensures we add the route’s documentation to the openapi docs and merge the properties correctly, should work identically to using the base method.

See also

Base class version route()

Return type:Callable

OpenApiView helper

class quart_openapi.OpenApiView(api)[source]

Bases: quart_openapi.Resource

The Resource used for the ‘/openapi.json’ route

It also uses CORS to set the Access-Control-Allow-Origin header to “*” for this route so that the openapi.json can be accessible from other domains.

Todo

Allow customizing the origin for CORS on the openapi.json

dispatch_request(*args, **kwargs)

Can be overridden instead of creating verb functions

This will be called with the request view_args, i.e. any url parameters

Return type:Union[Forwardref, Forwardref, AnyStr, Dict[str, Any], Asyncgenerator[AnyStr, None], Generator[AnyStr, None, None], Tuple[Union[Forwardref, Forwardref, AnyStr, Dict[str, Any], Asyncgenerator[AnyStr, None], Generator[AnyStr, None, None]], Union[Forwardref, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Forwardref, Forwardref, AnyStr, Dict[str, Any], Asyncgenerator[AnyStr, None], Generator[AnyStr, None, None]], int], Tuple[Union[Forwardref, Forwardref, AnyStr, Dict[str, Any], Asyncgenerator[AnyStr, None], Generator[AnyStr, None, None]], int, Union[Forwardref, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]]]
get()[source]

Return the schema for get requests

validate_payload(func)

This will perform validation

Will check the api docs of the class as set by using the decorators in Pint and if an expect was present without validate set to False or None, it will attempt to validate any request against the schema if json, or ensure the content_type matches at least.

Return type:bool

Generated from version 1.7.2