Lesson 143 of 158 – Project Add Student API
90%

Project Add Student API

In this lesson, we will create the Add Student API for our Student Management mobile application.

The React Native application will send student information using Axios. The PHP API will authenticate the request, validate the data, and insert the student into the MySQL database using PDO.

Project Goal: Create a secure POST API for adding students using JWT authentication, PHP, MySQL, PDO, JSON, and TypeScript.

1. Add Student API Flow

React Native Form
       ↓
    Axios POST
       ↓
students.php
       ↓
JWT Verification
       ↓
Validate Student Data
       ↓
PDO INSERT
       ↓
MySQL
       ↓
JSON Response
       ↓
React Native

2. HTTP Method

Creating a new student is a resource creation operation, so we use the HTTP POST method.

POST /api/students.php

The student information will be sent inside the JSON request body.

3. Student Request Data

The mobile application can send the following information:

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "mobile": "9876543210",
    "course": "Python",
    "address": "Patna"
}

4. API Content Type

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

The API uses JSON for both requests and responses.

5. Database Connection

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

The API uses the PDO connection to communicate with the student_management database.

6. JWT Authentication

The Add Student API should be protected. A user must send a valid JWT token.

Authorization:
Bearer YOUR_JWT_TOKEN

The API should verify the token before inserting the student.

7. Read Authorization Header

$headers = getallheaders();

$authorization =
    $headers['Authorization']
    ?? '';

The server reads the Authorization header sent by the mobile application.

8. Extract Bearer Token

if (
    !preg_match(
        '/Bearer\s(\S+)/',
        $authorization,
        $matches
    )
) {

    http_response_code(401);

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

    exit;
}

$token = $matches[1];

9. Verify JWT

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

try {

    $decoded = JWT::decode(
        $token,
        new Key(
            $secretKey,
            'HS256'
        )
    );

} catch (Exception $e) {

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid or expired token"
    ]);

    exit;
}

10. Check HTTP Method

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

    http_response_code(405);

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

    exit;
}

Only POST requests should create a new student.

11. Read JSON Body

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

The JSON request body is converted into a PHP associative array.

12. Get Student Fields

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

$email =
    trim($input['email'] ?? '');

$mobile =
    trim($input['mobile'] ?? '');

$course =
    trim($input['course'] ?? '');

$address =
    trim($input['address'] ?? '');

13. Validate Student Name

The student's name should be required.

if ($name === '') {

    http_response_code(422);

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

    exit;
}

14. Validate Email

If an email is provided, it can be validated using filter_var().

if (
    $email !== '' &&
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {

    http_response_code(422);

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

    exit;
}

15. Validate Mobile

The mobile number should also be validated according to the application's requirements.

if (
    $mobile !== '' &&
    !preg_match(
        '/^[0-9]{10,15}$/',
        $mobile
    )
) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid mobile number"
    ]);

    exit;
}

16. Validate Course

The course field can be required if every student must belong to a course.

if ($course === '') {

    http_response_code(422);

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

    exit;
}

17. Insert Student

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

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

Prepared statements safely pass the values to MySQL.

18. Get New Student ID

$studentId =
    $pdo->lastInsertId();

Since the ID is AUTO_INCREMENT, MySQL generates it automatically.

19. Successful Response

http_response_code(201);

echo json_encode([
    "success" => true,
    "message" =>
        "Student added successfully",
    "data" => [
        "id" => $studentId,
        "name" => $name,
        "email" => $email,
        "mobile" => $mobile,
        "course" => $course,
        "address" => $address
    ]
]);

HTTP 201 means that a new resource was successfully created.

20. Complete PHP Add Student API

<?php

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

require_once '../config/database.php';
require_once __DIR__ .
    '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secretKey =
    'CHANGE_THIS_TO_A_LONG_RANDOM_SECRET';

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

    http_response_code(405);

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

    exit;
}

$headers = getallheaders();

$authorization =
    $headers['Authorization']
    ?? '';

if (
    !preg_match(
        '/Bearer\s(\S+)/',
        $authorization,
        $matches
    )
) {

    http_response_code(401);

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

    exit;
}

$token = $matches[1];

