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.post shortcuts (Flask 2.0+)
  • url_for builds URLs by endpoint
  • Trailing slash behavior matters

More most-asked Flask questions

← All Flask questions