Last modified: Nov 15, 2024 By Alexander Williams

Flask make_response(): Create Custom HTTP Responses with Ease

Flask's make_response() function is a powerful tool that allows developers to create custom HTTP responses with fine-grained control over headers, cookies, and status codes.

Basic Usage of make_response()

The basic syntax of make_response() allows you to create a response object from your return value. Here's a simple example:


from flask import Flask, make_response

app = Flask(__name__)

@app.route('/')
def hello():
    response = make_response('Hello, World!')
    response.status_code = 200
    return response

Setting Headers

You can easily set custom headers using make_response(). This is particularly useful when you need to specify content types or security headers.


@app.route('/custom-header')
def custom_header():
    response = make_response('Content with custom header')
    response.headers['Custom-Header'] = 'Special-Value'
    response.headers['Content-Type'] = 'text/plain'
    return response

Working with Cookies

One of the most common uses of make_response() is setting cookies. Unlike Flask sessions, cookies are stored on the client side.


@app.route('/set-cookie')
def set_cookie():
    response = make_response('Cookie has been set!')
    response.set_cookie('user_id', '12345', max_age=3600)
    return response

Custom Status Codes

Status codes are crucial for proper HTTP communication. make_response() makes it easy to send custom status codes:


@app.route('/not-found')
def not_found():
    response = make_response('Resource not found', 404)
    return response

JSON Responses

When building APIs, you'll often need to send JSON responses. Here's how to create a custom JSON response:


from flask import jsonify

@app.route('/api/data')
def get_data():
    data = {'name': 'John', 'age': 30}
    response = make_response(jsonify(data))
    response.headers['Content-Type'] = 'application/json'
    return response

Error Handling

You can use make_response() with Flask's error handlers to create custom error responses. This is particularly useful when building RESTful APIs.


@app.errorhandler(404)
def not_found_error(error):
    response = make_response(jsonify({'error': 'Resource not found'}), 404)
    return response

Integrating with Redirects

You can combine make_response() with Flask's redirect functionality for advanced redirect scenarios.

Conclusion

Flask's make_response() is a versatile function that gives you complete control over HTTP responses. Understanding its capabilities is crucial for building robust web applications.