API Error Handling
APIs must handle errors gracefully, returning meaningful HTTP status codes and error messages. Flask provides several ways to customise error responses.
Using `abort()`
from flask import abort
@app.route('/api/user/')
def get_user(user_id):
user = User.query.get(user_id)
if not user:
abort(404, description='User not found')
return jsonify({'id': user.id, 'name': user.name}) Custom Error Handlers
Override default error responses to return JSON.
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Resource not found'}), 404
@app.errorhandler(403)
def forbidden(error):
return jsonify({'error': 'Access forbidden'}), 403Validation Errors
Return 400 Bad Request with details.
if not data.get('title'):
return jsonify({'error': 'Title is required'}), 400Common HTTP Status Codes
- 200 OK – success.
- 201 Created – resource created.
- 400 Bad Request – invalid input.
- 401 Unauthorized – authentication required.
- 403 Forbidden – authenticated but not allowed.
- 404 Not Found – resource does not exist.
- 500 Internal Server Error – server error.
Two Minute Drill
- Use `abort(status_code, description)` to raise HTTP errors.
- Register custom error handlers with `@app.errorhandler`.
- Always return JSON for API errors.
- Use appropriate status codes for different error types.
Need more clarification?
Drop us an email at career@quipoinfotech.com
