Lesson 111 of 158 – Axios PUT Request
70%

Axios PUT Request

The Axios PUT method is used to update an existing resource through a REST API. In a React Native application, Axios can send updated data to a PHP REST API, which can then update the corresponding record in MySQL.

Note: In this lesson, we will learn how to update records using React Native + Axios + PHP REST API + MySQL.

1. What is a PUT Request?

A PUT request is commonly used to update an existing resource.

React Native
      ↓
  Axios PUT
      ↓
 PHP REST API
      ↓
   Validate
      ↓
    MySQL
      ↓
 Updated Record
      ↓
 JSON Response

2. PUT vs POST

POST PUT
Usually creates a resource Usually updates an existing resource
Example: Add student Example: Update student
Usually does not require an existing ID Usually identifies an existing resource

3. Basic Axios PUT Syntax

const response =
    await axios.put(
        API_URL,
        data
    );

The first argument is the API URL and the second argument contains the updated data.

4. Updating a Student

const response =
    await axios.put(
        `${API_URL}?id=10`,
        {
            name: "Rahul Kumar",
            email: "rahul@example.com",
            course: "React Native"
        }
    );

console.log(
    response.data
);

Here, id=10 identifies the student that should be updated.

5. Using async/await

async function updateStudent() {

    try {

        const response =
            await axios.put(
                `${API_URL}?id=10`,
                {
                    name: "Rahul Kumar",
                    course: "React Native"
                }
            );

        console.log(
            response.data
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

6. PUT Request Body

The request body contains the data that should be updated.

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "course": "TypeScript"
}

Axios can send this JavaScript object as JSON.

7. Sending Content-Type

const response =
    await axios.put(

        `${API_URL}?id=10`,

        {
            name: "Rahul Kumar",
            course: "TypeScript"
        },

        {
            headers: {
                "Content-Type":
                    "application/json"
            }
        }
    );

8. PHP Reading PUT Data

PHP can read the JSON body of a PUT request using php://input.

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

9. Getting the Student ID

The API needs to know which student should be updated.

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

The API should validate the ID before executing the update.

10. Validating the ID

if (!$id) {

    http_response_code(400);

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

    exit;
}

11. Reading Updated Fields

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

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

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

These values should be validated before updating the database.

12. Validating Required Fields

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

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "All fields are required"
    ]);

    exit;
}

13. Checking Whether the Record Exists

$check = $pdo->prepare(
    "SELECT id
     FROM students
     WHERE id = ?"
);

$check->execute([
    $id
]);

if (!$check->fetch()) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" =>
            "Student not found"
    ]);

    exit;
}

14. Updating the Database

Use a prepared UPDATE statement to modify the existing record.

$stmt = $pdo->prepare(
    "UPDATE students
     SET name = ?,
         email = ?,
         course = ?
     WHERE id = ?"
);

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

15. Checking rowCount()

Remember that rowCount() can be 0 when the submitted values are identical to the existing values. Therefore, it should not automatically be treated as "student not found" when you have already checked that the record exists.

16. Returning Updated Data

$getStudent = $pdo->prepare(
    "SELECT id, name, email, course
     FROM students
     WHERE id = ?"
);

$getStudent->execute([
    $id
]);

$student =
    $getStudent->fetch(
        PDO::FETCH_ASSOC
    );

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" =>
        "Student updated successfully",
    "data" => $student
]);

17. Axios PUT Response

React Native can read the JSON response using response.data.

const response =
    await axios.put(
        `${API_URL}?id=${id}`,
        student
    );

console.log(
    response.data.message
);

console.log(
    response.data.data
);

18. PUT Request with React Native State

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

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

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

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

const [message, setMessage] =
    useState("");

19. Update Function in React Native

async function updateStudent() {

    setLoading(true);
    setMessage("");

    try {

        const response =
            await axios.put(
                `${API_URL}?id=${studentId}`,
                {
                    name: name.trim(),
                    email: email.trim(),
                    course: course.trim()
                }
            );

        setMessage(
            response.data.message
        );

    } catch (error) {

        setMessage(
            error.response?.data?.message ||
            "Unable to update student"
        );

    } finally {

        setLoading(false);
    }
}

20. PUT Request with JWT Authentication

A protected update endpoint should verify the user's JWT token and authorization before changing the record.

const response =
    await axios.put(

        `${API_URL}?id=${studentId}`,

        {
            name,
            email,
            course
        },

        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

21. Handling HTTP 404

If the requested student does not exist, the PHP API can return HTTP 404 Not Found.

try {

    await axios.put(
        `${API_URL}?id=999`,
        student
    );

} catch (error) {

    if (
        error.response?.status === 404
    ) {

        console.log(
            "Student not found"
        );
    }
}

22. Handling Validation Errors

The server can return HTTP 422 when the submitted data is invalid.

catch (error) {

    if (
        error.response?.status === 422
    ) {

        setMessage(
            error.response.data.message
        );
    }
}

23. Update Button

<Button
    title="Update Student"
    onPress={updateStudent}
/>

The button can call the update function when the user wants to save changes.

24. Update Form Example

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Student Name"
/>

<TextInput
    value={email}
    onChangeText={setEmail}
    placeholder="Email"
/>

<TextInput
    value={course}
    onChangeText={setCourse}
    placeholder="Course"
/>

<Button
    title="Update Student"
    onPress={updateStudent}
/>

<Text>
    {message}
</Text>

25. Complete PHP PUT API

<?php

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

require_once "../db.php";

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$id) {

    http_response_code(400);

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

    exit;
}

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

