A POST request is used when a React Native application needs to send data to a REST API. It is commonly used for registration, login, adding students, creating products, submitting forms, and other operations that create data on the server.
POST is an HTTP method commonly used to send data to a server.
React Native
↓
POST Request
↓
PHP REST API
↓
Validate Data
↓
MySQL
↓
JSON Response
POST can be used for operations such as:
fetch(API_URL, {
method: "POST"
});
The request body can be added when the application needs to send data.
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com"
})
}
);
JavaScript objects cannot simply be placed into a JSON request body. JSON.stringify() converts the JavaScript object into a JSON string.
const student = {
name: "Rahul",
email: "rahul@example.com"
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
When sending JSON, use the Content-Type header.
headers: {
"Content-Type": "application/json"
}
This tells the PHP API that the request body contains JSON data.
The PHP API can read the JSON request body using php://input.
$input = json_decode(
file_get_contents("php://input"),
true
);
$name = $input['name'] ?? '';
$email = $input['email'] ?? '';
const student = {
name: "Rahul Kumar",
email: "rahul@example.com",
course: "React Native"
};
const response = await fetch(
"https://example.com/api/students.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
}
);
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
}
);
const result = await response.json();
console.log(result);
A PHP API can return a standard response after successfully creating a record.
{
"success": true,
"message": "Student created successfully",
"data": {
"id": 15,
"name": "Rahul Kumar"
}
}
React Native can use result.data to access the newly created record.
const result = await response.json();
if (result.success) {
console.log(
"Student created:",
result.data
);
} else {
console.log(
result.message
);
}
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
}
);
if (!response.ok) {
console.log(
"HTTP Error:",
response.status
);
}
const result = await response.json();
async function addStudent() {
try {
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com"
})
}
);
const result =
await response.json();
console.log(result);
} catch (error) {
console.log(
"Network Error:",
error.message
);
}
}
React Native form values can be collected into an object and sent to the API.
const student = {
name: name,
email: email,
course: course
};
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
}
);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
<TextInput
value={name}
onChangeText={setName}
placeholder="Enter name"
/>
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Enter email"
/>
The state values can later be sent using a POST request.
async function handleSubmit() {
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name,
email
})
}
);
const result =
await response.json();
console.log(result);
}
The PHP API must validate data even if React Native already validates it.
$errors = [];
if ($name === '') {
$errors['name'] = "Name is required";
}
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
$errors['email'] =
"Valid email is required";
}
Client-side validation improves user experience, while server-side validation protects the API.
The PHP API can return HTTP 422 for invalid input.
{
"success": false,
"message": "Validation failed",
"errors": {
"name": "Name is required",
"email": "Invalid email address"
}
}
React Native can display these messages to the user.
const result = await response.json();
if (!result.success) {
if (result.errors) {
console.log(
result.errors
);
}
console.log(
result.message
);
}
Protected POST endpoints can require a JWT token.
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json",
"Authorization":
`Bearer ${token}`
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com"
})
}
);
After validation, the PHP API can insert the received data using PDO.
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email)
VALUES (?, ?)"
);
$stmt->execute([
$name,
$email
]);
$studentId = $pdo->lastInsertId();
Prepared statements help protect against SQL injection.
When a new resource is successfully created, the API can return HTTP 201.
http_response_code(201);
echo json_encode([
"success" => true,
"message" => "Student created successfully",
"data" => [
"id" => $studentId
]
]);
const result = await response.json();
if (result.success) {
Alert.alert(
"Success",
result.message
);
}
After successful creation, the application can navigate to another screen or refresh the list.
if (result.success) {
setName("");
setEmail("");
Alert.alert(
"Success",
"Student added successfully"
);
}
Clearing the form after a successful request provides a better user experience.
const [loading, setLoading] =
useState(false);
async function handleSubmit() {
setLoading(true);
try {
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name,
email
})
}
);
const result =
await response.json();
console.log(result);
} catch (error) {
console.log(error.message);
} finally {
setLoading(false);
}
}
A loading state can also prevent the user from submitting the same form repeatedly while the request is still running.
async function handleSubmit() {
if (loading) {
return;
}
setLoading(true);
try {
// POST request
} finally {
setLoading(false);
}
}
async function createStudent(student) {
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify(student)
}
);
const result =
await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Unable to create student"
);
}
return result;
}
const API_URL =
"https://example.com/api/students.php";
async function addStudent() {
const student = {
name: "Rahul Kumar",
email: "rahul@example.com",
course: "React Native"
};
try {
const response = await fetch(
API_URL,
{
method: "POST",
headers: {
"Content-Type":
"application/json",
"Accept":
"application/json"
},
body: JSON.stringify(student)
}
);
const result =
await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Request failed"
);
}
if (result.success) {
console.log(
"Created:",
result.data
);
} else {
console.log(
result.message
);
}
} catch (error) {
console.log(
"POST Error:",
error.message
);
}
}
React Native Form
↓
Collect Input
↓
Validate
↓
fetch()
↓
POST Request
↓
PHP API
↓
Server Validation
↓
PDO
↓
MySQL
↓
JSON Response
↓
React Native
↓
Success / Error
↓
Update UI
This pattern is the foundation for registration forms, student creation, login requests, course creation, and many other mobile application features.
Question: Which JavaScript method is used to convert a React Native object into JSON before sending it in a POST request?