Skip to content

Validation Errors

DodaTech 2 min read

title: "Validation Errors — Structured Input Error Responses" description: "API validation errors tell clients exactly which input fields failed validation, why they failed, and what format is expected for each field." date: 2026-06-28 lastmod: 2026-06-28 weight: 14 tags: [apis, error-handling] }

Validation errors occur when client input doesn't meet API requirements, and structured responses identify each invalid field with the specific validation rule that failed.

What You'll Learn

  • Structuring validation error responses
  • Reporting multiple field errors at once
  • Validation strategies for complex inputs

Why It Matters

Form validation is where most API errors happen. Clear validation errors reduce the number of failed requests and improve client-side error handling.

Code Examples

// Multiple field validation errors
{
  "error": "VALIDATION_ERROR",
  "message": "The request contains invalid fields",
  "status": 400,
  "fields": [
    {
      "name": "email",
      "value": "not-an-email",
      "reason": "Must be a valid email address",
      "code": "INVALID_FORMAT"
    },
    {
      "name": "age",
      "value": -5,
      "reason": "Must be a positive integer",
      "code": "MINIMUM_VALUE"
    },
    {
      "name": "name",
      "reason": "This field is required",
      "code": "REQUIRED"
    }
  ]
}
# Server-side validation with structured errors
from marshmallow import Schema, fields, ValidationError

class UserSchema(Schema):
    name = fields.String(required=True)
    email = fields.Email(required=True)
    age = fields.Integer(required=True, validate=lambda n: n > 0)

@app.route('/users', methods=['POST'])
def create_user():
    schema = UserSchema()
    try:
        data = schema.load(request.json)
        return jsonify({"id": create_user(data)}), 201
    except ValidationError as err:
        field_errors = [
            {
                "name": field,
                "reason": " ".join(messages),
                "code": "VALIDATION_ERROR"
            }
            for field, messages in err.messages.items()
        ]
        return jsonify({
            "error": "VALIDATION_ERROR",
            "message": "Invalid request data",
            "fields": field_errors
        }), 400

Common Mistakes

1. Returning Only the First Error

Report all validation errors in one response so clients fix them all at once.

2. Not Including the Invalid Value

Include the rejected value so clients can show it in the form field.

3. No Error Codes

Human-readable messages are good. Machine-readable codes are better.

4. Inconsistent Field Names

Use the same field names in errors as in the request body.

5. Not Validating at the Schema Level

Validate at API entry, not deep in business logic.

Practice Questions

  1. Why should validation errors report all failed fields at once?
  2. What information should each field error include?
  3. How do validation errors differ from authentication errors?
  4. What HTTP status code is appropriate for validation errors?
  5. Why include the invalid value in the error response?

Answers:

  1. So clients fix all issues in one round-trip instead of iterative debugging.
  2. Field name, reason, error code, and the invalid value.
  3. Validation errors mean bad input (400); auth errors mean bad credentials (401).
  4. 400 Bad Request or 422 Unprocessable Entity.
  5. So the client can show the exact rejected value to the user.

Challenge: Create a validation middleware that catches any validation error and returns a structured response with all field errors. Test it with missing fields, wrong types, and constraint violations.

FAQ

Should I return 400 or 422 for validation?

: 422 is more semantically correct for schema validation, but 400 is more common.

How do I validate nested objects?

: Recursively report errors with dot-notation paths like address.zip_code.

What if a field has multiple validation rules?

: Report all violations for that field, not just the first one.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro