Lesson 63 of 158 – PHP API Status Codes
63%

PHP API Status Codes

HTTP status codes tell the client what happened after an API request. In a PHP REST API, choosing the correct status code helps React Native and other clients understand whether a request was successful, invalid, unauthorized, or failed because of a server problem.

Note: HTTP status codes are returned by the server along with the API response. PHP provides http_response_code() to set the response status.

1. What is an HTTP Status Code?

An HTTP status code is a three-digit number returned by a server after processing an HTTP request.

Client Request
      ↓
PHP REST API
      ↓
HTTP Status Code
      +
JSON Response

For example, 200 usually means the request was successful.

2. Why Status Codes Are Important

Status codes allow the client application to understand the result of an API request without depending only on a text message.

200 → Success
400 → Bad Request
401 → Unauthorized
404 → Not Found
500 → Server Error

React Native can use these codes to decide what action to perform.

3. Status Code Categories

HTTP status codes are divided into five major categories.

Range Category
100–199 Informational
200–299 Success
300–399 Redirection
400–499 Client Error
500–599 Server Error

4. PHP http_response_code()

PHP provides the http_response_code() function for setting the HTTP response status code.

http_response_code(200);

This sends HTTP status code 200 to the client.

5. HTTP 200 – OK

HTTP 200 indicates that the request was successfully processed. It is commonly used for successful GET requests and successful updates.

http_response_code(200);

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

6. HTTP 201 – Created

HTTP 201 is used when a new resource has been successfully created. It is commonly used after a successful POST request.

http_response_code(201);

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

7. HTTP 204 – No Content

HTTP 204 means the request was successfully processed but the server does not need to return a response body.

http_response_code(204);

A 204 response normally does not contain a JSON response body.

8. HTTP 400 – Bad Request

HTTP 400 indicates that the request contains invalid or missing data.

http_response_code(400);

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

9. HTTP 401 – Unauthorized

HTTP 401 is commonly used when authentication is required or the supplied authentication credentials are not valid.

http_response_code(401);

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

10. HTTP 403 – Forbidden

HTTP 403 means the server understood the request but refuses to allow the requested operation.

http_response_code(403);

echo json_encode([
    "success" => false,
    "message" => "Access denied"
]);

This can be useful when a logged-in user does not have permission to perform an operation.

11. HTTP 404 – Not Found

HTTP 404 is used when the requested resource cannot be found.

http_response_code(404);

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

12. HTTP 405 – Method Not Allowed

HTTP 405 can be used when the requested HTTP method is not supported by an API endpoint.

http_response_code(405);

echo json_encode([
    "success" => false,
    "message" => "Method not allowed"
]);

13. HTTP 409 – Conflict

HTTP 409 can be used when a request conflicts with the current state of a resource.

http_response_code(409);

echo json_encode([
    "success" => false,
    "message" => "Email already exists"
]);

This can be useful when registering a user with an already registered email.

14. HTTP 422 – Validation Error

HTTP 422 is commonly used when the request format is understood but the submitted data fails validation.

http_response_code(422);

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

15. HTTP 500 – Internal Server Error

HTTP 500 indicates an unexpected problem on the server.

http_response_code(500);

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

Do not expose sensitive database or server details to the mobile client.

16. HTTP 503 – Service Unavailable

HTTP 503 can indicate that the server or service is temporarily unable to handle the request.

http_response_code(503);

echo json_encode([
    "success" => false,
    "message" => "Service temporarily unavailable"
]);

17. Status Code with JSON

A REST API normally sends a status code together with a JSON response.

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

http_response_code(200);

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

18. GET Request Status

A successful GET request that retrieves existing data commonly uses HTTP 200.

GET /students

200 OK
{
    "success": true,
    "data": []
}

19. POST Request Status

When a POST request successfully creates a new record, HTTP 201 is commonly used.

POST /students

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

20. PUT Request Status

A successful PUT request that updates an existing resource commonly returns HTTP 200.

PUT /students/10

200 OK
{
    "success": true,
    "message": "Student updated successfully"
}

21. DELETE Request Status

A successful DELETE request can return HTTP 200 with a JSON message, or HTTP 204 when no response body is needed.

DELETE /students/10

200 OK
{
    "success": true,
    "message": "Student deleted successfully"
}

22. Check Method in PHP

PHP can read the HTTP method using $_SERVER['REQUEST_METHOD'].

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {

    echo "GET request";

}

This allows one endpoint to handle different HTTP methods when designed that way.

23. Handle Unsupported Methods

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'GET') {

    http_response_code(405);

    echo json_encode([
        "success" => false,
        "message" => "Method not allowed"
    ]);

    exit;
}

The API stops processing after returning the error.

24. Status Code with Validation

$name = trim($_POST['name'] ?? '');

if ($name === '') {

    http_response_code(400);

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

    exit;
}

Validation errors should be detected before performing database operations.

25. Status Code with Database Error

try {

    $stmt = $pdo->prepare(
        "SELECT * FROM students"
    );

    $stmt->execute();

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" => "Database operation failed"
    ]);

    exit;
}

The actual database error should not normally be exposed to the client.

26. React Native Checks Status

React Native can check the HTTP status using the response object's status property.

fetch(url)
    .then(response => {

        console.log(response.status);

        return response.json();
    })
    .then(data => {

        console.log(data);

    });

27. React Native Success Check

fetch(url)
    .then(response => {

        if (response.ok) {
            console.log("Request successful");
        }

        return response.json();
    })
    .then(data => {

        console.log(data);

    });

The ok property indicates whether the response status represents a successful HTTP response.

28. Status Code Decision Flow

API Request
     ↓
Validate Request
     ↓
Valid?
 ┌───┴────┐
No       Yes
↓          ↓
400      Database
           ↓
        Found?
       ┌──┴──┐
      No    Yes
      ↓       ↓
    404      Success
              ↓
             200

The exact status code depends on what happened during API processing.

29. Best Practices for Status Codes

  • Use standard HTTP status codes.
  • Use 200 for successful operations that return a response.
  • Use 201 when a resource is created.
  • Use 400 for invalid requests.
  • Use 401 for authentication problems.
  • Use 403 when access is forbidden.
  • Use 404 when a resource cannot be found.
  • Use 405 for unsupported HTTP methods.
  • Use 422 for validation failures when appropriate.
  • Use 500 for unexpected server errors.
  • Return a clear JSON message with the status.
  • Never expose sensitive server information.

30. Complete PHP Status Code Example

<?php

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

$id = $_GET['id'] ?? '';

if ($id === '') {

    http_response_code(400);

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

    exit;
}

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

http_response_code(200);

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

?>

This example validates the request, sets the appropriate status code, and returns a JSON response.

📌 Key Points

  • HTTP status codes tell the client what happened to an API request.
  • Status codes are divided into informational, success, redirection, client error, and server error categories.
  • http_response_code() is used in PHP to set the response status.
  • HTTP 200 commonly represents a successful request.
  • HTTP 201 commonly represents a newly created resource.
  • HTTP 204 means the request succeeded without a response body.
  • HTTP 400 represents a bad request.
  • HTTP 401 represents an authentication problem.
  • HTTP 403 represents forbidden access.
  • HTTP 404 means the requested resource was not found.
  • HTTP 405 means the HTTP method is not allowed.
  • HTTP 409 can represent a resource conflict.
  • HTTP 422 can represent validation failure.
  • HTTP 500 represents an internal server error.
  • HTTP 503 can represent temporary service unavailability.
  • React Native can check response.status and response.ok.
  • Always return clear and consistent JSON responses.

🧠 Quick Quiz

Question: Which PHP function is used to set an HTTP response status code?