Lesson 57 of 158 – JSON Data in PHP REST API
57%

JSON Data in PHP REST API

JSON is one of the most important data formats used in REST APIs. In the previous lesson, we sent student data using a POST request. Now we will learn how PHP receives JSON data, converts JSON into PHP data, works with the values, and sends JSON back to the client.

Note: React Native and PHP REST APIs commonly exchange data using JSON. Understanding json_encode() and json_decode() is essential for API development.

1. What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight text-based format used to exchange data between applications.

{
    "name": "Rahul",
    "course": "PHP"
}

JSON is easy for both humans and programming languages to read.

2. Why REST APIs Use JSON

REST APIs need a common format for sending data between clients and servers. JSON is widely used for this purpose.

React Native
      ↕
     JSON
      ↕
PHP REST API

The mobile application can send JSON to PHP and PHP can return JSON to the mobile application.

3. JSON Object

A JSON object contains data in key-value pairs.

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

The keys are written inside double quotes.

4. JSON Array

A JSON array can contain multiple values or objects.

[
    {
        "id": 1,
        "name": "Rahul"
    },
    {
        "id": 2,
        "name": "Amit"
    }
]

Arrays are useful when an API returns multiple records.

5. PHP and JSON

PHP provides built-in functions for working with JSON.

  • json_encode() converts PHP data to JSON.
  • json_decode() converts JSON to PHP data.
PHP Array
   ↓
json_encode()
   ↓
JSON

JSON
   ↓
json_decode()
   ↓
PHP Array

6. json_encode()

The json_encode() function converts PHP data into a JSON string.

$student = [
    "name" => "Rahul",
    "course" => "PHP"
];

echo json_encode($student);

The output is:

{"name":"Rahul","course":"PHP"}

7. JSON Response Header

When a PHP API returns JSON, set the response content type.

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

This tells the client that the response contains JSON data.

8. Simple JSON Response

<?php

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

$response = [
    "success" => true,
    "message" => "API is working"
];

echo json_encode($response);

?>

The API returns a JSON object containing a success value and message.

9. json_decode()

The json_decode() function converts JSON into PHP data.

$json = '{
    "name": "Rahul",
    "course": "PHP"
}';

$data = json_decode($json, true);

The second parameter true makes the result an associative array.

10. Access Decoded JSON

After decoding JSON into an associative array, values can be accessed using their keys.

echo $data['name'];

echo $data['course'];

The output will be:

Rahul
PHP

11. Read JSON Request Body

A REST API can receive JSON through the HTTP request body.

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

This reads the raw body sent by the client.

12. Decode Request JSON

The raw JSON body can be converted into a PHP associative array.

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

Now the PHP code can work with the received values.

13. Example POST JSON

A React Native application or Postman can send:

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

PHP receives this JSON through the request body.

14. Convert JSON to PHP Array

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

$name = $data['name'];
$email = $data['email'];
$mobile = $data['mobile'];
$course = $data['course'];

Each JSON property can now be accessed using PHP array syntax.

15. Null Coalescing Operator

The null coalescing operator can be used when a JSON key may not exist.

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

If a key does not exist, an empty string is used.

16. Validate JSON Data

The API should validate the received data before processing it.

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

    http_response_code(400);

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

    exit;
}

17. JSON Request Content-Type

When sending JSON to an API, the client should identify the content type.

Content-Type: application/json

This tells the server that the request body contains JSON data.

18. JSON Response with Student Data

PHP can return a student array as JSON.

$student = [
    "id" => 1,
    "name" => "Rahul",
    "email" => "rahul@example.com",
    "course" => "PHP"
];

echo json_encode($student);

19. JSON Array Response

Multiple PHP records can be converted into a JSON array.

$students = [
    [
        "id" => 1,
        "name" => "Rahul"
    ],
    [
        "id" => 2,
        "name" => "Amit"
    ]
];

echo json_encode($students);

20. Structured JSON Response

A REST API can wrap the data inside a response object.

$response = [
    "success" => true,
    "message" => "Students fetched successfully",
    "data" => $students
];

echo json_encode($response);

This makes the response easier for clients to understand.

21. JSON Error Response

Errors can also be returned as JSON.

http_response_code(400);

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

The client can check the HTTP status and JSON message.

22. JSON with Database Data

Database records can be fetched using PDO and then converted to JSON.

$stmt = $pdo->query(
    "SELECT id, name, email, mobile, course
     FROM students"
);

$students = $stmt->fetchAll(
    PDO::FETCH_ASSOC
);

echo json_encode([
    "success" => true,
    "data" => $students
]);

23. JSON Data Flow

React Native
      ↓
JSON Request
      ↓
php://input
      ↓
json_decode()
      ↓
PHP Array
      ↓
MySQL
      ↓
PHP Array
      ↓
json_encode()
      ↓
JSON Response
      ↓
React Native

24. Test JSON in Postman

Postman can be used to test JSON requests.

Choose:

Method: POST

Body:
raw
JSON

Then enter:

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

25. JSON Invalid Data

If the client sends invalid JSON, json_decode() may not produce the expected PHP data.

For example, this is invalid JSON:

{
    "name": "Rahul",
    "email": "rahul@example.com",
}

There is an extra comma after the email value.

26. Check JSON Errors

PHP provides json_last_error() to check the last JSON decoding or encoding error.

$data = json_decode(
    $input,
    true
);

if (json_last_error() !== JSON_ERROR_NONE) {

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

    exit;
}

27. JSON and React Native

React Native can send JSON using JSON.stringify().

fetch("http://localhost/rest_api/api/students.php", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Rahul",
        email: "rahul@example.com",
        mobile: "9876543210",
        course: "PHP"
    })
});

The PHP API can receive this data using php://input.

28. Parse JSON Response in React Native

React Native can convert a JSON HTTP response into JavaScript data using response.json().

fetch("http://localhost/rest_api/api/students.php")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

This allows the application to work with the API response.

29. JSON Best Practices

  • Use valid JSON syntax.
  • Use double quotes around JSON keys and string values.
  • Set the correct Content-Type.
  • Validate incoming JSON data.
  • Use json_decode() for incoming JSON.
  • Use json_encode() for outgoing JSON.
  • Return consistent response structures.
  • Do not expose sensitive information.

30. JSON Data in PHP Summary

JSON is the main data exchange format we are using between our PHP REST API and React Native application. PHP uses json_decode() to read JSON received from the client and json_encode() to send PHP data back as JSON.

Client
  ↓
JSON
  ↓
json_decode()
  ↓
PHP
  ↓
MySQL
  ↓
PHP
  ↓
json_encode()
  ↓
JSON
  ↓
Client

📌 Key Points

  • JSON stands for JavaScript Object Notation.
  • REST APIs commonly use JSON for data exchange.
  • json_encode() converts PHP data to JSON.
  • json_decode() converts JSON to PHP data.
  • php://input reads the raw HTTP request body.
  • The second parameter of json_decode() can create an associative array.
  • JSON requests should use Content-Type: application/json.
  • Incoming JSON should be validated before processing.
  • json_last_error() can be used to check JSON errors.
  • PHP database records can be converted into JSON responses.
  • React Native can send JSON using JSON.stringify().
  • React Native can read JSON responses using response.json().

🧠 Quick Quiz

Question: Which PHP function converts JSON data into PHP data?