Lesson 110 of 158 – Axios POST Request
70%

Axios POST Request

The Axios POST method is used to send data from a React Native application to a REST API. It is commonly used for creating new records such as students, users, products, admissions and other database records.

Note: In this lesson, we will learn how to send JSON data from React Native → Axios → PHP REST API → MySQL.

1. What is a POST Request?

A POST request sends data to the server. The server can validate the data and create a new record in the database.

React Native
      ↓
  Axios POST
      ↓
 PHP REST API
      ↓
   Validate
      ↓
    MySQL
      ↓
 JSON Response

2. POST vs GET

GET POST
Usually retrieves data Usually creates/sends data
Parameters can be in URL Data is commonly sent in request body
Example: Get students Example: Add student

3. Basic Axios POST Syntax

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

The first argument is the API URL and the second argument contains the data that should be sent to the server.

4. Simple POST Example

const response =
    await axios.post(
        "https://example.com/api/students.php",
        {
            name: "Rahul Kumar",
            email: "rahul@example.com"
        }
    );

console.log(
    response.data
);

5. Using async/await

async function addStudent() {

    try {

        const response =
            await axios.post(
                API_URL,
                {
                    name: "Rahul Kumar",
                    email: "rahul@example.com"
                }
            );

        console.log(
            response.data
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

6. POST JSON Data

Axios can send a JavaScript object as the request body.

const student = {

    name: "Rahul Kumar",

    email: "rahul@example.com",

    course: "React Native"

};

const response =
    await axios.post(
        API_URL,
        student
    );

7. Content-Type Header

A JSON API commonly uses the following Content-Type:

application/json

Axios can send this header explicitly when needed.

const response =
    await axios.post(
        API_URL,
        student,
        {
            headers: {
                "Content-Type":
                    "application/json"
            }
        }
    );

8. Reading POST Response

Suppose the PHP API returns:

{
    "success": true,
    "message": "Student added successfully",
    "data": {
        "id": 15,
        "name": "Rahul Kumar"
    }
}

Axios reads this response through:

const result =
    response.data;

console.log(
    result.message
);

9. HTTP 201 Created

When a new resource is successfully created, the REST API commonly returns HTTP status 201 Created.

if (response.status === 201) {

    console.log(
        "Student created"
    );

}

10. POST Form Data from React Native State

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

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

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

async function addStudent() {

    const response =
        await axios.post(
            API_URL,
            {
                name: name,
                email: email,
                course: course
            }
        );

    console.log(
        response.data
    );
}

11. TextInput for Student Name

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter student name"
/>

The entered value can later be sent in the POST request.

12. TextInput for Email

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

13. POST Button

<Button
    title="Add Student"
    onPress={addStudent}
/>

Pressing the button can call the function that sends the POST request.

14. PHP Reading JSON POST Data

PHP can read JSON request data using php://input.

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

The second parameter true converts the JSON object into a PHP associative array.

15. Reading Individual Fields in PHP

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

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

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

16. Validating POST Data

if ($name === '') {

    http_response_code(422);

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

    exit;
}

Always validate data on the server even if the React Native application already validates it.

17. Validating Email

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

    http_response_code(422);

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

    exit;
}

18. Inserting Data with PDO

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

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

Prepared statements should be used instead of inserting user input directly into SQL.

19. Getting the New Record ID

After inserting a record, PDO can provide the generated ID.

$studentId =
    $pdo->lastInsertId();

This ID can be returned to the React Native application.

20. PHP JSON Success Response

http_response_code(201);

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

21. Handling Axios POST Errors

try {

    const response =
        await axios.post(
            API_URL,
            student
        );

    console.log(
        response.data
    );

} catch (error) {

    if (error.response) {

        console.log(
            error.response.status
        );

        console.log(
            error.response.data
        );

    } else {

        console.log(
            "Network error"
        );
    }
}

22. POST Request with Loading State

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

async function addStudent() {

    setLoading(true);

    try {

        await axios.post(
            API_URL,
            {
                name,
                email,
                course
            }
        );

    } catch (error) {

        console.log(
            error.message
        );

    } finally {

        setLoading(false);
    }
}

23. POST Request with Success Message

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

async function addStudent() {

    try {

        const response =
            await axios.post(
                API_URL,
                {
                    name,
                    email,
                    course
                }
            );

        setMessage(
            response.data.message
        );

    } catch (error) {

        setMessage(
            "Unable to add student"
        );
    }
}

24. POST Request with JWT Authentication

A protected POST endpoint can require a JWT token.

const response =
    await axios.post(

        API_URL,

        {
            name,
            email,
            course
        },

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

The PHP API should verify the token and authorize the user before inserting the record.

25. Complete PHP POST API

<?php

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

require_once "../db.php";

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

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

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

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

if ($name === '') {

    http_response_code(422);

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

    exit;
}

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

    http_response_code(422);

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

    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, course)
     VALUES (?, ?, ?)"
);

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

$studentId =
    $pdo->lastInsertId();

http_response_code(201);

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

26. Complete React Native POST Function

async function addStudent() {

    setLoading(true);
    setMessage("");

    try {

        const response =
            await axios.post(
                API_URL,
                {
                    name: name.trim(),
                    email: email.trim(),
                    course: course.trim()
                }
            );

        setMessage(
            response.data.message
        );

        setName("");
        setEmail("");
        setCourse("");

    } catch (error) {

        if (error.response) {

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

        } else {

            setMessage(
                "Network error"
            );
        }

    } finally {

        setLoading(false);
    }
}

27. Duplicate Data Handling

The server should check for duplicate records when required. For example, an email address may need to be unique.

if ($emailExists) {

    http_response_code(409);

    echo json_encode([
        "success" => false,
        "message" =>
            "Email already exists"
    ]);

    exit;
}

React Native can display the returned message to the user.

28. Complete React Native Student Form

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 AddStudent() {

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

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

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

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

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

    async function addStudent() {

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

            setMessage(
                "Please fill all fields"
            );

            return;
        }

        setLoading(true);
        setMessage("");

        try {

            const response =
                await axios.post(
                    API_URL,
                    {
                        name:
                            name.trim(),

                        email:
                            email.trim(),

                        course:
                            course.trim()
                    }
                );

            setMessage(
                response.data.message
            );

            setName("");
            setEmail("");
            setCourse("");

        } catch (error) {

            if (error.response) {

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

            } else {

                setMessage(
                    "Network error"
                );
            }

        } finally {

            setLoading(false);
        }
    }

    return (

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

            <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="Add Student"
                onPress={addStudent}
            />

            <Text>
                {message}
            </Text>

        </View>
    );
}

