Lesson 12 of 158 – POST Method
12%

POST Method

The POST method is an HTTP method commonly used to send data to a server. In REST API development, POST is mainly used to create a new resource.

For example, when a user registers from a React Native application, the mobile app can send the user's name, email, and password to a PHP REST API using a POST request.

Note: POST is commonly used when the client wants the server to create a new resource, such as a new user, student, product, or order.

1. What is POST?

POST is an HTTP method used to send data to a server.

In REST APIs, POST is commonly used to create a new resource.


POST /api/students

The client sends student information to the server, and the server processes that information.

2. Purpose of POST

The main purpose of POST in a REST API is to create a new resource.

Examples include:

  • Creating a new student
  • Registering a new user
  • Creating a new product
  • Creating an order
  • Submitting a form
  • Adding a new course

3. POST and REST API

A REST API usually uses POST when a new resource needs to be created.


POST /api/students

The request can contain the new student's information in the request body.

4. POST Request Body

POST requests commonly send data through the request body.


{
    "name": "Rahul",
    "email": "rahul@example.com",
    "course": "React Native"
}

The server receives this data and can use it to create a new record.

5. POST and JSON

JSON is commonly used to send structured data in a POST request.


{
    "name": "Amit",
    "email": "amit@example.com",
    "mobile": "9876543210"
}

The API reads the JSON data and processes the submitted information.

6. Content-Type Header

When JSON data is sent in a POST request, the client commonly uses the Content-Type header.


Content-Type: application/json

This tells the server that the request body contains JSON data.

7. POST Request Example

A complete POST request can look like this:


POST /api/students HTTP/1.1
Content-Type: application/json

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

The server can use this information to create a student record.

8. POST Response

After processing a POST request, the server sends a response.


{
    "success": true,
    "message": "Student created successfully",
    "id": 15
}

The response can contain the newly created resource ID.

9. HTTP Status Code 201

When a server successfully creates a resource, the HTTP status code 201 Created is commonly used.


HTTP/1.1 201 Created

The response body can contain information about the newly created resource.

10. POST with React Native Fetch

React Native can send POST requests using the Fetch API.


const response = await fetch(
    "https://example.com/api/students",
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            name: "Rahul",
            email: "rahul@example.com"
        })
    }
);

const data = await response.json();

console.log(data);

11. POST Method Option

When using Fetch, the HTTP method must be specified as POST.


fetch(url, {
    method: "POST"
});

Without specifying the method, Fetch uses GET by default.

12. JSON.stringify()

JavaScript objects should be converted into JSON strings before sending them as a JSON request body.


const student = {
    name: "Rahul",
    email: "rahul@example.com"
};

body: JSON.stringify(student)

The server can then decode the JSON data.

13. POST with Async/Await

Async/await makes POST request code easier to read.


const createStudent = async () => {

    const response = await fetch(
        "https://example.com/api/students",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                name: "Rahul",
                email: "rahul@example.com"
            })
        }
    );

    const data = await response.json();

    console.log(data);
};

14. POST Error Handling

POST requests should handle network and server errors.


try {

    const response = await fetch(
        "https://example.com/api/students",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                name: "Rahul"
            })
        }
    );

    if (!response.ok) {
        throw new Error("Request failed");
    }

    const data = await response.json();

} catch (error) {

    console.log(error);

}

15. POST Form Data

A mobile application can collect data from a form and send it to an API using POST.

For example:

  • Name
  • Email
  • Mobile number
  • Course

The collected values can be converted into JSON and sent to the server.

16. POST Registration Example

A registration screen can send user information to a registration API.


POST /api/register

{
    "name": "Rahul",
    "email": "rahul@example.com",
    "password": "mypassword"
}

The server can validate the information and create a new account.

17. POST with PHP REST API

PHP can receive a POST request and process JSON data.


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

The decoded data can then be validated before inserting it into the database.

18. Reading POST JSON in PHP

Suppose React Native sends this JSON:


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

PHP can read the values:


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

$name = $input['name'] ?? '';
$email = $input['email'] ?? '';

19. POST and MySQL INSERT

After validating the submitted data, PHP can insert it into MySQL.


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

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

Prepared statements help prevent SQL injection.

20. Complete PHP POST Flow


POST Request
      ↓
PHP REST API
      ↓
Read JSON
      ↓
Validate Data
      ↓
MySQL INSERT
      ↓
Create JSON Response
      ↓
React Native

This is the basic flow for creating a resource using POST.

21. PHP POST Response

After inserting the record, PHP can return a JSON response.


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

echo json_encode([
    "success" => true,
    "message" => "Student created successfully"
]);

The React Native application can read this response and display a success message.

22. POST Validation

Server-side validation is important when processing POST data.

For example, the API can check:

  • Required fields
  • Email format
  • Mobile number
  • Password length
  • Duplicate email
  • Valid course ID

Never rely only on validation performed inside the mobile application.

23. POST with Axios

Axios provides a convenient method for sending POST requests.


import axios from "axios";

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

console.log(response.data);

24. POST and Authentication

POST is often used for authentication-related operations such as login and registration.

Example:


POST /api/login

{
    "email": "rahul@example.com",
    "password": "mypassword"
}

The server can validate the credentials and return an authentication token.

25. POST and Postman

Postman can be used to test a POST API before connecting it to a React Native application.

In Postman:

  1. Select the POST method.
  2. Enter the API URL.
  3. Open the Body section.
  4. Select raw.
  5. Select JSON.
  6. Enter the JSON data.
  7. Click Send.

26. POST vs GET

GET POST
Usually retrieves data Commonly creates data
Parameters can be in URL Data is commonly sent in body
Used for reading resources Used for creating resources
Example: GET /students Example: POST /students

27. Common POST Errors

  • Forgetting to set the POST method.
  • Forgetting the Content-Type header.
  • Sending invalid JSON.
  • Forgetting JSON.stringify() in Fetch.
  • Not validating input on the server.
  • Using unsafe SQL queries.
  • Ignoring API error responses.
  • Using an incorrect API URL.

28. POST in a Student Management App

In a React Native student management application, POST can be used for several operations.

  • Student registration
  • User registration
  • Student login
  • Add student
  • Submit leave application
  • Submit contact form

Each operation can have its own API endpoint.

29. POST Request Flow in Mobile Apps


React Native Form
       ↓
Collect User Data
       ↓
Validate Basic Input
       ↓
POST Request
       ↓
PHP REST API
       ↓
Server Validation
       ↓
MySQL INSERT
       ↓
JSON Response
       ↓
React Native
       ↓
Show Success/Error

30. Complete POST Concept

POST is one of the most important HTTP methods for creating data in REST APIs.


POST /api/students

The mobile application sends JSON data, the PHP API receives and validates it, the data can be stored in MySQL, and the API returns a JSON response.


React Native
      ↓
POST Request
      ↓
PHP REST API
      ↓
Validate JSON
      ↓
MySQL INSERT
      ↓
JSON Response
      ↓
React Native

📌 Key Points

  • POST is commonly used to create resources.
  • POST data is commonly sent in the request body.
  • JSON is commonly used as the request body format.
  • Content-Type should be set correctly for JSON requests.
  • React Native can send POST requests using Fetch or Axios.
  • JSON.stringify() can convert JavaScript objects into JSON strings.
  • PHP can read JSON using php://input.
  • PHP can validate POST data before storing it.
  • PDO prepared statements should be used for MySQL operations.
  • HTTP 201 Created is commonly used after successful resource creation.
  • Postman can be used to test POST APIs.
  • POST is commonly used for registration and other form submissions.
  • Server-side validation is important for API security and data quality.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to create a new resource in a REST API?