Skip to content

How To Pass JSON Data In POST Request

In API development and testing, HTTP methods like Post, Put and Patch are used to send JSON/XML objects to the server for data exchange and submission. In this guide, we will explore multiple ways using which we can pass JSON data in Post request.

How to Pass JSON Data In POST Request

What is Payload in API

Payload is the information or data that is exchanged between the client and the server while hitting the API. The information that is sent from the client in the form of a request is known as request payload or request body and the information provided by the server in response is referred to as server payload.

The payload can be either in the form of a JSON payload or an XML payload. In Rest API, the payload is sent with different methods like post, put, patch etc.

What is JSON?

JSON or JavaScript Object Notation is a lightweight, human-readable data interchange format. JSON represents data in key-value pairs and supports various data types like Arrays, Objects, and Strings making it versatile for transmitting complex information.

How to pass JSON payload in Rest API?

There are several ways to pass JSON payload in Rest API. I will discuss them here one by one. Before that, it is important to know that we must specify the content-type header as ‘application/json’ while sending the JSON data to the server. This will inform the server that the client is sending JSON data in the body of the HTTP request.

Refer below the mentioned ways to send JSON payload in Post request:

  1. Send JSON Payload as a string.
  2. Use external JSON file as payload.
  3. Use hashMap as Payload.
  4. Send POJO class as Payload.

. Open IDE, create a new java-maven project and add rest assured dependency in the pom.xml.

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
</dependency>

a) How to send JSON payload as a string

This is the simplest way to pass the request body to the post/put/patch request. To send the data to the server enclose the JSON payload in String.

Sample JSON Payload

{
  "Id": 1912,
  "Quantity": 5,
  "Price": 20.00
}

baseURL=https://favqs.com

Open Project, create a new class in the project directory and add the below code.

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
public class StringPostRequest {

    public static void main(String[] args) {
       
     String url = "https://favqs.com";

        // JSON payload to send
        String payload = "{\n" +
                "    \"Id\": \"1912\",\n" +
                "    \"Quantity\": 5,\n" +
                "    \"Price\": \"20\"\n" +
                "}";

        // Send the POST request
        Response response = given()
                .contentType(ContentType.JSON)
                .body(payload)
                .post(url);

        // Check the response
       Assert.assertEquals(response.getStatusCode(),HttpStatus.SC_OK);
    }
}

The given() method is used to set up the request. It specifies the Content-Type as JSON, sets the request body to the String JSON payload, and sends a POST request to the specified URL. The response is captured in the response variable and the response code is validated using assertion.

b) How to send JSON file as Payload

Another approach is to save JSON as a file and then pass this file as a payload.

1)Create a new file in the project and name it sample.json.

2)Add sample JSON to this file and save it.

3)Create a new class and name it “FilePayloadTest”.

4)Provide the path of the JSON file in the body() method.

import static io.restassured.RestAssured.given;

public class FilePayloadTest {

    public static void main(String[] args) {
      
        String url = "https://api.example.com/endpoint";

        // JSON file path
        String filePath = "/path/to/json/file.json";

        // Create a File object from the JSON file path
        File jsonFile = new File(filePath);

        // Send the POST request with the JSON file
        Response response = given()
                .contentType(ContentType.JSON)
                .body(jsonFile)
                .post(url);
        // Assert the response code
        Assert.assertEquals(response.getStatusCode(),HttpStatus.SC_OK);
      }
}

c) How to send request payload using HashMap

Hashmap is a data structure in Java that stores data as a key-value pair. In HashMap, each key must be unique, however, the value can be duplicated. Refer to the sample JSON data.

Sample JSON

{
    "username" : "admin",
    "password" : "password",
    "email" : "aqh@gmail.com",
    "age" : "30"
}

To send the JSON payload as HashMap, first, we need to import the HashMap package and then add the data in the HashMap object. Pass this object in the body() method.

Create a new class “HashmapPayloadExample” put the below code and execute it.

import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;

public class HashmapPayloadExample {

    public static void main(String[] args) {
       
        String url = "https://favqs.com";

        // Create a HashMap for JSON data
        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("username", "admin");
        jsonData.put("age", 30);
        jsonData.put("email", "aqh@gmail.com");
        jsonData.put("password", "password");

        // Send the POST request with JSON data as HashMap
        Response response = given()
                .contentType(ContentType.JSON)
                .body(jsonData)
                .post(url);

        // Check the response
      Assert.assertEquals(response.getStatusCode(),HttpStatus.SC_OK);
    }
}

A hashmap named jsonData is created to represent the JSON data. It includes key-value pairs for “username,” “age,” “email,” and “password.” This hashmap is passed in body() and the response is saved and validated with the assertion.

d) How to send JSON Payload as a POJO object

We can send the payload as a POJO (Plain old Java object) object. POJO classes are used for serialization and deserialization purposes.

1) Create a new class “UserPOJO” and add the getter and setter methods.

public class UserPOJO {
    private String username;
    private String password;
    private String email;
    private int age;

    public UserPOJO() {
         
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String name) {
        this.username = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public int getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    public int getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

These getter and setter methods maintain encapsulation by controlling the access and modification of Java Class fields.

2) Create a new Java class “TestPOJOPayload”. Create an instance of the “UserPOJO” class and set the properties using getter and setter in the “TestPOJOPayload” class. Use this object to create a payload.

UserPOJO userPayload = new UserPOJO();
userPayload.setUsername("AutomationQaHub");
userPayload.setEmail("AutomationQaHub@gmail.com");
userPayload.setAge("25");
userPayload.setPassword("AQH");

3) Call the body() method in Rest Assured and pass the “user payload” object as the parameter.

4) Call the post method and verify the response.

import static io.restassured.RestAssured.given;

public class TestPOJOPayload {

    public static void main(String[] args) {
        
        String url = "https://favqs.com";

        // Create a POJO object for payload
     UserPOJO userPayload = new UserPOJO();
     userPayload.setUsername("AutomationQaHub");
     userPayload.setEmail("AutomationQaHub@gmail.com");
     userPayload.setAge("25");
     userPayload.setPassword("AQH");

        // Send the POST request with POJO payload
        Response response = given()
                .contentType(ContentType.JSON)
                .body(userPayload)
                .post(url);

        // Check the response
        Assert.assertEquals(response.getStatusCode(),HttpStatus.SC_OK);
      
    }
}

The use of POJOs adds a level of abstraction and readability to the code by modelling the structure of the JSON payload as a Java object.

Now we have a solid understanding of sending JSON payloads in the POST/PUT/PATCH requests. By following the approaches as mentioned above we got complete knowledge of how to submit a request to Rest API.

Visit here to understand how to pass data from one API to another API.