API error handling helps your app tell users when something goes wrong in a clear way. It stops crashes and gives useful messages.
API error handling in 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.
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(400) def bad_request(error): return jsonify({'error': 'Bad request'}), 400
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(403) def forbidden(error): return jsonify({'error': 'Forbidden access'}), 403
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(Exception) def handle_exception(error): return jsonify({'error': 'Something went wrong'}), 500
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.
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)
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.
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.
Practice
@app.errorhandler in a Flask API?Solution
Step 1: Understand the role of
This decorator is used to catch errors that happen during API requests.@app.errorhandlerStep 2: Recognize its use for custom responses
It allows you to send back clear messages and proper HTTP status codes when errors occur.Final Answer:
To catch specific errors and return custom responses -> Option CQuick Check:
@app.errorhandlercatches errors [OK]
- Thinking it defines routes
- Confusing it with app.run()
- Assuming it manages database connections
Solution
Step 1: Identify correct decorator usage
The@app.errorhandlerdecorator takes an integer status code like 404 without quotes.Step 2: Check function signature and return
The handler function should accept an error argument and return a response with the status code.Final Answer:
@app.errorhandler(404)\ndef not_found(error):\n return 'Not Found', 404 -> Option AQuick Check:
Correct decorator and function signature = @app.errorhandler(404) def not_found(error): return 'Not Found', 404 [OK]
- Using @app.route instead of @app.errorhandler
- Passing status code as string '404'
- Omitting the error parameter in handler function
from flask import abort, jsonify
@app.errorhandler(400)
def bad_request(error):
return jsonify({'error': 'Bad Request'}), 400
@app.route('/test')
def test():
abort(400)What will be the JSON response and status code when accessing
/test?Solution
Step 1: Understand abort triggers error handler
Theabort(400)call triggers the 400 error handler defined by@app.errorhandler(400).Step 2: Check handler return value
The handler returns a JSON dictionary with the error message and status code 400.Final Answer:
{"error": "Bad Request"} with status code 400 -> Option AQuick Check:
abort triggers handler response JSON + 400 [OK]
- Expecting plain text instead of JSON
- Assuming default Flask error page shows
- Missing status code in response
@app.errorhandler(500)
def internal_error():
return {'error': 'Server Error'}, 500Solution
Step 1: Check function signature for error handlers
Error handler functions must accept one parameter for the error object.Step 2: Identify missing parameter
The functioninternal_errorhas no parameters, so Flask will raise a TypeError.Final Answer:
The handler function must accept an error parameter -> Option DQuick Check:
Error handler functions need error argument [OK]
- Omitting the error parameter
- Using string status codes
- Confusing errorhandler with route decorator
KeyError raised in your routes. Which of the following is the best way to implement this?Solution
Step 1: Use exception class in errorhandler
To catch a specific Python error likeKeyError, use it directly in@app.errorhandler(KeyError).Step 2: Return JSON with appropriate status code
Return a JSON message and HTTP 400 (bad request) status code to indicate client error.Final Answer:
@app.errorhandler(KeyError)\ndef handle_key_error(error):\n return {'error': 'Missing key in request'}, 400 -> Option BQuick Check:
Use exception class in errorhandler for specific errors [OK]
- Using status code instead of exception class
- Defining error handler as a route
- Catching all exceptions instead of specific one
Ready to prove it?
Pass the test and this pattern moves unknown
