Lesson 25 of 158 – Request Body
25%

Request Body

The request body is the data sent by a client application to a server as part of an HTTP request. In REST APIs, the request body is commonly used when creating or updating resources.

For a React Native application, the request body can contain information such as a student's name, email, course, address, or other form data. The PHP REST API receives this information, validates it, and can store it in a MySQL database.

Note: GET requests commonly retrieve data, while request bodies are commonly used with POST, PUT, and PATCH requests to send data to the server.

1. What is a Request Body?

A request body contains data sent from the client to the server.

Example:


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

This data can be sent to a REST API when creating or updating a resource.

2. Why is the Request Body Used?

The request body allows the client to send structured information to the server.

For example, a registration request may need:

  • Name
  • Email
  • Password
  • Mobile number

These values can be placed inside the request body.

3. Request Body and HTTP Request

An HTTP request can contain a method, URL, headers, and body.


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

{
    "name": "Rahul",
    "course": "React Native"
}

The JSON object after the headers is the request body.

4. Request Body with POST

POST requests commonly use a request body to send data for creating a new resource.


POST /api/students

Request body:


{
    "name": "Rahul",
    "course": "React Native"
}

5. Request Body with PUT

PUT requests can use a request body to send updated information for a resource.


PUT /api/students/25

Request body:


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

6. Request Body with PATCH

PATCH can send only the fields that need to be changed.


PATCH /api/students/25

Request body:


{
    "course": "React Native"
}

Only the specified property may need to be updated.

7. Request Body and GET

GET requests are generally used to retrieve data. Instead of relying on a request body for filtering or searching, APIs commonly use query parameters.


GET /api/students?course=react

The query parameter provides the filtering information.

8. JSON Request Body

JSON is one of the most common formats used for REST API request bodies.


{
    "name": "Rahul",
    "age": 22,
    "course": "React Native"
}

The server can read these values and process them.

9. Content-Type for JSON Body

When JSON is sent in a request body, the request commonly includes the following header:


Content-Type: application/json

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

10. Request Body with Fetch

React Native can send a JSON request body using Fetch.


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

const data = await response.json();

console.log(data);

11. Why JSON.stringify() is Used

JavaScript objects need to be converted into JSON text before they are sent as a JSON request body.


const student = {
    name: "Rahul",
    course: "React Native"
};

const body = JSON.stringify(student);

The resulting JSON string can be assigned to the Fetch body property.

12. Request Body with Axios

Axios can send JavaScript objects as request data.


const response = await axios.post(
    "https://example.com/api/students",
    {
        name: "Rahul",
        course: "React Native"
    }
);

console.log(response.data);

Axios handles the request data according to the request configuration and content type.

13. Request Body with Headers

Headers provide information about the request. When sending JSON, the Content-Type header is commonly used.


fetch(url, {
    method: "POST",

    headers: {
        "Content-Type": "application/json"
    },

    body: JSON.stringify({
        name: "Rahul"
    })
});

14. Request Body in Postman

Postman can be used to manually test request bodies.

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

15. Student Registration Request Body

A registration API can receive student information through the request body.


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

The API can validate these values before storing them.

16. PHP Reading a JSON Request Body

PHP can read the raw request body using php://input.


$input = file_get_contents(
    "php://input"
);

The returned value can then be decoded if the request contains JSON.

17. PHP json_decode() for Request Body

After reading the raw request body, PHP can decode the JSON data.


$input = file_get_contents(
    "php://input"
);

$data = json_decode(
    $input,
    true
);

$name = $data['name'] ?? '';

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

18. Validating Request Body Data

The API should validate data received in the request body before using it.


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

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

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

    // Return validation error

}

Validation helps ensure that required information is present.

19. Request Body and MySQL

After validation, PHP can use request body values in a database operation.


$sql = "INSERT INTO students
        (name, email, course)
        VALUES
        (:name, :email, :course)";

$stmt = $pdo->prepare($sql);

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

Prepared statements should be used when inserting request data into the database.

20. Request Body and API Response

After processing the request body, the server can return a JSON response.


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

The React Native application can read this response and update the user interface.

21. Nested Objects in Request Body

A request body can contain nested JSON objects.


{
    "name": "Rahul",
    "address": {
        "city": "Patna",
        "state": "Bihar"
    }
}

The server can read the nested values after decoding the JSON.

22. Arrays in Request Body

A request body can also contain arrays.


{
    "name": "Rahul",
    "skills": [
        "JavaScript",
        "TypeScript",
        "React Native"
    ]
}

The API can process the array according to its requirements.

23. Request Body for Login

A login API commonly receives credentials through the request body.


POST /api/login

Request body:


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

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

24. Request Body for Updating a Student

A mobile application can send updated information using PUT or PATCH.


PATCH /api/students/25

Request body:


{
    "mobile": "9876543210",
    "course": "TypeScript"
}

The API can update only the required fields.

25. Request Body and Content-Length

HTTP requests can include a Content-Length header that indicates the size of the request body in bytes.


Content-Type: application/json
Content-Length: 72

Clients and servers generally handle this automatically, so application developers normally do not need to manually calculate it.

26. Common Request Body Mistakes

  • Sending invalid JSON.
  • Forgetting the Content-Type header when required.
  • Forgetting JSON.stringify() with Fetch.
  • Using incorrect property names.
  • Sending missing required fields.
  • Not validating received values.
  • Using request data directly in unsafe SQL queries.
  • Not handling invalid or empty request bodies.

27. Request Body and TypeScript

TypeScript can define the expected structure of a request body.


interface StudentRequest {
    name: string;
    email: string;
    course: string;
}

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

This helps developers understand which fields should be sent to the API.

28. Complete Request Body Flow


React Native Form
       ↓
JavaScript Object
       ↓
JSON.stringify()
       ↓
HTTP Request Body
       ↓
PHP REST API
       ↓
php://input
       ↓
json_decode()
       ↓
Validation
       ↓
MySQL Database
       ↓
JSON Response
       ↓
React Native

This is a common flow when a mobile application sends form data to a PHP REST API.

29. Complete Request Body Example

React Native request:


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

const response = await fetch(
    "https://example.com/api/students",
    {
        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify(student)
    }
);

const data = await response.json();

console.log(data);

The PHP API receives the JSON body, validates it, stores the required data, and returns a JSON response.

30. Complete Request Body Concept

The request body is one of the most important parts of REST API communication when a client needs to send data to the server.


POST /api/students

Content-Type: application/json

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

In a React Native application, form values can be converted into JSON and sent through Fetch or Axios. A PHP REST API can read the body, decode the JSON, validate the values, process the database operation, and return a JSON response.

📌 Key Points

  • A request body contains data sent from the client to the server.
  • POST commonly uses a request body to create resources.
  • PUT can use a request body to update resources.
  • PATCH can use a request body for partial updates.
  • JSON is commonly used as a REST API request body format.
  • The Content-Type header can identify JSON data.
  • Fetch can send a request body using the body property.
  • JSON.stringify() converts a JavaScript object into JSON text.
  • Axios can send request data directly.
  • Postman can be used to test request bodies.
  • PHP can read the raw request body using php://input.
  • PHP can convert JSON into an array using json_decode().
  • Request data should be validated before processing.
  • Prepared statements should be used for database operations.
  • TypeScript interfaces can describe the expected request body.

🧠 Quick Quiz

Question: Which HTTP request component is commonly used to send JSON data when creating a new resource?