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.
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.
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.
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.
PHP arrays can be converted into JSON using json_encode().
$response = [
"success" => true,
"message" => "API is working"
];
echo json_encode($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.
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.
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.
PHP provides http_response_code() to set the HTTP status code.
http_response_code(200);
This sets the response status to 200.
| Status | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
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"
]);
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.
| Status | Meaning |
|---|---|
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
These status codes help the client understand why a request failed.
HTTP 400 can be used when the client sends invalid data.
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid student data"
]);
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"
]);
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"
]);
A JSON response can contain actual API data.
$student = [
"id" => 1,
"name" => "Rahul",
"email" => "rahul@example.com"
];
echo json_encode([
"success" => true,
"data" => $student
]);
A response can also contain multiple records.
$students = [
[
"id" => 1,
"name" => "Rahul"
],
[
"id" => 2,
"name" => "Amit"
]
];
echo json_encode([
"success" => true,
"data" => $students
]);
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.
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.
Using a consistent response structure makes the API easier to consume.
Success:
{
"success": true,
"message": "...",
"data": {}
}
Error:
{
"success": false,
"message": "..."
}
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.
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.
sendResponse(404, [
"success" => false,
"message" => "Student not found"
]);
The same function can be used for both successful and error responses.
<?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"
]);
?>
$student = [
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
];
sendResponse(200, [
"success" => true,
"message" => "Student fetched successfully",
"data" => $student
]);
if ($name === '') {
sendResponse(400, [
"success" => false,
"message" => "Name is required"
]);
}
This keeps validation response code short and consistent.
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.
PHP Operation
↓
Determine Result
↓
HTTP Status Code
↓
PHP Array
↓
json_encode()
↓
JSON Response
↓
React Native
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
Question: Which PHP function is used to convert a PHP array into a JSON string?