Lesson 48 of 158 – PHP API Entry Point
48%

PHP API Entry Point

An API entry point is the PHP file through which a client starts communicating with the REST API. It receives the HTTP request, processes the required information, and sends a response back to the client.

Note: In our Student Management API project, the entry point will connect the client request with the PHP backend logic. Later, React Native will send requests to these API endpoints.

1. What is an API Entry Point?

An API entry point is a URL or PHP endpoint where an API request begins.

For example:

http://localhost/student_api/api/students.php

The client sends an HTTP request to this endpoint.

2. Why Do We Need an Entry Point?

The client needs a specific endpoint to communicate with the backend.

React Native
      ↓
API Entry Point
      ↓
PHP
      ↓
MySQL

The entry point receives the request and starts the API processing.

3. API Entry Point Example

Suppose our student endpoint is:

api/students.php

The complete local URL may be:

http://localhost/student_api/api/students.php

This file can process student-related API requests.

4. Creating students.php

Create a file named students.php inside the API folder.

student_api/
│
└── api/
    └── students.php

This file will become our main student API endpoint.

5. Basic PHP Entry Point

A very simple PHP API entry point can start like this:

<?php

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

echo json_encode([
    "success" => true,
    "message" => "Student API is working"
]);

The endpoint sends a JSON response to the client.

6. Content-Type Header

REST APIs commonly return JSON data. PHP can tell the client that the response is JSON using the Content-Type header.

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

This should be sent before outputting the JSON response.

7. Returning JSON

PHP can convert an array into JSON using json_encode().

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

echo json_encode($response);

8. Test the Entry Point in a Browser

For a simple GET endpoint, you can open the API URL in a browser.

http://localhost/student_api/api/students.php

If the PHP file is working, it should display a JSON response.

9. Test the Entry Point with Postman

Postman is a better tool for testing different HTTP methods and request bodies.

GET
http://localhost/student_api/api/students.php

Click Send and check the response.

10. Get the HTTP Method

PHP provides the $_SERVER['REQUEST_METHOD'] value to identify the HTTP method used by the request.

$method = $_SERVER['REQUEST_METHOD'];

echo $method;

For a GET request, the value will be GET.

11. Check for GET Request

We can check whether the client sent a GET request.

if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    echo json_encode([
        "message" => "GET request received"
    ]);

}

12. Check for POST Request

The same entry point can also check for POST requests.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    echo json_encode([
        "message" => "POST request received"
    ]);

}

This allows one endpoint to handle different operations.

13. Handling Multiple Methods

An endpoint can use conditional statements to handle multiple HTTP methods.

$method = $_SERVER['REQUEST_METHOD'];

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

    // Get students

} elseif ($method === 'POST') {

    // Add student

}

14. PUT and DELETE Methods

The same approach can be used for PUT, PATCH, and DELETE requests.

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {

    case 'GET':
        // Read
        break;

    case 'POST':
        // Create
        break;

    case 'PUT':
        // Update
        break;

    case 'DELETE':
        // Delete
        break;
}

15. Using switch for API Methods

A switch statement can make the API entry point easier to organize when multiple HTTP methods are supported.

switch ($_SERVER['REQUEST_METHOD']) {

    case 'GET':
        break;

    case 'POST':
        break;

    case 'PUT':
        break;

    case 'DELETE':
        break;

    default:
        break;
}

16. Set the Response Status Code

PHP can set an HTTP response status code using http_response_code().

http_response_code(200);

For example, 200 can indicate that a request was successfully processed.

17. JSON Response with Status Code

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" => "API is working"
]);

The client receives both the HTTP status and the JSON response body.

18. Method Not Allowed

If the API does not support the requested HTTP method, it can return 405 Method Not Allowed.

http_response_code(405);

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

19. Basic Entry Point Example

<?php

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

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {

    case 'GET':

        echo json_encode([
            "success" => true,
            "message" => "GET request"
        ]);

        break;

    case 'POST':

        echo json_encode([
            "success" => true,
            "message" => "POST request"
        ]);

        break;

    default:

        http_response_code(405);

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

20. Connect the Entry Point to Database

Once the entry point is working, we can include our database connection.

require_once '../config/database.php';

The API can then use the PDO connection to communicate with MySQL.

21. Entry Point with PDO

A basic API endpoint can load the database connection and then process the request.

<?php

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

require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];

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

    // Database operation

}

22. GET Request Flow

GET Request
     ↓
students.php
     ↓
Check HTTP Method
     ↓
Connect to MySQL
     ↓
Execute SELECT Query
     ↓
Create JSON
     ↓
Return Response

23. POST Request Flow

POST Request
     ↓
students.php
     ↓
Read JSON Body
     ↓
Validate Data
     ↓
Insert into MySQL
     ↓
Create JSON Response
     ↓
Return Response

24. Entry Point and React Native

React Native will send HTTP requests to the PHP entry point.

React Native
      ↓
fetch() / Axios
      ↓
students.php
      ↓
PHP
      ↓
MySQL
      ↓
JSON
      ↓
React Native

The mobile application communicates with the API rather than directly with the database.

25. Common Entry Point Mistakes

  • Incorrect API URL
  • Incorrect relative path
  • Missing Content-Type header
  • Not checking the HTTP method
  • Invalid JSON response
  • Incorrect database connection path
  • Not setting appropriate HTTP status codes
  • Mixing HTML output with JSON responses

26. Keep API Responses as JSON

A REST API endpoint should return API data in a consistent format.

Example:

{
    "success": true,
    "message": "Students retrieved successfully",
    "data": []
}

Avoid printing unrelated HTML, warnings, or debugging text in the API response.

27. Test the Entry Point

Use Postman to test the endpoint.

GET
http://localhost/student_api/api/students.php

Then check:

  • HTTP status code
  • Response headers
  • Response JSON
  • Error messages

28. Recommended Entry Point Flow

Receive Request
       ↓
Set JSON Header
       ↓
Load Configuration
       ↓
Connect Database
       ↓
Identify HTTP Method
       ↓
Validate Request
       ↓
Perform Operation
       ↓
Set Status Code
       ↓
Return JSON

29. Complete Project Connection

student_api/
│
├── config/
│   └── database.php
│
├── api/
│   └── students.php
│
└── index.php

        ↓

React Native
        ↓
students.php
        ↓
database.php
        ↓
MySQL

This is the basic connection between the mobile application, API entry point, database configuration, and MySQL database.

30. PHP API Entry Point Summary

The API entry point is an important part of a REST API. It receives the client request, identifies the HTTP method, communicates with the database when required, and returns a JSON response. Our students.php endpoint will become the main entry point for student-related API operations.

Client
  ↓
students.php
  ↓
HTTP Method
  ↓
PHP Logic
  ↓
MySQL
  ↓
JSON Response

📌 Key Points

  • An API entry point is where an API request starts.
  • PHP files can act as REST API endpoints.
  • students.php will be our student API endpoint.
  • Use Content-Type: application/json for JSON responses.
  • PHP can identify the HTTP method using $_SERVER['REQUEST_METHOD'].
  • GET, POST, PUT, PATCH, and DELETE can be handled by the API.
  • Use json_encode() to create JSON responses.
  • Use http_response_code() to set HTTP status codes.
  • PDO can be included for database communication.
  • Postman can be used to test the API entry point.
  • React Native will communicate with the entry point using HTTP requests.
  • A clean JSON response is important for mobile application integration.

🧠 Quick Quiz

Question: Which PHP variable can be used to identify the HTTP method of an API request?