Given two blueprints registered with different URL prefixes for API versions, what URL will respond with 'Hello from v1'?
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 v1' v2 = Blueprint('v2', __name__, url_prefix='/api/v2') @v2.route('/hello') def hello_v2(): return 'Hello from v2' app.register_blueprint(v1) app.register_blueprint(v2)
Think about how the url_prefix affects the route URL.
The blueprint v1 is registered with prefix /api/v1. So the route /hello inside it becomes /api/v1/hello. Only option B matches this.
Choose the code snippet that correctly registers two blueprints v1 and v2 with URL prefixes /api/v1 and /api/v2 respectively.
Remember where the url_prefix should be set: at blueprint creation or registration.
Setting url_prefix at blueprint creation is the recommended way. Option D does this correctly. Option D sets prefixes at registration but without blueprints having no prefix, which is allowed but less common. Option D tries to set url_prefix after registration which does nothing. Option D misses prefixes at blueprint creation.
Given blueprints registered for /api/v1 and /api/v2, what happens when a client requests /api/v3/hello?
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 v1' v2 = Blueprint('v2', __name__, url_prefix='/api/v2') @v2.route('/hello') def hello_v2(): return 'Hello from v2' app.register_blueprint(v1) app.register_blueprint(v2)
Think about what happens if no route matches the requested URL.
Since no blueprint or route is registered for /api/v3/hello, Flask returns a 404 Not Found error.
Consider this code snippet. The route /hello is defined inside blueprint v1 with prefix /api/v1. But accessing /api/v1/hello returns 404. What is the likely cause?
from flask import Flask, Blueprint app = Flask(__name__) v1 = Blueprint('v1', __name__, url_prefix='/api/v1') @app.route('/hello') def hello(): return 'Hello from v1' app.register_blueprint(v1)
Check where the route decorator is applied.
The route is decorated on app instead of v1 blueprint. So it is not part of the /api/v1 prefix routes. Accessing /api/v1/hello returns 404 because no such route exists under the blueprint.
Why is using blueprints with URL prefixes for API versioning a good practice in Flask applications?
Think about how versioning affects code organization and client support.
Blueprints with URL prefixes let you keep different API versions in separate code modules. This helps maintain old versions while developing new ones and allows clients to choose which version to use.