29. Common Axios POST Mistakes

  • Using GET when the API expects POST.
  • Sending incorrect field names.
  • Not validating input on the server.
  • Not using prepared statements.
  • Forgetting to send JSON data correctly.
  • Not checking the API response.
  • Not handling HTTP 422 validation errors.
  • Not handling HTTP 409 duplicate errors.
  • Forgetting JWT authentication for protected endpoints.
  • Not showing loading or success/error messages.

30. Complete Axios POST Flow

React Native Form
       ↓
   User Input
       ↓
  axios.post()
       ↓
   JSON Body
       ↓
   PHP REST API
       ↓
    Validate
       ↓
 Prepared SQL
       ↓
     MySQL
       ↓
 Create Record
       ↓
 JSON Response
       ↓
 React Native
       ↓
 Success / Error
       ↓
      UI

Axios POST requests are the foundation for creating records from a mobile application. The next lesson will cover updating existing records with Axios PUT requests.

📌 Key Points

  • axios.post() is used to send data to a REST API.
  • POST is commonly used to create new records.
  • Axios can send a JavaScript object as JSON request data.
  • PHP can read JSON using php://input.
  • Always validate data on the server.
  • Use PDO prepared statements for database operations.
  • A successful creation commonly returns HTTP 201.
  • Use 422 for validation errors when appropriate.
  • Use 409 for conflicts such as duplicate unique data.
  • Use JWT authentication for protected POST endpoints.
  • Always handle loading, success, network and server errors.

🧠 Quick Quiz

Question: Which Axios method is commonly used to create a new record through a REST API?