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 aPOST 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 aPOST 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
-5shirts, the API validates the quantity to ensure it is greater than0.
5. Detailed Code Examples
Let's look at a raw PHP approach to validating a JSON payload for creating a user.
php
6. Request/Response Examples
When validation fails, a beautifully structured error response saves frontend developers hours of debugging.Bad Request Payload:
json
Standardized Error Response (HTTP 422):
json
7. HTTP Examples
While400 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
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/elsegets messy. Frameworks like Laravel use built-in validation classes. If writing core PHP, consider using a library likerakit/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. What PHP function is explicitly designed to validate whether a string is a properly formatted email address?
filtervar($email, FILTERVALIDATE_EMAIL))*
12. Coding Challenges
Challenge 1: Write a PHP validation block that checks if a JSON payload contains ausername 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 Requestand a422 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'strim() 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 a422 Unprocessable Entity status code, complete with a structured JSON response detailing exactly which fields failed, making life easier for frontend developers.