try {

    $decoded = JWT::decode(
        $token,
        new Key(
            $secretKey,
            'HS256'
        )
    );

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

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

    $email =
        trim($input['email'] ?? '');

    $mobile =
        trim($input['mobile'] ?? '');

    $course =
        trim($input['course'] ?? '');

    $address =
        trim($input['address'] ?? '');

    if ($name === '') {

        http_response_code(422);

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

        exit;
    }

    if (
        $email !== '' &&
        !filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        )
    ) {

        http_response_code(422);

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

        exit;
    }

    if (
        $mobile !== '' &&
        !preg_match(
            '/^[0-9]{10,15}$/',
            $mobile
        )
    ) {

        http_response_code(422);

        echo json_encode([
            "success" => false,
            "message" =>
                "Invalid mobile number"
        ]);

        exit;
    }

    if ($course === '') {

        http_response_code(422);

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

        exit;
    }

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

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

    $studentId =
        $pdo->lastInsertId();

    http_response_code(201);

    echo json_encode([
        "success" => true,
        "message" =>
            "Student added successfully",
        "data" => [
            "id" => $studentId,
            "name" => $name,
            "email" => $email,
            "mobile" => $mobile,
            "course" => $course,
            "address" => $address
        ]
    ]);

} catch (Exception $e) {

    error_log($e->getMessage());

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid or expired token"
    ]);
}

21. React Native Add Student State

const [name, setName] =
    useState("");

const [email, setEmail] =
    useState("");

const [mobile, setMobile] =
    useState("");

const [course, setCourse] =
    useState("");

const [address, setAddress] =
    useState("");

const [loading, setLoading] =
    useState(false);

22. TypeScript Add Student Interface

interface AddStudentRequest {
    name: string;
    email: string;
    mobile: string;
    course: string;
    address: string;
}

This interface describes the request body sent to the API.

23. Add Student Response Interface

interface AddStudentResponse {
    success: boolean;
    message: string;
    data?: {
        id: number;
        name: string;
        email: string;
        mobile: string;
        course: string;
        address: string;
    };
}

24. Axios Add Student Request

const response =
    await api.post<AddStudentResponse>(
        "/students.php",
        {
            name,
            email,
            mobile,
            course,
            address
        }
    );

console.log(response.data);

If the Axios instance already has a JWT request interceptor, the Authorization header can be added automatically.

25. Handle Successful Add

if (response.data.success) {

    Alert.alert(
        "Success",
        response.data.message
    );

    // Clear form
    // Refresh student list
    // Navigate back

}

After successfully adding a student, the application can return to the student list and refresh the data.

26. Handle API Errors

try {

    const response =
        await api.post<AddStudentResponse>(
            "/students.php",
            {
                name,
                email,
                mobile,
                course,
                address
            }
        );

} catch (error) {

    Alert.alert(
        "Error",
        "Unable to add student"
    );

}

A centralized Axios error handler can later display validation and authentication errors more accurately.

27. Testing with Postman

Method: POST

URL:

https://example.com/api/students.php

Headers:

Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN

Body:

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "mobile": "9876543210",
    "course": "Python",
    "address": "Patna"
}

28. Add Student Security

  • Require a valid JWT.
  • Validate all student fields on the server.
  • Use PDO prepared statements.
  • Do not trust client-side validation alone.
  • Use HTTPS in production.
  • Do not expose database credentials.
  • Return safe error messages.
  • Check authorization if different user roles have different permissions.
  • Do not accept authentication tokens through URL parameters.

29. Complete Add Student Flow

Add Student Screen
        ↓
TypeScript Form State
        ↓
Axios POST
        ↓
JWT Interceptor
        ↓
PHP students.php
        ↓
JWT Verification
        ↓
Input Validation
        ↓
PDO INSERT
        ↓
MySQL
        ↓
HTTP 201
        ↓
JSON Response
        ↓
React Native
        ↓
Refresh Student List

30. Add Student API Summary

The Add Student API is now ready to receive student information from the React Native application.

  • POST is used to create a student.
  • A JWT is required for authentication.
  • PHP validates the request body.
  • Email and mobile values can be validated.
  • PDO prepared statements insert the record.
  • MySQL generates the student ID.
  • HTTP 201 indicates successful creation.
  • Axios sends the request from React Native.
  • TypeScript interfaces define request and response data.
  • The next lesson will implement student update functionality.

📌 Key Points

  • The Add Student API uses POST.
  • The endpoint is /api/students.php.
  • A valid Bearer JWT should be required.
  • Student data is received as JSON.
  • Server-side validation is required.
  • PDO prepared statements should be used for INSERT.
  • HTTP 201 represents successful student creation.
  • Axios can send the student form data.
  • TypeScript interfaces provide type safety.
  • The next lesson will cover updating students.

🧠 Quick Quiz

Question: Which HTTP status code is commonly returned when a new student has been successfully created?