Skip to main content

The Response Object

The Response class in Flask is the standard object used to send data back to the client. While it inherits the majority of its functionality from werkzeug.wrappers.Response, it introduces Flask-specific integrations for configuration, JSON handling, and default behavior.

Core Response Behavior

The Response class (found in src/flask/wrappers.py) is designed to work seamlessly with Flask's routing system. Unlike its Werkzeug parent, Flask's Response defaults to an HTML mimetype:

class Response(ResponseBase):
default_mimetype: str | None = "text/html"
json_module = json
autocorrect_location_header = False
# ...

In most cases, developers do not instantiate this class directly. Instead, Flask's make_response utility handles the conversion of various return types into a proper Response instance.

Automatic Response Creation

When a view function returns a value, Flask uses Flask.make_response (in src/flask/app.py) to transform that value into a Response object. This method supports several return types:

  • Strings/Bytes: Converted into a response with the default text/html mimetype.
  • Dictionaries/Lists: Automatically serialized to JSON with application/json mimetype.
  • Tuples: Allow specifying status codes and headers alongside the body.
  • Generators: Used for streaming responses.

Working with Tuples

A common pattern in Flask is returning a tuple from a view. The make_response method logic in src/flask/app.py unpacks these tuples:

# From src/flask/app.py
if isinstance(rv, tuple):
len_rv = len(rv)
if len_rv == 3:
rv, status, headers = rv
elif len_rv == 2:
if isinstance(rv[1], (Headers, dict, tuple, list)):
rv, headers = rv
else:
rv, status = rv

This allows for flexible return signatures in views, as seen in tests/test_basic.py:

@app.route("/full_tuple")
def from_full_tuple():
return (
"Meh",
400,
{"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},
)

Manual Response Management

For finer control, you can manually instantiate the Response class or use the make_response helper from src/flask/helpers.py.

The make_response Helper

The make_response helper is useful when you need to modify a response object (like adding headers) before returning it from a view:

from flask import make_response, render_template

def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Custom-Header'] = 'Value'
return response

Direct Instantiation

You can also create a Response object directly, which is often used in tests or specialized utility functions:

# Example from tests/test_basic.py
@app.route("/response_headers")
def from_response_headers():
return (
flask.Response(
"Hello world", 404, {"Content-Type": "text/html", "X-Foo": "Baz"}
),
{"Content-Type": "text/plain", "X-Foo": "Bar", "X-Bar": "Foo"},
)

JSON Responses

Flask provides specialized handling for JSON. When a view returns a dict or list, Flask invokes the JSONProvider.response method (in src/flask/json/provider.py). This method ensures the response has the correct application/json mimetype:

# From src/flask/json/provider.py
def response(self, *args: t.Any, **kwargs: t.Any) -> Response:
obj = self._prepare_response_obj(args, kwargs)
return self._app.response_class(self.dumps(obj), mimetype="application/json")

The jsonify() function is a wrapper around this provider logic, allowing you to create JSON responses explicitly while still benefiting from the application's configured JSON encoder.

The Response object provides the set_cookie and delete_cookie methods for managing client-side cookies. Flask integrates these with the application configuration via the max_cookie_size property.

In src/flask/wrappers.py, the Response class dynamically checks the MAX_COOKIE_SIZE configuration:

@property
def max_cookie_size(self) -> int:
if current_app:
return current_app.config["MAX_COOKIE_SIZE"]
return super().max_cookie_size

If a cookie exceeds this size (defaulting to 4093 bytes as per Werkzeug), Flask will issue a warning during the set_cookie call. This is particularly relevant when using session cookies, as seen in src/flask/sessions.py.

Customizing Response Behavior

If your application requires a different default behavior (such as a different default mimetype or additional methods), you can subclass Response and assign it to app.response_class:

from flask import Flask, Response

class MyResponse(Response):
default_mimetype = "application/xml"

app = Flask(__name__)
app.response_class = MyResponse

By setting response_class, all automatic response creation (via make_response and jsonify) will use your custom class instead of the default src.flask.wrappers.Response.