Flask-Restful, like all properly implemented Flask extensions, supports two methods of registering itself:
- With the app at instantiation (as you are trying to do with
Api(current_app)
) - At a later point using
api.init_app(app)
The canonical way of dealing with the circular imports issue is to use the second pattern and import the instantiated extension in your create_app
function and register the extension using the init_app
method:
# app/resource/__init__.py
from resource.hello_world import HelloWorld
api = restful.Api(prefix='/api/v1') # Note, no app
api.add_resource(HelloWorld, '/hello')
# We could actually register our API on a blueprint
# and then import and register the blueprint as normal
# but that's an alternate we will leave for another day
# bp = Blueprint('resource', __name__, url_prefix='/api')
# api.init_app(bp)
And then in your create_app
call you would simply load and register the api:
def create_app():
# ... snip ...
# We import our extension
# and register it with our application
# without any circular references
# Our handlers can use `current_app`, as you already know
from app.resource import api
api.init_app(app)