Flask blueprints are a powerful way to organize your web application into modular components. Think of blueprints as mini-applications that can be combined to create larger applications. They're especially useful for REST APIs where you want to group related endpoints together.
As your API grows, putting all routes in a single file becomes unwieldy. Blueprints solve this by letting you:
A blueprint is created separately from your main Flask app, then registered with the app. The blueprint defines routes using decorators just like a regular Flask app, but the routes don't become active until the blueprint is registered.
When building REST APIs with blueprints, follow these conventions:
/api/v1/resource for collections, /api/v1/resource/id for specific items)Blueprints make it easy to maintain these patterns consistently across different resource types in your API.
1from flask import Flask, Blueprint, jsonify
2
3# Create a blueprint for user-related routes
4users_bp = Blueprint('users', __name__)
5
6# Sample data
7users = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
8
9@users_bp.route('/api/v1/users', methods=['GET'])
10def get_users():
11 return jsonify(users), 200
12
13@users_bp.route('/api/v1/users/<int:user_id>', methods=['GET'])
14def get_user(user_id):
15 user = next((u for u in users if u['id'] == user_id), None)
16 if not user:
17 return jsonify({'error': 'User not found'}), 404
18 return jsonify(user), 200
19
20# Create the main Flask app
21app = Flask(__name__)
22
23# Register the blueprint with the app
24app.register_blueprint(users_bp)