How to Return Error Response in Flask API Correctly
In Flask API, return an error response by using
jsonify to create a JSON message and specify the HTTP status code as a second return value, like return jsonify({'error': 'message'}), 400. This sends a clear error message with the correct HTTP status to the client.Syntax
Use jsonify() to create a JSON response body and return it with an HTTP status code as a tuple. The first part is the JSON data, and the second is the status code number.
jsonify({'error': 'message'}): creates a JSON error message.400: HTTP status code indicating a bad request error.- Return both as
return jsonify(...), status_code.
python
return jsonify({'error': 'Invalid input'}), 400
Example
This example shows a Flask API endpoint that returns a 400 error response with a JSON error message when the input is missing a required parameter.
python
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/api/data', methods=['POST']) def api_data(): data = request.json if not data or 'name' not in data: return jsonify({'error': 'Missing "name" parameter'}), 400 return jsonify({'message': f'Hello, {data["name"]}!'}), 200 if __name__ == '__main__': app.run(debug=True)
Output
When POSTing JSON without 'name': HTTP 400 with {"error": "Missing \"name\" parameter"}
When POSTing JSON with 'name': HTTP 200 with {"message": "Hello, <name>!"}
Common Pitfalls
Common mistakes include:
- Returning plain strings instead of JSON, which can confuse clients expecting JSON.
- Not setting the HTTP status code, so the client assumes success (200) even on errors.
- Using incorrect status codes that do not match the error type.
Always use jsonify and proper HTTP status codes for clarity.
python
from flask import jsonify # Wrong way: returns string without status code return 'Error: Missing data' # Right way: returns JSON with status code return jsonify({'error': 'Missing data'}), 400
Quick Reference
| HTTP Status Code | Meaning | When to Use |
|---|---|---|
| 400 | Bad Request | Client sent invalid or missing data |
| 401 | Unauthorized | Authentication required or failed |
| 403 | Forbidden | Client not allowed to access resource |
| 404 | Not Found | Requested resource does not exist |
| 500 | Internal Server Error | Server encountered an error |
Key Takeaways
Use jsonify() to return JSON error messages in Flask APIs.
Always include the correct HTTP status code as the second return value.
Avoid returning plain strings or missing status codes for errors.
Choose the HTTP status code that best matches the error type.
Clear error responses help clients handle API errors properly.