Skip to main content

Blueprint

Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later. A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as Flask, but defers the need for an application by recording them for later registration.

Constructor

Blueprint(
    name: str,
    import_name: str,
    static_folder: str | os.PathLike[str] | None = None,
    static_url_path: str | None = None,
    template_folder: str | os.PathLike[str] | None = None,
    url_prefix: str | None = None,
    subdomain: str | None = None,
    url_defaults: dict[str, Any] | None = None,
    root_path: str | None = None,
    cli_group: str | None = None,
)
name
str
required
The name of the blueprint. Will be prepended to each endpoint name.
import_name
str
required
The name of the blueprint package, usually __name__. This helps locate the root_path for the blueprint.
static_folder
str | os.PathLike[str] | None
default:"None"
A folder with static files that should be served by the blueprint’s static route. The path is relative to the blueprint’s root path. Blueprint static files are disabled by default.
static_url_path
str | None
default:"None"
The url to serve static files from. Defaults to static_folder. If the blueprint does not have a url_prefix, the app’s static route will take precedence.
template_folder
str | os.PathLike[str] | None
default:"None"
A folder with templates that should be added to the app’s template search path. The path is relative to the blueprint’s root path. Blueprint templates are disabled by default.
url_prefix
str | None
default:"None"
A path to prepend to all of the blueprint’s URLs, to make them distinct from the rest of the app’s routes.
subdomain
str | None
default:"None"
A subdomain that blueprint routes will match on by default.
url_defaults
dict[str, Any] | None
default:"None"
A dict of default values that blueprint routes will receive by default.
root_path
str | None
default:"None"
By default, the blueprint will automatically set this based on import_name. In certain situations this automatic detection can fail, so the path can be specified manually instead.
cli_group
str | None
default:"None"
The name of the CLI group for commands registered with this blueprint.

Example

from flask import Blueprint

api = Blueprint('api', __name__, url_prefix='/api')

Routing Methods

route()

Decorate a view function to register it with the given URL rule and options.
@blueprint.route(rule: str, **options) -> Callable
rule
str
required
The URL rule string.
methods
list[str]
default:"['GET']"
A list of HTTP methods this rule should handle.
endpoint
str
default:"None"
The endpoint name for the route. Defaults to the name of the view function.

Example

@api.route('/users')
def list_users():
    return {'users': []}

@api.route('/users/<int:user_id>')
def get_user(user_id):
    return {'user_id': user_id}

add_url_rule()

Register a rule for routing incoming requests and building URLs.
blueprint.add_url_rule(
    rule: str,
    endpoint: str | None = None,
    view_func: Callable | None = None,
    **options
) -> None

HTTP Method Shortcuts

Blueprints provide shortcuts for common HTTP methods:
@blueprint.get(rule: str, **options)
@blueprint.post(rule: str, **options)
@blueprint.put(rule: str, **options)
@blueprint.delete(rule: str, **options)
@blueprint.patch(rule: str, **options)

Example

@api.get('/status')
def get_status():
    return {'status': 'ok'}

@api.post('/data')
def create_data():
    return {'created': True}

Request Handling Hooks

before_request()

Register a function to run before each request that the blueprint handles.
@blueprint.before_request
def before_request_func() -> None | Response:
    pass

Example

@api.before_request
def require_auth():
    if not request.headers.get('Authorization'):
        abort(401)

before_app_request()

Register a function to run before every request, not just those handled by this blueprint.
@blueprint.before_app_request
def before_app_request_func() -> None | Response:
    pass

after_request()

Register a function to run after each request that the blueprint handles.
@blueprint.after_request
def after_request_func(response: Response) -> Response:
    return response
response
Response
required
The response object that will be sent to the client.

Example

@api.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

after_app_request()

Register a function to run after every request, not just those handled by this blueprint.
@blueprint.after_app_request
def after_app_request_func(response: Response) -> Response:
    return response

teardown_request()

Register a function to be called when the request context is popped for requests handled by this blueprint.
@blueprint.teardown_request
def teardown_request_func(exception: BaseException | None = None) -> None:
    pass

teardown_app_request()

Register a function to be called when the request context is popped for all requests.
@blueprint.teardown_app_request
def teardown_app_request_func(exception: BaseException | None = None) -> None:
    pass

Error Handling

errorhandler()

Register a function to handle errors for routes in this blueprint.
@blueprint.errorhandler(code_or_exception: type[Exception] | int)
def error_handler(error: Exception) -> Response:
    return response
