Lesson 56 of 158 – PHP POST API
56%

PHP POST API

In the previous lessons, we learned how to retrieve all records and a single record using the GET method. Now we will learn how to create a new student using the HTTP POST method.

Note: The POST method is commonly used when the client wants to send new data to the server and create a new database record.

1. What is the POST Method?

The HTTP POST method is commonly used to send data to a server for creating a new resource.

In our project, POST will be used to create a new student.

React Native
     ↓
POST Request
     ↓
PHP REST API
     ↓
MySQL
     ↓
New Student

2. POST vs GET

Method Purpose
GET Retrieve data
POST Create new data

GET is generally used for reading data, while POST is used to submit data to create a new resource.

3. POST API Endpoint

We can use the same student endpoint for POST requests.

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

The HTTP method tells the server what operation the client wants to perform.

4. Create the PHP POST File

Our API file can handle the POST request.

api/
    students.php

The file can contain different logic depending on the HTTP request method.

5. Check the Request Method

PHP provides the HTTP request method through $_SERVER['REQUEST_METHOD'].

$method = $_SERVER['REQUEST_METHOD'];

We can check whether the request is a POST request.

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

    // Create student

}

6. Set JSON Content Type

The API should return JSON responses.

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

This tells the client that the API response is JSON.

7. Include PDO Connection

The API needs a database connection to insert the new student.

require_once "../config/database.php";

This provides the PDO connection stored in $pdo.

8. Receive JSON Request Data

REST APIs commonly receive POST data in JSON format.

PHP can read the raw request body using:

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

The returned value is a string containing the request body.

9. Convert JSON to PHP Array

The JSON request body can be converted into a PHP array using json_decode().

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

The second parameter true makes json_decode return an associative array.

10. Example JSON Request

A client can send student information like this:

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

The PHP API receives this JSON and converts it into a PHP array.

11. Read Individual Values

After decoding the JSON, we can access individual values.

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

The null coalescing operator provides an empty value if the key does not exist.

12. Validate Required Fields

Before inserting data into the database, validate the required fields.

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

    http_response_code(400);

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

    exit;
}

13. INSERT Query

The SQL INSERT statement is used to create a new database record.

INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)

The question marks are placeholders for the values.

14. Prepare the INSERT Query

$stmt = $pdo->prepare(
    "INSERT INTO students
    (name, email, mobile, course)
    VALUES (?, ?, ?, ?)"
);

Prepared statements keep the SQL query separate from the supplied values.

15. Execute the INSERT Query

Pass the received values to the prepared statement.

$stmt->execute([
    $name,
    $email,
    $mobile,
    $course
]);

If the query succeeds, a new student record is inserted into the table.

16. AUTO_INCREMENT ID

Our students table uses an AUTO_INCREMENT primary key.

id INT AUTO_INCREMENT PRIMARY KEY

Therefore, MySQL automatically generates the new student's ID when the record is inserted.

17. Get the New Student ID

PDO provides lastInsertId() to retrieve the ID generated by an AUTO_INCREMENT column.

$student_id = $pdo->lastInsertId();

This ID can be included in the API response.

18. Successful POST Response

After successfully creating a student, the API can return HTTP status code 201 Created.

http_response_code(201);

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

19. Complete Basic POST API

<?php

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

require_once "../config/database.php";

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

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

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

    http_response_code(400);

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

    exit;
}

$stmt = $pdo->prepare(
    "INSERT INTO students
    (name, email, mobile, course)
    VALUES (?, ?, ?, ?)"
);

$stmt->execute([
    $name,
    $email,
    $mobile,
    $course
]);

$student_id = $pdo->lastInsertId();

http_response_code(201);

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

?>

20. Handle Database Errors

Database operations can fail, so the INSERT operation should be handled with try-catch.

try {

    $stmt = $pdo->prepare(
        "INSERT INTO students
        (name, email, mobile, course)
        VALUES (?, ?, ?, ?)"
    );

    $stmt->execute([
        $name,
        $email,
        $mobile,
        $course
    ]);

} catch (PDOException $e) {

    http_response_code(500);

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

}

21. Complete POST API with Error Handling

<?php

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

require_once "../config/database.php";

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

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

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

    http_response_code(400);

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

    exit;
}

try {

    $stmt = $pdo->prepare(
        "INSERT INTO students
        (name, email, mobile, course)
        VALUES (?, ?, ?, ?)"
    );

    $stmt->execute([
        $name,
        $email,
        $mobile,
        $course
    ]);

    $student_id = $pdo->lastInsertId();

    http_response_code(201);

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

} catch (PDOException $e) {

    http_response_code(500);

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

}

?>

22. Test POST API in Postman

Open Postman and select the POST method.

POST

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

Then open the Body section and select:

raw
JSON

23. Send JSON Data

Enter the following JSON in the Postman request body:

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

Then click Send.

24. POST Response

If the student is created successfully, the API can return:

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

The generated ID depends on the records already present in the table.

25. Verify the New Record

After creating a student, you can use the Get All API to verify the record.

GET

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

The newly created student should appear in the response.

26. Common POST Errors

  • Invalid JSON
  • Missing required fields
  • Incorrect Content-Type
  • Database connection failure
  • Incorrect table or column names
  • Invalid data
  • SQL errors

Always check the API response and server logs when a POST request fails.

27. POST API Flow

React Native / Postman
        ↓
POST Request
        ↓
JSON Request Body
        ↓
json_decode()
        ↓
Validate Data
        ↓
PDO Prepared Statement
        ↓
INSERT INTO students
        ↓
MySQL
        ↓
JSON Response

28. POST API and React Native

A React Native application can send a POST request when the user submits a registration or student form.

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"
    })
});

29. Important Security Practice

Never directly insert user-provided values into an SQL query. Use prepared statements instead.

$stmt = $pdo->prepare(
    "INSERT INTO students
    (name, email, mobile, course)
    VALUES (?, ?, ?, ?)"
);

$stmt->execute([
    $name,
    $email,
    $mobile,
    $course
]);

Prepared statements help protect database queries from SQL injection.

30. PHP POST API Summary

The POST API receives JSON data from the client, converts it into a PHP array, validates the required values, and inserts the new student into the MySQL database using a PDO prepared statement. The API then returns the newly created student ID as a JSON response.

POST
 ↓
JSON Body
 ↓
json_decode()
 ↓
Validation
 ↓
INSERT
 ↓
MySQL
 ↓
lastInsertId()
 ↓
JSON Response

📌 Key Points

  • POST is commonly used to create a new resource.
  • POST data can be sent in a JSON request body.
  • php://input reads the raw request body.
  • json_decode() converts JSON into PHP data.
  • Required fields should be validated before inserting data.
  • INSERT INTO is used to create a database record.
  • PDO prepared statements should be used for INSERT queries.
  • lastInsertId() retrieves the generated ID.
  • HTTP 201 indicates that a resource was created successfully.
  • HTTP 400 can be used for invalid client input.
  • HTTP 500 can be used for server or database errors.
  • React Native can send POST requests using Fetch or Axios.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to create a new resource?