API error handling helps your app tell users when something goes wrong in a clear way. It stops crashes and gives useful messages.
0
0
API error handling in Flask
Introduction
When a user sends wrong data to your API.
When a requested item is not found in the database.
When the server has an internal problem.
When a user tries to access a resource without permission.
When the API endpoint does not exist.
Syntax
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(404) def not_found(error): return jsonify({'error': 'Not found'}), 404 @app.errorhandler(500) def internal_error(error): return jsonify({'error': 'Server error'}), 500
Use @app.errorhandler(status_code) to catch specific HTTP errors.
Return a JSON response with an error message and the correct HTTP status code.
Examples
This handles 400 errors when the client sends bad data.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(400) def bad_request(error): return jsonify({'error': 'Bad request'}), 400
This handles 403 errors when a user tries to access something they shouldn't.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(403) def forbidden(error): return jsonify({'error': 'Forbidden access'}), 403
This catches all other errors not specifically handled and returns a 500 error.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(Exception) def handle_exception(error): return jsonify({'error': 'Something went wrong'}), 500
Sample Program
This simple API returns an item by id. If the id is missing, it returns a 404 error with a message. It also handles general 404 and 500 errors gracefully.
Flask
from flask import Flask, jsonify, request app = Flask(__name__) items = {'1': 'apple', '2': 'banana'} @app.route('/item/<id>') def get_item(id): if id not in items: return jsonify({'error': 'Item not found'}), 404 return jsonify({'item': items[id]}) @app.errorhandler(404) def not_found(error): return jsonify({'error': 'Not found'}), 404 @app.errorhandler(500) def internal_error(error): return jsonify({'error': 'Server error'}), 500 if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always return JSON for API errors so clients can understand the problem easily.
Use proper HTTP status codes to match the error type.
Test your error handlers by calling routes that cause errors.
Summary
API error handling helps your app respond clearly when things go wrong.
Use @app.errorhandler to catch errors and return JSON messages.
Always include the right HTTP status code with your error response.