Nested error reporting helps show detailed problems inside complex data or requests. It makes it easier to find exactly where something went wrong.
0
0
Nested error reporting in Rest API
Introduction
When an API request has multiple parts and some parts fail while others succeed.
When validating a form with sections, and you want to tell the user which fields inside each section have errors.
When processing nested data like JSON objects or arrays and you want to report errors at different levels.
When you want to give clear feedback about errors inside related objects or sub-requests.
Syntax
Rest API
{
"error": {
"message": "Main error message",
"details": {
"field1": "Error message for field1",
"nestedField": {
"subField1": "Error message for subField1"
}
}
}
}The main error object contains a message and a details object.
Details can have nested objects to represent errors inside nested data.
Examples
This example shows an error for a missing username and a nested error inside the profile object for email format.
Rest API
{
"error": {
"message": "Validation failed",
"details": {
"username": "Username is required",
"profile": {
"email": "Invalid email format"
}
}
}
}This example reports errors inside an order object, including errors for specific items by index and a payment error.
Rest API
{
"error": {
"message": "Multiple errors",
"details": {
"order": {
"items": {
"0": "Item ID missing",
"2": "Quantity must be positive"
},
"payment": "Payment method not supported"
}
}
}
}Sample Program
This Flask API endpoint checks for a username and a valid email inside a profile object. It returns nested error messages if validation fails.
Rest API
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): data = request.json errors = {} if not data.get('username'): errors['username'] = 'Username is required' profile = data.get('profile', {}) profile_errors = {} email = profile.get('email', '') if '@' not in email and email != '': profile_errors['email'] = 'Invalid email format' if profile_errors: errors['profile'] = profile_errors if errors: return jsonify({ 'error': { 'message': 'Validation failed', 'details': errors } }), 400 return jsonify({'message': 'Success'}), 200 if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Use nested error reporting to help users fix specific parts of their input.
Keep error messages clear and related to the exact field or subfield.
APIs should return HTTP status codes like 400 for validation errors along with nested error details.
Summary
Nested error reporting shows errors inside complex or nested data clearly.
It helps users and developers find and fix problems faster.
Use structured JSON objects with nested details for best clarity.