Using Flask Restful with Blueprint

Flask is one of the most popular Python web frameworks. If you want to use Flask to develop REST service, you may want to check Twilio's Flask Restful .

The common way to group flask application is by refactoring them into smaller blueprints.

Until recently, integrating Blueprint with Flask Restful may present problems. Now Blueprint instance can be passed directly into init_app method.

blueprint = Blueprint('game_api', __name__, url_prefix='/1.0/games')
api = restful.Api()
api.init_app(blueprint)

class GameById(restful.Resource):
	def get(self, id):
		game = utils.get_mongo().games.find_one({'_id': ObjectId(id)})
		game = prepare_model(game)  #do some formatting
		return jsonify(game)

api.add_resource(GameById, '/<int:id>')
	 

Nothing changes on main app module.

import games_blueprint
....

app = Flask(__name__)
app.register_blueprint(games_blueprint.blueprint)
utils.create_mongo_instance(app) #method to ensure only 1 PyMongo instance is created

In the above example I use a module (in this case "utils") to provide accessors and factory methods for shared instances.