Skip to content

APIBlueprint

Flask's Blueprint object with some web API support.

Examples:

from apiflask import APIBlueprint

bp = APIBlueprint(__name__, 'foo')

Version changed: 0.5.0

  • Add enable_openapi parameter.

Version added: 0.2.0

__init__(self, name, import_name, tag=None, enable_openapi=True, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=<object object at 0x7f75f0090190>) special

Make a blueprint instance.

Parameters:

Name Type Description Default
name str

The name of the blueprint. Will be prepended to each endpoint name.

required
import_name str

The name of the blueprint package, usually __name__. This helps locate the root_path for the blueprint.

required
tag Union[str, dict]

The tag of this blueprint. If not set, the <blueprint name>.title() will be used ('foo' -> 'Foo'). Accepts a tag name string or an OpenAPI tag dict. Example:

bp = APIBlueprint(__name__, 'foo', tag='Foo')
bp = APIBlueprint(__name__, 'foo', tag={'name': 'Foo'})
None
enable_openapi bool

If False, will disable OpenAPI support for the current blueprint.

True

Other keyword arguments are directly passed to flask.Blueprint.

Source code in apiflask/blueprint.py
def __init__(
    self,
    name: str,
    import_name: str,
    tag: t.Optional[t.Union[str, dict]] = None,
    enable_openapi: bool = True,
    static_folder: t.Optional[str] = None,
    static_url_path: t.Optional[str] = None,
    template_folder: t.Optional[str] = None,
    url_prefix: t.Optional[str] = None,
    subdomain: t.Optional[str] = None,
    url_defaults: t.Optional[dict] = None,
    root_path: t.Optional[str] = None,
    cli_group: t.Union[t.Optional[str]] = _sentinel  # type: ignore
) -> None:
    """Make a blueprint instance.

    Arguments:
        name: The name of the blueprint. Will be prepended to
            each endpoint name.
        import_name: The name of the blueprint package, usually
            `__name__`. This helps locate the `root_path` for the
            blueprint.
        tag: The tag of this blueprint. If not set, the
            `<blueprint name>.title()` will be used (`'foo'` -> `'Foo'`).
            Accepts a tag name string or an OpenAPI tag dict.
            Example:

            ```python
            bp = APIBlueprint(__name__, 'foo', tag='Foo')
            ```

            ```python
            bp = APIBlueprint(__name__, 'foo', tag={'name': 'Foo'})
            ```
        enable_openapi: If `False`, will disable OpenAPI support for the
            current blueprint.

    Other keyword arguments are directly passed to `flask.Blueprint`.
    """
    super().__init__(
        name,
        import_name,
        static_folder=static_folder,
        static_url_path=static_url_path,
        template_folder=template_folder,
        url_prefix=url_prefix,
        subdomain=subdomain,
        url_defaults=url_defaults,
        root_path=root_path,
        cli_group=cli_group,
    )
    self.tag = tag
    self.enable_openapi = enable_openapi

delete(self, rule, **options)

Shortcut for app.route(methods=['DELETE']).

Source code in apiflask/blueprint.py
def delete(self, rule: str, **options: t.Any):
    """Shortcut for `app.route(methods=['DELETE'])`."""
    return _method_route(self, 'DELETE', rule, options)

get(self, rule, **options)

Shortcut for app.route().

Source code in apiflask/blueprint.py
def get(self, rule: str, **options: t.Any):
    """Shortcut for `app.route()`."""
    return _method_route(self, 'GET', rule, options)

patch(self, rule, **options)

Shortcut for app.route(methods=['PATCH']).

Source code in apiflask/blueprint.py
def patch(self, rule: str, **options: t.Any):
    """Shortcut for `app.route(methods=['PATCH'])`."""
    return _method_route(self, 'PATCH', rule, options)

post(self, rule, **options)

Shortcut for app.route(methods=['POST']).

Source code in apiflask/blueprint.py
def post(self, rule: str, **options: t.Any):
    """Shortcut for `app.route(methods=['POST'])`."""
    return _method_route(self, 'POST', rule, options)

put(self, rule, **options)

Shortcut for app.route(methods=['PUT']).

Source code in apiflask/blueprint.py
def put(self, rule: str, **options: t.Any):
    """Shortcut for `app.route(methods=['PUT'])`."""
    return _method_route(self, 'PUT', rule, options)

route(self, rule, **options)

Decorate a view function or MethodView subclass to register it with the given URL rule and options.

Source code in apiflask/blueprint.py
def route(self, rule: str, **options):
    """Decorate a view function or `MethodView` subclass to register it with
    the given URL rule and options.
    """
    def decorator(f):
        endpoint: str = options.pop('endpoint', f.__name__)
        if isinstance(f, MethodViewType):
            # MethodView class
            view_func = f.as_view(endpoint)
            if hasattr(self, 'enable_openapi') and self.enable_openapi:
                view_func._method_spec = {}
                if not hasattr(view_func, '_spec'):
                    view_func._spec = {}
                for method_name in f.methods:  # method_name: ['GET', 'POST', ...]
                    method = f.__dict__[method_name.lower()]
                    # collect spec info from class attribute "decorators"
                    if hasattr(view_func, '_spec') and view_func._spec != {}:
                        if not hasattr(method, '_spec'):
                            method._spec = view_func._spec
                        else:
                            for key, value in view_func._spec.items():
                                if value is not None and method._spec.get(key) is None:
                                    method._spec[key] = value
                    else:
                        if not hasattr(method, '_spec'):
                            method._spec = {'no_spec': True}
                    if not method._spec.get('summary'):
                        method._spec['summary'] = get_path_summary(
                            method, f'{method_name.title()} {f.__name__}'
                        )
                        method._spec['generated_summary'] = True
                    if not method._spec.get('description'):
                        method._spec['description'] = get_path_description(method)
                        method._spec['generated_description'] = True
                    view_func._method_spec[method_name] = method._spec
        else:
            view_func = f
        self.add_url_rule(rule, endpoint, view_func, **options)
        return f
    return decorator