How to Set Status Code in Flask: Simple Guide
In Flask, you set the HTTP status code by returning a tuple from your route function with
response_body and status_code, like return 'OK', 200. Alternatively, use the make_response() function to create a response object and set its status_code property.Syntax
There are two common ways to set the status code in Flask:
- Return tuple: Return a tuple with the response body and the status code.
- Response object: Use
make_response()to create a response, then set itsstatus_code.
Example syntax:
return <response_body>, <status_code> response = make_response(<response_body>) response.status_code = <status_code> return response
python
return 'Hello, world!', 200 from flask import make_response response = make_response('Hello, world!') response.status_code = 200 return response
Example
This example shows a Flask app with two routes: one returns a 200 OK status, the other returns a 404 Not Found status using the tuple method and the make_response method.
python
from flask import Flask, make_response app = Flask(__name__) @app.route('/success') def success(): return 'Success!', 200 @app.route('/notfound') def not_found(): response = make_response('Not Found', 404) return response if __name__ == '__main__': app.run(debug=True)
Output
When you visit /success, the browser shows 'Success!' with status code 200.
When you visit /notfound, the browser shows 'Not Found' with status code 404.
Common Pitfalls
Common mistakes when setting status codes in Flask include:
- Returning only the response body without the status code, which defaults to 200.
- Returning the status code as a string instead of an integer.
- Not using
make_responsewhen you want to set headers or cookies along with the status code.
Example of wrong and right ways:
python
from flask import Flask app = Flask(__name__) @app.route('/wrong') def wrong(): # Wrong: status code as string, ignored by Flask return 'Error', '404' @app.route('/right') def right(): # Right: status code as integer return 'Error', 404
Quick Reference
| Method | Usage | Example |
|---|---|---|
| Return tuple | Return (body, status_code) | return 'OK', 200 |
| make_response | Create response, set status_code | resp = make_response('OK') resp.status_code = 200 return resp |
Key Takeaways
Return a tuple with response body and integer status code to set status in Flask.
Use make_response() to customize response objects including status codes.
Always use integer status codes, not strings.
Default status code is 200 if none is specified.
Setting status code correctly helps browsers and clients understand your response.