Lesson 62 of 158 – PHP JSON Response
62%

PHP JSON Response

In the previous lessons, we created GET, POST, PUT, PATCH, and DELETE APIs. All of these APIs need to send clear responses back to the client. In this lesson, we will learn how to create professional JSON responses in PHP REST APIs.

Note: A consistent JSON response makes it easier for React Native and other clients to understand whether an API request was successful or failed.

1. What is a JSON Response?

A JSON response is data returned by the server in JSON format after an API request is processed.

{
    "success": true,
    "message": "Student created successfully"
}

The client can read this response and decide what to display to the user.

2. Why Use JSON Responses?

JSON is easy for mobile applications and web applications to process.

React Native
      ↓
HTTP Request
      ↓
PHP REST API
      ↓
JSON Response
      ↓
React Native

A consistent JSON structure makes API integration easier.

3. Set JSON Content Type

The API should tell the client that the response contains JSON.

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

This header should normally be sent before outputting the JSON response.

4. json_encode()

PHP arrays can be converted into JSON using json_encode().

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

echo json_encode($response);

5. Success Response

A successful operation can return a response such as:

{
    "success": true,
    "message": "Student created successfully"
}

The success property tells the client that the operation was successful.

6. Error Response

An API can return a JSON response when something goes wrong.

{
    "success": false,
    "message": "Student not found"
}

The client can display the message or perform another action.

7. HTTP Status Code

An API response contains both an HTTP status code and a response body.

HTTP Status
     +
JSON Body

The status code provides a standard indication of the result of the HTTP request.

8. Set HTTP Status Code in PHP

PHP provides http_response_code() to set the HTTP status code.

http_response_code(200);

This sets the response status to 200.

9. Common Success Codes

Status Meaning
200 OK
201 Created
204 No Content

10. HTTP 200 Response

HTTP 200 is commonly used when a request has been successfully processed.

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" => "Student fetched successfully"
]);

11. HTTP 201 Response

HTTP 201 is commonly used when a new resource has been created.

http_response_code(201);

echo json_encode([
    "success" => true,
    "message" => "Student created successfully"
]);

This is useful for a successful POST operation that creates a new student.

12. Common Client Error Codes

Status Meaning
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found

These status codes help the client understand why a request failed.

13. HTTP 400 Response

HTTP 400 can be used when the client sends invalid data.

http_response_code(400);

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

14. HTTP 404 Response

HTTP 404 can be used when the requested resource does not exist.

http_response_code(404);

echo json_encode([
    "success" => false,
    "message" => "Student not found"
]);

15. Server Error Codes

HTTP 500 is commonly used when the server encounters an unexpected error.

http_response_code(500);

echo json_encode([
    "success" => false,
    "message" => "Internal server error"
]);

16. Response with Data

A JSON response can contain actual API data.

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

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

17. Response with Multiple Records

A response can also contain multiple records.

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

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

18. Add Total Records

For a list response, the total number of records can also be returned.

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

This can be useful when displaying lists and pagination information.

19. Add Error Details

A useful error response can contain a clear message.

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

Avoid exposing sensitive server or database information in responses sent to clients.

20. Consistent Response Structure

Using a consistent response structure makes the API easier to consume.

Success:

{
    "success": true,
    "message": "...",
    "data": {}
}

Error:

{
    "success": false,
    "message": "..."
}

21. Create a Reusable Response Function

A reusable function can reduce repeated response code.

function sendResponse(
    int $status,
    array $data
) {

    http_response_code($status);

    echo json_encode($data);

    exit;
}

Now different API operations can use the same function.

22. Use the Response Function

sendResponse(200, [
    "success" => true,
    "message" => "Student fetched successfully",
    "data" => $student
]);

The function sets the status code, converts the array to JSON, outputs the response, and stops execution.

23. Error Response Function

sendResponse(404, [
    "success" => false,
    "message" => "Student not found"
]);

The same function can be used for both successful and error responses.

24. Complete Response Helper

<?php

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

function sendResponse(
    int $status,
    array $data
) {

    http_response_code($status);

    echo json_encode($data);

    exit;
}

sendResponse(200, [
    "success" => true,
    "message" => "API is working"
]);

?>

25. Response Helper with Student Data

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

sendResponse(200, [
    "success" => true,
    "message" => "Student fetched successfully",
    "data" => $student
]);

26. Response Helper for Validation Error

if ($name === '') {

    sendResponse(400, [
        "success" => false,
        "message" => "Name is required"
    ]);
}

This keeps validation response code short and consistent.

27. React Native Reads the Response

React Native can convert the API response into JavaScript data.

fetch(url)
    .then(response => response.json())
    .then(data => {

        console.log(data);

        if (data.success) {
            console.log(data.message);
        }

    });

The application can use the success property to decide what to do next.

28. API Response Flow

PHP Operation
      ↓
Determine Result
      ↓
HTTP Status Code
      ↓
PHP Array
      ↓
json_encode()
      ↓
JSON Response
      ↓
React Native

29. JSON Response Best Practices

  • Always return JSON from JSON API endpoints.
  • Set the Content-Type correctly.
  • Use meaningful HTTP status codes.
  • Keep response structures consistent.
  • Return clear success and error messages.
  • Include data only when appropriate.
  • Do not expose passwords or sensitive information.
  • Do not expose internal database errors to clients.

30. PHP JSON Response Summary

A professional REST API should return a clear JSON response together with an appropriate HTTP status code. PHP can use http_response_code() to set the status and json_encode() to create the JSON response.

API Operation
     ↓
HTTP Status
     ↓
PHP Array
     ↓
json_encode()
     ↓
JSON Response
     ↓
React Native

📌 Key Points

  • REST APIs commonly return data in JSON format.
  • Content-Type: application/json identifies a JSON response.
  • json_encode() converts PHP data into JSON.
  • http_response_code() sets the HTTP response status.
  • HTTP 200 can indicate a successful request.
  • HTTP 201 can indicate that a resource was created.
  • HTTP 400 can indicate invalid client input.
  • HTTP 404 can indicate that a resource was not found.
  • HTTP 500 can indicate a server-side error.
  • JSON responses can contain messages and data.
  • Consistent response structures make APIs easier to use.
  • A reusable response function can reduce repeated code.
  • React Native can read JSON responses using response.json().

🧠 Quick Quiz

Question: Which PHP function is used to convert a PHP array into a JSON string?