Response Object (Flask)

A Flask Response represents the HTTP reply sent back to the client, carrying the body, status code, headers, and cookies. Flask builds one automatically from your view's return value, or you can construct it explicitly with make_response().

Flask

When a view returns a string, Flask wraps it in a Response with status 200 and a text/html content type. When you need to set cookies, custom headers, or a non-default status, build the response yourself so you can mutate it before returning.

make_response() turns any valid view return into a real Response object you can modify. From there you call resp.set_cookie(), assign resp.headers[...], or set resp.status_code.

For data APIs you usually return jsonify(...) instead, which produces a Response with the application/json content type already set.

Syntax

from flask import make_response
resp = make_response(body, status)
resp.headers["X-Foo"] = "bar"

Examples

Python

from flask import make_response

@app.route("/set")
def set_cookie():
    resp = make_response("Cookie set")
    resp.set_cookie("theme", "dark", max_age=3600)
    return resp

Learn it in a lesson

See also

Back to the Dictionary