A PUT request is commonly used to update an existing resource in a REST API. In a React Native application, Fetch can send updated data to a PHP REST API, which can then validate the data and update the MySQL database.
PUT is an HTTP method commonly used to update an existing resource.
React Native
↓
PUT Request
↓
PHP REST API
↓
Validate Data
↓
MySQL UPDATE
↓
JSON Response
PUT can be used for operations such as:
fetch(API_URL, {
method: "PUT"
});
The request body can contain the new values that should replace or update the existing resource.
const response = await fetch(
`${API_URL}?id=10`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Kumar",
email: "rahulkumar@example.com"
})
}
);
React Native uses JavaScript objects, while the API expects JSON data. JSON.stringify() converts the object into JSON text.
const student = {
name: "Rahul Kumar",
email: "rahulkumar@example.com"
};
const jsonData =
JSON.stringify(student);
When sending JSON data, specify the Content-Type header.
headers: {
"Content-Type": "application/json"
}
This tells the PHP API that the request body contains JSON.
The API needs to know which record should be updated.
A common approach is to send the record ID as a query parameter.
PUT /api/students.php?id=10
Here, 10 identifies the student that should be updated.
const studentId = 10;
const response = await fetch(
`${API_URL}?id=${studentId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Kumar",
email: "rahul@example.com"
})
}
);
const response = await fetch(
`${API_URL}?id=10`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Kumar",
email: "rahulkumar@example.com"
})
}
);
const result = await response.json();
console.log(result);
After a successful update, the PHP API can return:
{
"success": true,
"message": "Student updated successfully",
"data": {
"id": 10,
"name": "Rahul Kumar",
"email": "rahulkumar@example.com"
}
}
const result = await response.json();
if (result.success) {
console.log(
"Updated:",
result.data
);
} else {
console.log(
result.message
);
}
const response = await fetch(
`${API_URL}?id=10`,
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Kumar"
})
}
);
if (!response.ok) {
console.log(
"HTTP Error:",
response.status
);
}
const result = await response.json();
async function updateStudent() {
try {
const response = await fetch(
`${API_URL}?id=10`,
{
method: "PUT",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: "Rahul Kumar",
email:
"rahulkumar@example.com"
})
}
);
const result =
await response.json();
console.log(result);
} catch (error) {
console.log(
"Network Error:",
error.message
);
}
}
PHP can read JSON data from the request body.
$input = json_decode(
file_get_contents("php://input"),
true
);
$name = trim($input['name'] ?? '');
$email = trim($input['email'] ?? '');
$studentId = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
if (!$studentId) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
$errors = [];
if ($name === '') {
$errors['name'] =
"Name is required";
}
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
$errors['email'] =
"Valid email is required";
}
if (!empty($errors)) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" => "Validation failed",
"errors" => $errors
]);
exit;
}
PDO prepared statements should be used for the database update.
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?, email = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$studentId
]);
rowCount() should not be treated as a universal way to distinguish "not found" from "no values changed" for every database setup. If that distinction matters, first check whether the record exists.
$check = $pdo->prepare(
"SELECT id
FROM students
WHERE id = ?"
);
$check->execute([
$studentId
]);
if (!$check->fetch()) {
http_response_code(404);
echo json_encode([
"success" => false,
"message" => "Student not found"
]);
exit;
}
Protected update endpoints should verify the user's authentication token.
const response = await fetch(
`${API_URL}?id=${studentId}`,
{
method: "PUT",
headers: {
"Content-Type":
"application/json",
"Authorization":
`Bearer ${token}`
},
body: JSON.stringify({
name,
email
})
}
);
Authentication alone does not necessarily mean the user is allowed to update every student.
JWT Verification
↓
Identify User
↓
Check Role / Permission
↓
Check Resource Ownership
↓
Update Student
The server should enforce these rules.
Existing student information can first be loaded into state.
const [name, setName] = useState("");
const [email, setEmail] = useState("");
setName(student.name);
setEmail(student.email);
After editing the fields, the updated values can be sent using PUT.
async function handleUpdate() {
const response = await fetch(
`${API_URL}?id=${studentId}`,
{
method: "PUT",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: name,
email: email
})
}
);
const result =
await response.json();
if (result.success) {
Alert.alert(
"Success",
result.message
);
} else {
Alert.alert(
"Error",
result.message
);
}
}
const [loading, setLoading] =
useState(false);
async function handleUpdate() {
if (loading) {
return;
}
setLoading(true);
try {
// PUT request
} catch (error) {
console.log(error.message);
} finally {
setLoading(false);
}
}
The loading state can prevent accidental repeated submissions.
The API may return 404 if the requested student does not exist.
if (response.status === 404) {
Alert.alert(
"Not Found",
"Student does not exist."
);
return;
}
A PHP API can return HTTP 422 when submitted values are invalid.
if (response.status === 422) {
const result =
await response.json();
console.log(
result.errors
);
return;
}
The application can use these field-specific errors to show messages beside the form fields.
async function updateStudent(
studentId,
student
) {
const response = await fetch(
`${API_URL}?id=${studentId}`,
{
method: "PUT",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify(student)
}
);
const result =
await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Unable to update student"
);
}
return result;
}
const API_URL =
"https://example.com/api/students.php";
async function updateStudent() {
const studentId = 10;
const student = {
name: "Rahul Kumar",
email: "rahulkumar@example.com",
course: "React Native"
};
try {
const response = await fetch(
`${API_URL}?id=${studentId}`,
{
method: "PUT",
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 ||
"Update failed"
);
}
if (result.success) {
console.log(
"Updated successfully:",
result.data
);
} else {
console.log(
result.message
);
}
} catch (error) {
console.log(
"PUT Error:",
error.message
);
}
}
React Native Edit Screen
↓
Load Existing Data
↓
Edit Form
↓
Validate Input
↓
fetch()
↓
PUT Request
↓
PHP REST API
↓
Authentication
↓
Authorization
↓
Validation
↓
PDO UPDATE
↓
MySQL
↓
JSON Response
↓
React Native
↓
Update Screen
This pattern can be used for student profiles, user accounts, courses, products, employee records, and other resources that need to be updated from a React Native application.
Question: Which HTTP method is commonly used to update an existing resource in a REST API?