SyntaxStudy
Sign Up
REST API Request Validation and Error Responses
REST API Beginner 1 min read

Request Validation and Error Responses

Robust APIs validate all input before processing it and return structured, actionable error responses. A useful error response includes an HTTP status code, a machine-readable error code, a human-readable message, and field-level validation details so clients can surface precise error messages in their UI without string-parsing. The RFC 7807 Problem Details format (application/problem+json) is a standard structure for HTTP error responses. It defines type (a URI identifying the error category), title, status, detail, and instance (a URI for this specific occurrence), providing a common vocabulary for errors across APIs.
Example
# RFC 7807 Problem Details response
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{
  "type":     "https://api.example.com/errors/validation-error",
  "title":    "Validation Error",
  "status":   422,
  "detail":   "The request body contains invalid data.",
  "instance": "/requests/7c4e2b1a",
  "errors": [
    { "field": "email",    "code": "INVALID_FORMAT",  "message": "Must be a valid email address." },
    { "field": "password", "code": "TOO_SHORT",        "message": "Must be at least 8 characters." },
    { "field": "age",      "code": "BELOW_MINIMUM",    "message": "Must be 18 or older." }
  ]
}

// Laravel Form Request validation auto-generates 422 responses:
class CreateUserRequest extends FormRequest {
  public function rules(): array {
    return [
      'name'     => ['required', 'string', 'max:100'],
      'email'    => ['required', 'email', 'unique:users'],
      'password' => ['required', 'min:8', 'confirmed'],
      'age'      => ['required', 'integer', 'min:18'],
    ];
  }
  public function messages(): array {
    return [
      'age.min' => 'Must be 18 or older.',
    ];
  }
}
// Laravel returns 422 with validation errors automatically.