code_or_exception
type[Exception] | int
required
The HTTP status code as an integer or an exception class.

Example

@api.errorhandler(404)
def api_not_found(error):
    return {'error': 'Resource not found'}, 404

@api.errorhandler(ValueError)
def handle_value_error(error):
    return {'error': str(error)}, 400

app_errorhandler()

Register a function to handle errors for all requests, not just those handled by this blueprint.
@blueprint.app_errorhandler(code_or_exception: type[Exception] | int)
def error_handler(error: Exception) -> Response:
    return response

register_error_handler()

Non-decorator alternative to errorhandler().
blueprint.register_error_handler(
    code_or_exception: type[Exception] | int,
    f: Callable
) -> None

Template Context

context_processor()

Register a template context processor function for templates rendered from this blueprint’s views.
@blueprint.context_processor
def context_processor_func() -> dict:
    return {'key': 'value'}

Example

@api.context_processor
def inject_api_version():
    return {'api_version': '2.0'}

app_context_processor()

Register a template context processor function for all templates.
@blueprint.app_context_processor
def app_context_processor_func() -> dict:
    return {'key': 'value'}

app_template_filter()

Register a custom template filter available in all templates.
@blueprint.app_template_filter(name: str | None = None)
def filter_func(value):
    return modified_value

app_template_global()

Register a custom template global function available in all templates.
@blueprint.app_template_global(name: str | None = None)
def global_func():
    return value

app_template_test()

Register a custom template test available in all templates.
@blueprint.app_template_test(name: str | None = None)
def test_func(value):
    return True or False

URL Building

url_defaults()

Register a function to modify keyword arguments when generating URLs for this blueprint.
@blueprint.url_defaults
def url_defaults_func(endpoint: str, values: dict) -> None:
    pass

app_url_defaults()

Register a function to modify keyword arguments when generating all URLs.
@blueprint.app_url_defaults
def app_url_defaults_func(endpoint: str, values: dict) -> None:
    pass

url_value_preprocessor()

Register a URL value preprocessor function for this blueprint.
@blueprint.url_value_preprocessor
def url_value_preprocessor_func(endpoint: str, values: dict) -> None:
    pass

app_url_value_preprocessor()

Register a URL value preprocessor function for all requests.
@blueprint.app_url_value_preprocessor
def app_url_value_preprocessor_func(endpoint: str, values: dict) -> None:
    pass

Registration

register_blueprint()

Register a nested blueprint on this blueprint.
blueprint.register_blueprint(blueprint: Blueprint, **options) -> None
blueprint
Blueprint
required
The blueprint to register.
url_prefix
str
default:"None"
Override the nested blueprint’s url_prefix.

Example

api_v1 = Blueprint('api_v1', __name__)
api_v2 = Blueprint('api_v2', __name__)

api = Blueprint('api', __name__, url_prefix='/api')
api.register_blueprint(api_v1, url_prefix='/v1')
api.register_blueprint(api_v2, url_prefix='/v2')

app.register_blueprint(api)

record()

Register a function that is called when the blueprint is registered on the application.
blueprint.record(func: Callable[[BlueprintSetupState], None]) -> None

record_once()

Like record() but the function is only called once, even if the blueprint is registered multiple times.
blueprint.record_once(func: Callable[[BlueprintSetupState], None]) -> None

Other Utility Methods

open_resource()

Open a resource file relative to root_path for reading.
blueprint.open_resource(
    resource: str,
    mode: str = "rb",
    encoding: str | None = "utf-8"
) -> IO
resource
str
required
Path to the resource relative to root_path.
mode
str
default:"'rb'"
Open the file in this mode. Only reading is supported.
encoding
str | None
default:"'utf-8'"
Open the file with this encoding when opening in text mode.

Complete Example

from flask import Blueprint, jsonify, request

# Create blueprint
api = Blueprint('api', __name__, url_prefix='/api/v1')

# Add routes
@api.route('/users')
def list_users():
    return jsonify({'users': []})

@api.post('/users')
def create_user():
    data = request.get_json()
    return jsonify({'id': 1, **data}), 201

# Add hooks
@api.before_request
def check_auth():
    if not request.headers.get('X-API-Key'):
        return jsonify({'error': 'Unauthorized'}), 401

@api.after_request
def add_headers(response):
    response.headers['X-API-Version'] = '1.0'
    return response

# Error handling
@api.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Not found'}), 404

# Register with app
from flask import Flask
app = Flask(__name__)
app.register_blueprint(api)

Build docs developers (and LLMs) love