View Function (Flask)

A view function in Flask is the Python function attached to a route. It receives the request, runs your logic, and returns the response — a string, a rendered template, JSON, or a Response object.

Flask

Every page or endpoint in a Flask app is backed by a view function. Flask calls it when a matching URL is requested and turns its return value into an HTTP response automatically.

A view can return a plain string (becomes HTML with status 200), a tuple of (body, status_code), a tuple of (body, status, headers), the result of render_template(), or anything jsonify() produces. Returning a tuple is the quick way to set a status code like 404.

View functions are also called 'views', which can be confusing if you come from Django where 'view' usually means a class. In plain Flask they are just functions; class-based equivalents exist via MethodView.

Syntax

@app.route("/")
def index():
    return "response body", 200

Examples

Python

@app.route("/missing")
def missing():
    return "Not here", 404

@app.route("/headers")
def with_headers():
    return "OK", 200, {"X-Custom": "yes"}

Learn it in a lesson

See also

Back to the Dictionary