Skip to main content
RESTful Principles
CHAPTER 18 Beginner

API Validation and Error Handling

Updated: May 13, 2026
5 min read

# CHAPTER 18

API Validation and Error Handling

1. Introduction

"Never trust user input." This is the golden rule of web development. Even if your API is perfectly secure and authorized, a client sending a POST request with missing fields, letters instead of numbers, or malicious SQL injection attempts can crash your server. In Chapter 18, we will explore how to rigorously validate incoming JSON payloads, sanitize data, and return standardized, helpful error messages when validation fails.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Validate incoming JSON data for required fields and data types.
  • Sanitize inputs to prevent Cross-Site Scripting (XSS).
  • Structure standardized JSON error responses.
  • Understand the 422 Unprocessable Entity status code.
  • Provide actionable error messages to frontend developers.

3. Beginner-Friendly Explanation

Imagine a strict bouncer at a club, but instead of checking IDs, they are checking dress codes. The API expects a POST request with an email and an age.
  • If you don't send an email, the bouncer rejects you: "Email is required."
  • If you send your age as "Banana", the bouncer rejects you: "Age must be a number."
  • If you try to sneak in a script tag to hack the site, the bouncer confiscates it.

Validation is the process of examining the data *before* it ever touches your database to ensure it perfectly matches the expected rules.

4. Real-World Examples

  • Sign-up Forms: When an API rejects a password because it is "too short" or "missing a special character," that is backend validation at work.
  • E-commerce: If you try to order -5 shirts, the API validates the quantity to ensure it is greater than 0.

5. Detailed Code Examples

Let's look at a raw PHP approach to validating a JSON payload for creating a user.
php
123456789101112131415161718192021222324252627282930313233
<?php
$data = json_decode(file_get_contents("php://input"), true);
$errors = [];

// 1. Required Field Validation
if (empty($data[&#039;email'])) {
    $errors[&#039;email'] = "Email field is required.";
} elseif (!filter_var($data[&#039;email'], FILTER_VALIDATE_EMAIL)) {
    // 2. Format Validation
    $errors[&#039;email'] = "Invalid email format.";
}

if (empty($data[&#039;age'])) {
    $errors[&#039;age'] = "Age field is required.";
} elseif (!is_numeric($data[&#039;age']) || $data['age'] < 18) {
    // 3. Type and Logic Validation
    $errors[&#039;age'] = "Age must be a number and 18 or older.";
}

// 4. Check if there are any errors
if (!empty($errors)) {
    // 422 Unprocessable Entity is the standard for validation failures
    http_response_code(422); 
    echo json_encode([
        "message" => "The given data was invalid.",
        "errors" => $errors
    ]);
    exit; // Stop execution! Do not touch the database!
}

// If we reach here, data is 100% valid. Safe to insert into DB.
echo json_encode(["message" => "User created safely."]);
?>

6. Request/Response Examples

When validation fails, a beautifully structured error response saves frontend developers hours of debugging.

Bad Request Payload:

json
1234
{
  "email": "not-an-email",
  "age": 12
}

Standardized Error Response (HTTP 422):

json
1234567891011
{
  "message": "Validation failed",
  "errors": {
    "email": [
      "The email address must be valid."
    ],
    "age": [
      "You must be at least 18 years old to register."
    ]
  }
}

7. HTTP Examples

While 400 Bad Request is often used for malformed JSON syntax, modern APIs use 422 Unprocessable Entity for semantic validation errors (the JSON syntax is correct, but the actual data values break the business rules).

8. JSON Examples

When designing your API, establish a consistent error format and never change it. A frontend app needs to know exactly how to parse errors so it can highlight the correct input boxes in red.
json
12345678
// Good Error Format
{
  "success": false,
  "error_code": "VALIDATION_FAILED",
  "details": {
    "password": "Password must contain a number."
  }
}

9. Best Practices

  • Validate Everything: Never assume data is safe. Validate lengths, types, formats, and ranges.
  • Fail Fast: The moment you find a validation error, stop processing the script and return the error. Do not attempt to run database queries.
  • Use Libraries: In real-world PHP, doing raw validation with if/else gets messy. Frameworks like Laravel use built-in validation classes. If writing core PHP, consider using a library like rakit/validation.

10. Common Mistakes

  • Returning HTML Errors: If your PHP script hits a fatal error, it might output raw HTML (like the orange Xdebug screens). This breaks API clients because they are expecting JSON. Always configure PHP to return errors as JSON in an API environment.
  • Vague Error Messages: Returning {"error": "Bad Data"} is useless to a developer trying to use your API. Tell them exactly *which* field was bad and *why*.

11. Mini Exercises

  1. 1. What PHP function is explicitly designed to validate whether a string is a properly formatted email address?
*(Answer: filtervar($email, FILTERVALIDATE_EMAIL))*

12. Coding Challenges

Challenge 1: Write a PHP validation block that checks if a JSON payload contains a username string. If the string is less than 5 characters or greater than 15 characters, add an error message to an $errors array.

13. MCQs with Answers

Question 1

What is the most appropriate HTTP status code to return when a client sends correctly formatted JSON, but the data violates validation rules (e.g., password too short)?

Question 2

Why is it important to structure error messages with the field name as the key?

Question 3

If a user inputs <script>alert('hack')</script> into a name field, what should the API do?

14. Interview Questions

  • Q: Explain the difference between returning a 400 Bad Request and a 422 Unprocessable Entity.
  • Q: Why must validation occur on the backend API even if the frontend form has strict HTML5 validation (like required type="email")?
  • Q: What is the structure of a good JSON validation error response?

15. FAQs

Q: Should I sanitize (modify) bad data, or just reject it? A: Usually, it's best to reject it and force the client to send the correct format. However, for minor things (like a user adding extra spaces around their name), using PHP's trim() to sanitize the input before saving is good practice.

16. Summary

In Chapter 18, we secured our API against bad data. We learned that every piece of incoming data must be validated for type, length, and format. When data fails these checks, we immediately halt the script and return a 422 Unprocessable Entity status code, complete with a structured JSON response detailing exactly which fields failed, making life easier for frontend developers.

17. Next Chapter Recommendation

With our knowledge of methods, endpoints, security, and validation complete, it is time to put the pieces together. Proceed to Chapter 19: CRUD Operations in REST APIs to see how all four core database operations map to our API architecture.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·