Lesson 26 of 158 – JSON Request Body
26%

JSON Request Body

A JSON Request Body is JSON data sent from a client application to a REST API server inside the HTTP request body. It is one of the most common ways for React Native applications to send structured data to a backend API.

For example, when a student registers in a mobile application, the application can send the student's name, email, mobile number, and course as JSON to a PHP REST API.

Note: When sending JSON in an HTTP request, the client should normally specify Content-Type: application/json so that the server knows how to interpret the request body.

1. What is a JSON Request Body?

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


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

The server can read this data and process it.

2. Why Use JSON in a Request Body?

JSON provides a simple and organized way to send multiple related values in one request.


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

The server can easily read each property from the JSON object.

3. JSON Request Body Structure

A basic JSON request body contains an object with key-value pairs.


{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

Each property is separated using a comma.

4. JSON Request Body with POST

POST requests commonly send JSON data in the request body when creating a new resource.


POST /api/students

Content-Type: application/json

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

5. JSON Request Body with PUT

A PUT request can send a complete updated representation of a resource.


PUT /api/students/25

Content-Type: application/json

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

6. JSON Request Body with PATCH

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


PATCH /api/students/25

Content-Type: application/json

{
    "course": "React Native"
}

The API can update only the specified field.

7. Content-Type application/json

The Content-Type request header tells the server what type of data is being sent.


Content-Type: application/json

This is the standard media type used when sending JSON data.

8. JSON Request Body with Fetch

React Native can send JSON 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",
            course: "React Native"
        })
    }
);

const data = await response.json();

console.log(data);

9. Why JSON.stringify() is Required

Fetch expects the request body to be sent as a suitable body value. When sending a JavaScript object as JSON, JSON.stringify() is used to convert the object into a JSON string.


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

const jsonBody = JSON.stringify(student);

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

10. JSON Request Body with Axios

Axios can send a JavaScript object 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 and JSON communication according to the request configuration.

11. JSON Request Body in Postman

Postman can be used to manually send a JSON request body to an API.

  1. Select POST, PUT, or PATCH.
  2. Enter the API URL.
  3. Open the Body tab.
  4. Select raw.
  5. Select JSON.
  6. Enter the JSON data.
  7. Click Send.

12. Student Registration JSON

A student registration API can receive data such as:


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

The API can validate these values before creating the student record.

13. Login JSON Request

A login API can receive email and password as JSON.


POST /api/login

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

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

14. PHP Reading JSON Request Body

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


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

echo $input;

If the request contains JSON, the variable can contain the JSON text sent by the client.

15. PHP json_decode()

After reading the JSON body, PHP can convert it into a PHP value using json_decode().


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

$data = json_decode(
    $input,
    true
);

Using true makes the JSON object available as an associative array.

16. Reading JSON Properties in PHP

After decoding the JSON, individual properties can be accessed.


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

echo $name;
echo $email;
echo $course;

17. Validate JSON Before Processing

The server should verify that valid JSON was received before using the decoded data.


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

$data = json_decode(
    $input,
    true
);

if (!is_array($data)) {

    http_response_code(400);

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

    exit;
}

18. Validate Required Fields

After decoding the JSON, required fields should be checked.


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

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

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

    http_response_code(422);

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

    exit;
}

19. JSON Request Body and MySQL

After validation, the decoded JSON values can be stored in MySQL.


$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 for database operations.

20. Returning a JSON Response

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


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

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

21. JSON Request Body with Nested Objects

JSON request bodies can contain nested objects.


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

The API can access nested values after decoding the JSON.


$city = $data['address']['city'] ?? '';

22. JSON Request Body with Arrays

A JSON request body can also contain arrays.


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

PHP can access the array after decoding the JSON.


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

23. JSON Request Body and TypeScript

TypeScript can define the structure of the JSON data that the application sends.


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

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

This makes the expected request structure easier to understand and helps catch type-related mistakes during development.

24. Sending TypeScript Data with Fetch


const student: StudentRequest = {
    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();

25. JSON Request Body and Authentication

Some APIs require authentication information in headers while the request body contains the actual data.


POST /api/students

Authorization: Bearer YOUR_TOKEN
Content-Type: application/json

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

The authentication header and JSON request body have different purposes.

26. Common JSON Request Body Errors

  • Invalid JSON syntax.
  • Missing double quotes around string values.
  • Missing commas between properties.
  • Incorrect property names.
  • Missing required fields.
  • Incorrect Content-Type.
  • Forgetting JSON.stringify() with Fetch.
  • Not validating JSON on the server.
  • Not handling empty request bodies.
  • Using request values directly in unsafe SQL queries.

27. Testing JSON Request Body

Postman is useful for testing JSON request bodies before connecting a React Native application.

Example:


POST
https://example.com/api/students

Content-Type:
application/json

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

If the API works correctly in Postman, the same request structure can then be implemented in the mobile application.

28. Complete JSON Request Flow


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

29. Complete JSON Request Example

React Native:


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 result = await response.json();

console.log(result);

PHP:


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

$data = json_decode(
    $input,
    true
);

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

30. Complete JSON Request Body Concept

A JSON request body provides a standard way for a React Native application to send structured information to a REST API.


POST /api/students

Content-Type: application/json

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

The PHP REST API reads the request body, decodes the JSON, validates the submitted values, performs the required database operation, and returns a JSON response to the mobile application.

This request-body pattern will be used repeatedly in registration, login, student management, profile updates, and other REST API operations.

📌 Key Points

  • A JSON request body contains JSON data sent to the server.
  • POST commonly uses JSON request bodies to create resources.
  • PUT can send complete updated resource data.
  • PATCH can send partial resource data.
  • Content-Type: application/json identifies JSON data.
  • Fetch can send JSON using JSON.stringify().
  • Axios can send JavaScript objects as request data.
  • Postman can be used to test JSON request bodies.
  • PHP can read the raw body using php://input.
  • json_decode() converts JSON text into a PHP value.
  • Request data should be validated before database operations.
  • Prepared statements should be used for SQL operations.
  • JSON bodies can contain objects and arrays.
  • TypeScript interfaces can describe request data structures.
  • JSON request bodies are widely used in React Native REST API applications.

🧠 Quick Quiz

Question: Which HTTP header is commonly used when sending JSON in a request body?