Custom status codes let you send special messages from your web server to the browser or client. This helps explain what happened with a request beyond the usual success or error.
0
0
Custom status codes in Flask
Introduction
You want to tell the client a request was accepted but processing is not finished yet.
You need to indicate a custom error that is not covered by standard HTTP codes.
You want to create a special response for a specific app feature or API behavior.
You want to improve communication between your server and client with clear signals.
You want to debug or log specific situations with unique status codes.
Syntax
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.route('/example') def example(): return jsonify(message='Custom status code example'), 299
You return a tuple with the response data and the custom status code number.
Status codes should be integers between 100 and 599.
Examples
Returns a simple text response with status code 102 (Processing).
Flask
return 'Processing', 102
Returns JSON with a custom error message and status code 499.
Flask
return jsonify(error='Custom error'), 499
Returns no content with status code 204 (No Content).
Flask
return '', 204
Sample Program
This Flask app has one route '/custom' that sends a JSON message with a custom status code 299. When you visit this URL, the server responds with the message and the special code.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.route('/custom') def custom_status(): # Return a JSON message with a custom status code 299 return jsonify(message='This is a custom status code'), 299 if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Browsers may not recognize custom status codes, so use them mainly for API clients or internal tools.
Always use standard codes when possible for better compatibility.
Custom codes should be documented clearly for anyone using your API.
Summary
Custom status codes let your server send special signals beyond standard HTTP codes.
In Flask, return a tuple with data and the custom code number.
Use custom codes carefully and document them well.