Flask interview question · Most asked
How does routing work in Flask, including variable rules and HTTP methods?
Summary
@app.route('/path/<converter:name>', methods=[...]) (or @app.get/@app.post shortcuts) maps URLs to view functions; converters like int, float, path, uuid and string parse and validate URL segments.
Longer Answer
url_for('view_name', **params) builds URLs from endpoint names, which avoids hard-coded paths. Routes ending with / redirect requests without the slash; routes without a trailing slash 404 on /path/. Custom converters subclass BaseConverter.
Code Example
@app.get("/users/<int:user_id>")
def get_user(user_id: int):
...
@app.route("/files/<path:filename>", methods=["GET", "DELETE"])
def file_op(filename: str):
if request.method == "DELETE":
...
url_for("get_user", user_id=5) # '/users/5'
Key Points
<int:id>,<path:p>,<uuid:u>converters@app.get/@app.postshortcuts (Flask 2.0+)url_forbuilds URLs by endpoint- Trailing slash behavior matters
More most-asked Flask questions
- How do Flask sessions work and what are their security implications?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How do you access request data and build responses in Flask?
- How do you implement user authentication in Flask?