Skip to main content

Response

The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object yourself because Flask.make_response() will take care of that for you. If you want to replace the response object used you can subclass this and set Flask.response_class to your subclass. Changed in 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON. Changed in 1.0: Added max_cookie_size.

Class Attributes

default_mimetype

The default mimetype for responses.
  • Type: str | None
  • Default: "text/html"

autocorrect_location_header

Whether to automatically correct the location header.
  • Type: bool
  • Default: False

Properties

response.max_cookie_size -> int
Read-only view of the MAX_COOKIE_SIZE config key. See werkzeug.wrappers.Response.max_cookie_size in Werkzeug’s docs for more details.

Common Response Attributes (from Werkzeug)

The Flask Response object inherits from Werkzeug’s Response class and provides access to the following common attributes and methods:

Response Data

status_code

The HTTP status code as an integer.
from flask import Response

response = Response('Not Found', status=404)
print(response.status_code)  # 404

status

The HTTP status code and reason phrase.
response = Response('Created', status=201)
print(response.status)  # '201 CREATED'

data

The response body as bytes.
response = Response('Hello, World!')
print(response.data)  # b'Hello, World!'

headers

The response headers.
response = Response('Hello')
response.headers['X-Custom-Header'] = 'value'
response.headers['Content-Type'] = 'text/plain'

Methods

response.set_cookie(
    key: str,
    value: str = '',
    max_age: int | None = None,
    expires: int | float | datetime | None = None,
    path: str | None = '/',
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: str | None = None,
    partitioned: bool = False
) -> None
Sets a cookie.
key
str
required
The name of the cookie
value
str
default:"''"
The value of the cookie
max_age
int | None
default:"None"
The lifetime of the cookie in seconds, or None for a session cookie
expires
int | float | datetime | None
default:"None"
The expiration date/time for the cookie
path
str | None
default:"'/'"
The path for which the cookie is valid
domain
str | None
default:"None"
The domain for which the cookie is valid
secure
bool
default:"False"
Whether the cookie should only be sent over HTTPS
httponly
bool
default:"False"
Whether the cookie should be inaccessible to JavaScript
samesite
str | None
default:"None"
SameSite attribute (‘Lax’, ‘Strict’, or ‘None’)
partitioned
bool
default:"False"
Whether the cookie should be partitioned (CHIPS)
from flask import Response

response = Response('Hello')
response.set_cookie('session_id', 'abc123', max_age=3600, httponly=True)
response.set_cookie('user_pref', 'dark_mode', path='/settings')
response.delete_cookie(
    key: str,
    path: str = '/',
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: str | None = None,
    partitioned: bool = False
) -> None
Deletes a cookie by setting its expiration date in the past.
key
str
required
The name of the cookie to delete
path
str
default:"'/'"
The path for which the cookie was valid
domain
str | None
default:"None"
The domain for which the cookie was valid
secure
bool
default:"False"
Whether the cookie was only sent over HTTPS
httponly
bool
default:"False"
Whether the cookie was inaccessible to JavaScript
samesite
str | None
default:"None"
SameSite attribute (‘Lax’, ‘Strict’, or ‘None’)
partitioned
bool
default:"False"
Whether the cookie was partitioned
response = Response('Logged out')
response.delete_cookie('session_id')

set_data()

response.set_data(value: bytes | str) -> None
Sets the response body data.
response = Response()
response.set_data('Hello, World!')

get_json()

response.get_json(
    force: bool = False,
    silent: bool = False
) -> Any | None
Parse the response data as JSON. Useful in testing.
force
bool
default:"False"
Ignore the mimetype and always try to parse JSON
silent
bool
default:"False"
Return None instead of raising an error on parse failure
# In tests
response = client.get('/api/users')
data = response.get_json()
assert data['username'] == 'alice'

Creating Responses

Flask provides several ways to create responses:

Return from View Function

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    # String response (200 OK by default)
    return 'Hello, World!'

@app.route('/created')
def created():
    # With status code
    return 'Resource created', 201

@app.route('/custom-headers')
def custom_headers():
    # With status code and headers
    return 'OK', 200, {'X-Custom': 'value'}

Using make_response()

from flask import make_response

@app.route('/cookie')
def set_cookie():
    response = make_response('Cookie set')
    response.set_cookie('username', 'alice')
    return response

Direct Response Object

from flask import Response

@app.route('/raw')
def raw_response():
    return Response(
        'Custom response',
        status=200,
        headers={'X-Custom': 'value'},
        mimetype='text/plain'
    )

JSON Responses

from flask import jsonify

@app.route('/api/user')
def get_user():
    # jsonify creates a Response with application/json mimetype
    return jsonify({
        'id': 123,
        'username': 'alice',
        'email': '[email protected]'
    })

Streaming Responses

from flask import Response

@app.route('/stream')
def stream():
    def generate():
        for i in range(10):
            yield f"Line {i}\n"
    
    return Response(generate(), mimetype='text/plain')

Example Usage

from flask import Flask, Response, make_response, jsonify
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/download')
def download():
    response = Response(
        'File content here',
        mimetype='application/octet-stream'
    )
    response.headers['Content-Disposition'] = 'attachment; filename=file.txt'
    return response

@app.route('/login', methods=['POST'])
def login():
    # Authenticate user...
    response = make_response(jsonify({'status': 'logged in'}))
    
    # Set secure session cookie
    response.set_cookie(
        'session_id',
        'secure-token-here',
        max_age=3600,
        httponly=True,
        secure=True,
        samesite='Lax'
    )
    
    return response

@app.route('/logout')
def logout():
    response = make_response('Logged out')
    response.delete_cookie('session_id')
    return response

@app.route('/api/data')
def api_data():
    response = jsonify({
        'users': ['alice', 'bob'],
        'count': 2
    })
    
    # Add custom headers
    response.headers['X-Total-Count'] = '2'
    response.headers['Cache-Control'] = 'no-cache'
    
    return response

@app.route('/redirect-temp')
def redirect_temp():
    response = Response('', status=302)
    response.headers['Location'] = '/new-location'
    return response

Build docs developers (and LLMs) love