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.
React Native Form
↓
Axios POST
↓
students.php
↓
JWT Verification
↓
Validate Student Data
↓
PDO INSERT
↓
MySQL
↓
JSON Response
↓
React Native
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.
The mobile application can send the following information:
{
"name": "Rahul Kumar",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "Python",
"address": "Patna"
}
header(
"Content-Type: application/json"
);
The API uses JSON for both requests and responses.
require_once '../config/database.php';
The API uses the PDO connection to communicate with the
student_management database.
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.
$headers = getallheaders();
$authorization =
$headers['Authorization']
?? '';
The server reads the Authorization header sent by the mobile application.
if (
!preg_match(
'/Bearer\s(\S+)/',
$authorization,
$matches
)
) {
http_response_code(401);
echo json_encode([
"success" => false,
"message" =>
"Authentication required"
]);
exit;
}
$token = $matches[1];
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;
}
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.
$input = json_decode(
file_get_contents("php://input"),
true
);
The JSON request body is converted into a PHP associative array.
$name =
trim($input['name'] ?? '');
$email =
trim($input['email'] ?? '');
$mobile =
trim($input['mobile'] ?? '');
$course =
trim($input['course'] ?? '');
$address =
trim($input['address'] ?? '');
The student's name should be required.
if ($name === '') {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Student name is required"
]);
exit;
}
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;
}
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;
}
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;
}
$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.
$studentId =
$pdo->lastInsertId();
Since the ID is AUTO_INCREMENT, MySQL generates it automatically.
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.
<?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"
]);
}
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);
interface AddStudentRequest {
name: string;
email: string;
mobile: string;
course: string;
address: string;
}
This interface describes the request body sent to the API.
interface AddStudentResponse {
success: boolean;
message: string;
data?: {
id: number;
name: string;
email: string;
mobile: string;
course: string;
address: string;
};
}
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.
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.
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.
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"
}
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
The Add Student API is now ready to receive student information from the React Native application.
/api/students.php.Question: Which HTTP status code is commonly returned when a new student has been successfully created?