OpenAPI

Flask_tern provides a flask blueprint which simplifies creating OpenAPI conform APIs.

To use it, it is necessary to create an OpenAPI spec document first. The Path objects in that spec are then matched against flask routes registered with the blueprint. Additionally it provides a simple template to render a Swagger UI to easily look at the documentation and execute test requests against the API.

The easiest way to use it, is to create a sub module in which the OpenApiBlueprint is instantiated, and place a openapi.yaml into the same folder. The blueprint instance will load the openapi.yaml file via flask:flask.Blueprint.open_resource().

All api methods are then implemnted as standard flask views, which are registered as routes against this blueprint instance. The API can then be mounted and served by Flask via registering that blueprint instance with your Flask application.

Settings

The module offers one option, which makes it easy to change the Swagger UI version used to render the documentation.

flask_tern.openapi.settings.SWAGGER_UI_VERSION = '5.0.0-alpha.14'

The Swagger UI version used to show the openapi documentation.

Decorators

To enable request and response validation each view method needs to be decorated with flask_tern.openapi.validate().

from flask import jsonify
from flask_tern import openapi

bp = openapi.OpenApiBlueprint()

# register view with blueprint
@bp.route("/view")
# enable request validation, disable response validation
@openapi.validate(True, False)
def view():
    return jsonify("test")

@bp.route("/test)
# validate requset and response
@openapi.validate()
def test():
    return jsonify("test")

Error response

The openapi.OpneApiBlueprint registers a default error handler. This handler catches any error that is a subclass of Exception, and renders a json error response.

{
    "error": {
        "code": 400,              # http status code
        "reason": "Bad Request",  # http status reason
        "message": "....",        # overall error message
        "errors": [               # list of additional error details
            {...},                #  e.g. one per form field during form validation, or chain of errors
            {...},
            {...}
        ]
    }
}