if (!is_array($input)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid JSON data"
    ]);

    exit;
}

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

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

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

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

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "All fields are required"
    ]);

    exit;
}

if (
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {

    http_response_code(422);

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

    exit;
}

$check = $pdo->prepare(
    "SELECT id
     FROM students
     WHERE id = ?"
);

$check->execute([
    $id
]);

if (!$check->fetch()) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" =>
            "Student not found"
    ]);

    exit;
}

$stmt = $pdo->prepare(
    "UPDATE students
     SET name = ?,
         email = ?,
         course = ?
     WHERE id = ?"
);

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

$getStudent = $pdo->prepare(
    "SELECT id, name, email, course
     FROM students
     WHERE id = ?"
);

$getStudent->execute([
    $id
]);

$student =
    $getStudent->fetch(
        PDO::FETCH_ASSOC
    );

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" =>
        "Student updated successfully",
    "data" => $student
]);

26. Complete React Native PUT Function

async function updateStudent() {

    if (
        name.trim() === "" ||
        email.trim() === "" ||
        course.trim() === ""
    ) {

        setMessage(
            "Please fill all fields"
        );

        return;
    }

    setLoading(true);
    setMessage("");

    try {

        const response =
            await axios.put(

                `${API_URL}?id=${studentId}`,

                {
                    name:
                        name.trim(),

                    email:
                        email.trim(),

                    course:
                        course.trim()
                }
            );

        if (
            response.status === 200
        ) {

            setMessage(
                response.data.message
            );
        }

    } catch (error) {

        if (error.response) {

            setMessage(
                error.response.data?.message ||
                "Server error"
            );

        } else {

            setMessage(
                "Network error"
            );
        }

    } finally {

        setLoading(false);
    }
}

27. Refreshing the Student List

After updating a student, the application may refresh the student list or update the corresponding item in local state.

await updateStudent();

const response =
    await axios.get(
        "/students.php"
    );

setStudents(
    response.data.data || []
);

Another approach is to update only the changed item in the existing state.

28. Complete React Native Update Screen

import React, {
    useState
} from "react";

import {
    View,
    Text,
    TextInput,
    Button,
    ActivityIndicator
} from "react-native";

import axios from "axios";

const API_URL =
    "https://example.com/api/students.php";

export default function EditStudent({
    studentId
}) {

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

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

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

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

    const [message, setMessage] =
        useState("");

    async function updateStudent() {

        if (
            name.trim() === "" ||
            email.trim() === "" ||
            course.trim() === ""
        ) {

            setMessage(
                "Please fill all fields"
            );

            return;
        }

        setLoading(true);
        setMessage("");

        try {

            const response =
                await axios.put(

                    `${API_URL}?id=${studentId}`,

                    {
                        name:
                            name.trim(),

                        email:
                            email.trim(),

                        course:
                            course.trim()
                    }
                );

            setMessage(
                response.data.message
            );

        } catch (error) {

            if (error.response) {

                setMessage(
                    error.response.data?.message ||
                    "Unable to update student"
                );

            } else {

                setMessage(
                    "Network error"
                );
            }

        } finally {

            setLoading(false);
        }
    }

    return (

        <View style={{
            padding: 20
        }}>

            <Text>
                Edit Student
            </Text>

            <TextInput
                value={name}
                onChangeText={setName}
                placeholder="Student Name"
            />

            <TextInput
                value={email}
                onChangeText={setEmail}
                placeholder="Email"
                keyboardType=
                    "email-address"
            />

            <TextInput
                value={course}
                onChangeText={setCourse}
                placeholder="Course"
            />

            {loading && (
                <ActivityIndicator
                    size="small"
                />
            )}

            <Button
                title="Update Student"
                onPress={updateStudent}
            />

            <Text>
                {message}
            </Text>

        </View>
    );
}

29. Common Axios PUT Mistakes

  • Using the wrong HTTP method.
  • Forgetting the student ID.
  • Using an invalid API URL.
  • Sending incorrect field names.
  • Not validating the request body.
  • Not checking whether the record exists.
  • Building SQL with string concatenation.
  • Not using prepared statements.
  • Not handling 404 and 422 errors.
  • Forgetting JWT authorization for protected APIs.
  • Not refreshing or updating local state after a successful update.

30. Complete Axios PUT Flow

React Native Edit Form
          ↓
       User Input
          ↓
      axios.put()
          ↓
      JSON Request
          ↓
      PHP REST API
          ↓
       Validate
          ↓
    Check Student ID
          ↓
      Prepared SQL
          ↓
        MySQL
          ↓
    Update Record
          ↓
     JSON Response
          ↓
     React Native
          ↓
   Update UI / List

Axios PUT requests are useful for editing existing records such as students, users, products, profiles and other resources.

📌 Key Points

  • axios.put() is commonly used to update an existing resource.
  • The record ID identifies which resource should be updated.
  • Axios can send JSON data in the PUT request body.
  • PHP can read PUT JSON data using php://input.
  • Always validate the ID and request data.
  • Check whether the record exists before updating it.
  • Use PDO prepared statements.
  • HTTP 200 can indicate a successful update.
  • HTTP 404 can indicate that the resource does not exist.
  • HTTP 422 can be used for validation errors.
  • Protected PUT APIs should verify authentication and authorization.
  • Update the React Native UI after a successful request.

🧠 Quick Quiz

Question: Which Axios method is commonly used to update an existing resource?