0
0
Rest APIprogramming~5 mins

Validation error details in Rest API

Choose your learning style9 modes available
Introduction

Validation error details help you understand why your data was not accepted by an API. They tell you exactly what went wrong so you can fix it.

When you send data to a web service and it rejects your input.
When you want to show users clear messages about what they need to correct in a form.
When debugging why your API request failed.
When building an API that needs to tell clients what errors happened.
When logging errors to improve your app's data quality.
Syntax
Rest API
HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "errors": [
    {
      "field": "username",
      "message": "Username is required",
      "code": "required"
    },
    {
      "field": "email",
      "message": "Email format is invalid",
      "code": "invalid_format"
    }
  ]
}

The response usually uses HTTP status 400 for validation errors.

The body is often JSON with an array of error objects describing each problem.

Examples
This example shows one error about a password being too short.
Rest API
{
  "errors": [
    {"field": "password", "message": "Password too short", "code": "min_length"}
  ]
}
This example shows two errors: one for age type and one for missing email.
Rest API
{
  "errors": [
    {"field": "age", "message": "Age must be a number", "code": "type_error"},
    {"field": "email", "message": "Email is missing", "code": "required"}
  ]
}
Sample Program

This simple Flask API checks if username and email are valid. If not, it returns validation error details in JSON with status 400.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    errors = []

    if not data.get('username'):
        errors.append({"field": "username", "message": "Username is required", "code": "required"})
    if not data.get('email') or '@' not in data.get('email', ''):
        errors.append({"field": "email", "message": "Email format is invalid", "code": "invalid_format"})

    if errors:
        return jsonify({"errors": errors}), 400

    return jsonify({"message": "User registered successfully"}), 200

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use clear and specific messages so users know how to fix errors.

Include the field name so clients can highlight the exact input with problems.

Use standard HTTP status codes like 400 for validation errors.

Summary

Validation error details explain what input is wrong and why.

They help users and developers fix data problems quickly.

Usually sent as JSON with error messages and field names.