How to Use make_response in Flask for Custom HTTP Responses
In Flask, use
make_response to create a response object that you can customize with headers, cookies, or status codes before sending it back to the client. It wraps your content into a full HTTP response allowing more control than returning plain strings or templates.Syntax
The make_response function takes your response content (string, dict, or template output) and returns a response object. You can then modify this object by setting headers, cookies, or status codes.
make_response(response, status=None, headers=None)response: The content to send (string, dict, etc.)status: Optional HTTP status code (e.g., 200, 404)headers: Optional dictionary of HTTP headers
python
response = make_response('Hello, world!', 200, {'Content-Type': 'text/plain'})
Example
This example shows how to use make_response to create a response with custom headers and a cookie.
python
from flask import Flask, make_response app = Flask(__name__) @app.route('/') def index(): # Create a response with text content response = make_response('Welcome to Flask!') # Set a custom header response.headers['X-Custom-Header'] = 'MyValue' # Set a cookie response.set_cookie('user_id', '12345') # Set status code response.status_code = 200 return response if __name__ == '__main__': app.run(debug=True)
Output
When you visit '/', the browser receives 'Welcome to Flask!' with a custom header 'X-Custom-Header: MyValue' and a cookie 'user_id=12345'. The HTTP status code is 200 OK.
Common Pitfalls
Common mistakes when using make_response include:
- Returning the response content directly instead of the response object, which prevents setting headers or cookies.
- Forgetting to set the status code on the response object if you want a code other than 200.
- Trying to set headers or cookies on a string instead of the response object.
python
from flask import Flask, make_response app = Flask(__name__) @app.route('/wrong') def wrong(): # Wrong: returning string directly, can't set headers return 'Hello' @app.route('/right') def right(): response = make_response('Hello') response.headers['X-Test'] = 'value' return response
Quick Reference
Tips for using make_response effectively:
- Use
make_responsewhen you need to add headers, cookies, or change status codes. - Always return the response object, not just the content.
- Set cookies with
response.set_cookie(). - Modify headers via
response.headers. - Set status code with
response.status_code.
Key Takeaways
Use make_response to create a full HTTP response object from your content.
Modify headers, cookies, and status codes on the response object before returning it.
Always return the response object, not just a string or template output.
Set cookies with response.set_cookie() and headers with response.headers.
make_response gives you more control over HTTP responses in Flask.