Skip to content
CodeKruPro

Send a POJO as the request body

Automation taskMediumJava onlyAsked in: Accenture, Capgemini

The other half of the POJO question (a POJO is a plain Java class that only holds data) is: "How do you build request bodies?" Passing an object to body() and letting REST Assured turn it into JSON is cleaner than writing JSON strings by hand.

Send POJO as Request Body

Send POJO as Request Body

Instead of constructing JSON strings manually, you can send a Java object (POJO) directly. REST Assured automatically serializes it to JSON:

User user = new User();
user.name = "Test";
given().contentType(ContentType.JSON).body(user).post("/users");

Define the class with public fields inside your Main class as static. Every public field is sent, so set all the fields the endpoint requires: /users answers 400 if name or email is missing, and a field you never set goes out as null (or 0 for an int).

Task: Create a User POJO and POST it.

Expected output:

Status: 201
Name: Test User
City: Mumbai