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.
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
| 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 |
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.
const response =
await axios.post(
"https://example.com/api/students.php",
{
name: "Rahul Kumar",
email: "rahul@example.com"
}
);
console.log(
response.data
);
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
);
}
}
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
);
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"
}
}
);
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
);
When a new resource is successfully created, the REST API commonly returns HTTP status 201 Created.
if (response.status === 201) {
console.log(
"Student created"
);
}
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
);
}
<TextInput
value={name}
onChangeText={setName}
placeholder="Enter student name"
/>
The entered value can later be sent in the POST request.
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Enter email"
keyboardType="email-address"
/>
<Button
title="Add Student"
onPress={addStudent}
/>
Pressing the button can call the function that sends the POST request.
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.
$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;
}
Always validate data on the server even if the React Native application already validates it.
if (
!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid email"
]);
exit;
}
$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.
After inserting a record, PDO can provide the generated ID.
$studentId =
$pdo->lastInsertId();
This ID can be returned to the React Native application.
http_response_code(201);
echo json_encode([
"success" => true,
"message" =>
"Student added successfully",
"data" => [
"id" => $studentId,
"name" => $name,
"email" => $email,
"course" => $course
]
]);
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"
);
}
}
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);
}
}
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"
);
}
}
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.
<?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
]
]);
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);
}
}
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.
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>
);
}
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.
Question: Which Axios method is commonly used to create a new record through a REST API?