0
0
Flaskframework~5 mins

API versioning with blueprints in Flask

Choose your learning style9 modes available
Introduction

API versioning helps keep different versions of your app's features separate. Blueprints let you organize these versions cleanly.

You want to update your API without breaking old apps using it.
You need to support multiple versions of your API at the same time.
You want to keep your code organized by grouping routes by version.
You want to test new features in a new API version before full release.
Syntax
Flask
from flask import Blueprint

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

@v1.route('/hello')
def hello_v1():
    return 'Hello from API v1'

@v2.route('/hello')
def hello_v2():
    return 'Hello from API v2'

app.register_blueprint(v1)
app.register_blueprint(v2)

Each Blueprint has a url_prefix to separate versions in the URL.

Register each Blueprint with the main Flask app to activate routes.

Examples
This creates a v1 Blueprint with a users route under /api/v1/users.
Flask
v1 = Blueprint('v1', __name__, url_prefix='/api/v1')

@v1.route('/users')
def users_v1():
    return 'Users list from v1'
This creates a v2 Blueprint with a users route under /api/v2/users that can return more data.
Flask
v2 = Blueprint('v2', __name__, url_prefix='/api/v2')

@v2.route('/users')
def users_v2():
    return 'Users list from v2 with extra info'
Sample Program

This Flask app uses two Blueprints to serve two API versions. Visiting /api/v1/hello returns a message from version 1, and /api/v2/hello returns a message from version 2.

Flask
from flask import Flask, Blueprint

app = Flask(__name__)

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

@v1.route('/hello')
def hello_v1():
    return 'Hello from API v1'

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

@v2.route('/hello')
def hello_v2():
    return 'Hello from API v2'

app.register_blueprint(v1)
app.register_blueprint(v2)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Use clear URL prefixes like /api/v1 to avoid confusion.

Keep your versioned code separate to make updates easier.

Test each version independently to avoid breaking changes.

Summary

API versioning with Blueprints helps organize different API versions cleanly.

Use url_prefix in Blueprints to separate versions in URLs.

Register each version Blueprint with your Flask app to activate routes.