Lesson 58 of 158 – Validate API Data
58%

Validate API Data

When a client sends data to a REST API, the server should not directly trust that data. Before storing or processing it, the API should validate the received values. In this lesson, we will learn how to validate student data before inserting it into MySQL.

Note: Validation checks whether the data received from the client is present, correctly formatted, and suitable for the operation.

1. What is Data Validation?

Data validation means checking whether the data received by the API meets the required rules.

For example:

  • Name should not be empty.
  • Email should have a valid format.
  • Mobile should contain an acceptable value.
  • Course should be provided when required.

2. Why Validate API Data?

An API receives data from external clients such as React Native applications, web applications, and Postman. The server must verify this data before using it.

Client
   ↓
API
   ↓
Validate Data
   ↓
Database

Validation helps prevent invalid data from entering the database.

3. Client-Side vs Server-Side Validation

Validation Location
Client-side React Native / Browser
Server-side PHP REST API

Client-side validation improves user experience, but server-side validation is essential because the server cannot assume that the client performed correct validation.

4. Validate Before Database Insert

The API should validate data before executing an INSERT query.

JSON Request
     ↓
Decode JSON
     ↓
Validate Data
     ↓
INSERT INTO
     ↓
MySQL

This keeps invalid data away from the database.

5. Read JSON Data

First, read the JSON request body.

$data = json_decode(
    file_get_contents("php://input"),
    true
);

The JSON data is converted into a PHP associative array.

6. Check Whether JSON Was Received

The API should make sure that decoded data is available before accessing its fields.

if (!is_array($data)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid JSON data"
    ]);

    exit;
}

7. Required Fields

Some fields may be required to create a student.

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');

The values can now be checked individually.

8. Validate Empty Name

A student's name should not be empty.

if ($name === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Name is required"
    ]);

    exit;
}

9. Validate Email

PHP provides filter_var() for validating email addresses.

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid email address"
    ]);

    exit;
}

10. Why Validate Email?

An email field may contain an incorrectly formatted value.

For example:

Invalid:
rahul@

Valid:
rahul@example.com

The API should validate the format before accepting the value.

11. Validate Mobile Number

The mobile number can be checked according to the requirements of the application.

For example, a simple length check can be performed:

if ($mobile !== '' &&
    strlen($mobile) < 10) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid mobile number"
    ]);

    exit;
}

12. Validate Course

If the course is required, check that it is not empty.

if ($course === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Course is required"
    ]);

    exit;
}

13. Trim User Input

The trim() function removes unnecessary whitespace from the beginning and end of a string.

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');

This helps prevent values containing only spaces from being treated as valid input.

14. Validate String Length

You can validate the length of text values using strlen().

if (strlen($name) > 100) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Name is too long"
    ]);

    exit;
}

The maximum length should match the database column and application requirements.

15. Validate Numeric ID

When an API receives an ID, it should validate that the ID is an integer.

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

This is useful for Get Single APIs.

16. Validate Positive ID

An ID should normally be greater than zero.

if ($id === false || $id <= 0) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid ID"
    ]);

    exit;
}

17. Check JSON Syntax

The API can check whether the received JSON is valid.

$data = json_decode(
    $input,
    true
);

if (json_last_error() !== JSON_ERROR_NONE) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid JSON"
    ]);

    exit;
}

18. Validate Multiple Fields

Multiple required fields can be validated together.

if (
    $name === '' ||
    $email === '' ||
    $course === ''
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Required fields are missing"
    ]);

    exit;
}

19. Return Validation Errors

A REST API should return a clear JSON response when validation fails.

{
    "success": false,
    "message": "Email is required"
}

The client can use this message to show an appropriate error.

20. HTTP 400 for Invalid Data

HTTP status code 400 Bad Request can be used when the client sends invalid input.

http_response_code(400);

echo json_encode([
    "success" => false,
    "message" => "Invalid input"
]);

21. Complete Validation Example

<?php

header("Content-Type: application/json");

$input = file_get_contents("php://input");

$data = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid JSON"
    ]);

    exit;
}

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');

if ($name === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Name is required"
    ]);

    exit;
}

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid email"
    ]);

    exit;
}

if ($course === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Course is required"
    ]);

    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Validation successful"
]);

?>

22. Validation Before INSERT

Validation should happen before executing the INSERT query.

Receive JSON
     ↓
Decode JSON
     ↓
Validate
     ↓
Prepare SQL
     ↓
Execute INSERT
     ↓
Return Response

Never skip validation simply because the application already validates the data on the client side.

23. Validation with Prepared Statements

Validation and prepared statements solve different problems. Validation checks whether data is acceptable, while prepared statements safely pass values to SQL queries.

Validate Data
      ↓
Prepare SQL
      ↓
Execute Values
      ↓
Database

24. Validate Data in Postman

You can test validation by sending incomplete JSON from Postman.

{
    "name": "Rahul"
}

If email and course are required, the API should reject this request and return a validation error.

25. Test Invalid Email

Send an invalid email:

{
    "name": "Rahul",
    "email": "rahul@",
    "course": "PHP"
}

The API should return a 400 response with an appropriate validation message.

26. Test Valid Data

Send valid data:

{
    "name": "Rahul",
    "email": "rahul@example.com",
    "mobile": "9876543210",
    "course": "PHP"
}

The validation should pass and the API can continue to the database operation.

27. React Native Validation

React Native can also validate form data before sending it to the API.

if (!name || !email) {
    console.log("Required fields missing");
}

However, server-side validation should still be performed by PHP.

28. Common Validation Rules

  • Required field validation
  • Email validation
  • Numeric validation
  • Integer validation
  • String length validation
  • JSON validation
  • Allowed value validation
  • Range validation

The rules should match the requirements of the API.

29. Complete API Validation Flow

React Native
     ↓
JSON Request
     ↓
PHP API
     ↓
json_decode()
     ↓
Check JSON
     ↓
Validate Fields
     ↓
Prepared Statement
     ↓
MySQL
     ↓
JSON Response

This validation flow should be used whenever the API accepts user-provided data.

30. Validate API Data Summary

API validation protects the application from invalid input. PHP can check JSON syntax, required fields, email format, numeric values, string lengths, and other application rules before the data reaches MySQL.

Receive
  ↓
Decode
  ↓
Validate
  ↓
Process
  ↓
Database
  ↓
Response

📌 Key Points

  • API data should always be validated on the server.
  • Client-side validation does not replace server-side validation.
  • json_decode() converts JSON into PHP data.
  • json_last_error() can check JSON parsing errors.
  • trim() removes unnecessary surrounding whitespace.
  • filter_var() can validate email addresses.
  • FILTER_VALIDATE_INT can validate integer input.
  • strlen() can be used for string length checks.
  • HTTP 400 can be used for invalid client input.
  • Validation should happen before database operations.
  • Prepared statements should still be used after validation.
  • Clear JSON error responses help React Native handle API errors.

🧠 Quick Quiz

Question: Which PHP function can be used to validate an email address?