python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.16k stars 335 forks source link

"/" route cannot be defined after Api() call #523

Closed Jc-L closed 1 year ago

Jc-L commented 1 year ago

Minimal Code to reproduce issue

from flask import Flask
from flask_restx import Api

app = Flask(__name__)

# NB: moving this line after the `route('/')` definition makes it work
api = Api(app, version='1.0', title='MyAPI', doc='/api')

@app.route('/')
def index():
    return 'OK'

app.run(debug=True)

Repro Steps (if applicable)

  1. The provided code answers a 404 on a request on /

However, if the call to API() is done after the setting of the / route ,then things work as expected.

Expected Behavior

Requests to / should answer properly.

Actual Behavior

Requests to / answer with a 404.

Error Messages/Stack Trace

N/A

Environment

Additional Context

Already mentioned in https://github.com/python-restx/flask-restx/issues/452 as a question, but seems more a bug.

peter-doggart commented 1 year ago

There is a full discussion about this over on the old project by the maintainers: https://github.com/noirbizarre/flask-restplus/issues/712#issuecomment-541187078

I don't think we can call it a bug, because the code explicitly sets out this is the desired response: https://github.com/python-restx/flask-restx/blob/f755aeb02fcf293c669207cd9cb0b75bb90aff0c/flask_restx/api.py#L447-L448

The issue is that this project uses the root view to build other URLs during API creation, therefore it must ensure the root view is created before the API is initialized to allow this to happen. As other users have pointed out, that is why it works correctly if you register the root view first.

Maybe we should make this clearer in the docs?

Jc-L commented 1 year ago

Thanks @peter-doggart. I reached the render_root() while investigating, but from a user perspective, the final behavior was unexpected and needed some time to be narrowed down (hence the bug label).

I understand from the discussion that there is no simple way to go around this. Making it appear in the documentation would indeed be helpful to avoid users scratching their heads on this.

peter-doggart commented 1 year ago

There is now a warning about this behaviour in the Quick Start Guide