Introduction
In our previous post, we explored Path Parameters in REST Assured, learning how to handle dynamic URL segments. Now, we’ll dive into Request Body, focusing on sending data in JSON and XML formats for API requests like POST and PUT. This guide is tailored for beginners and experienced developers, providing clear explanations and practical examples to help you master sending request bodies in REST Assured.
Key Point: The request body is used to send data to an API, such as creating or updating resources, and REST Assured makes it easy to work with JSON and XML payloads.
What is a Request Body?
A Request Body is the data sent to an API server in the body of an HTTP request, typically for POST, PUT, or PATCH methods. It contains structured data in formats like JSON or XML, defining the resource to create or update. For example, when creating a new user, you might send a JSON payload with the user’s name and email.
REST Assured simplifies sending request bodies by allowing you to define them as strings, Java objects, or files, and it automatically handles content type headers.
Sending a JSON Request Body
JSON is the most common format for API request bodies due to its simplicity and widespread use. Let’s explore how to send a JSON request body using REST Assured.
Option 1: Using a JSON String
The simplest way to send a JSON request body is by defining it as a string in the body()
method.
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class JsonBodyTest {
@Test
public void testJsonBody() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
String jsonBody = "{\"title\": \"Test Post\", \"body\": \"This is a test post\", \"userId\": 1}";
given()
.contentType("application/json")
.body(jsonBody)
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("Test Post"))
.body("id", notNullValue());
}
}
Explanation:
contentType("application/json")
: Sets the request’s Content-Type header to indicate a JSON payload.body(jsonBody)
: Sends the JSON string as the request body.post("/posts")
: Sends a POST request to create a new post.then()
: Validates the response, checking the status code (201 for created) and response fields.
Important: Always set theContent-Type
header to match the request body format (application/json
for JSON) to avoid server errors.
Option 2: Using a Java Object
For cleaner code, you can use a Java object as the request body. REST Assured automatically serializes the object to JSON using libraries like Jackson or Gson (if included in your project).
First, add the Jackson dependency to your pom.xml
to enable serialization:
com.fasterxml.jackson.core
jackson-databind
2.15.2
test
Now, create a Java class for the request body and use it in a test:
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
// Java class for the request body
class Post {
private String title;
private String body;
private int userId;
public Post(String title, String body, int userId) {
this.title = title;
this.body = body;
this.userId = userId;
}
// Getters and setters
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getBody() { return body; }
public void setBody(String body) { this.body = body; }
public int getUserId() { return userId; }
public void setUserId(int userId) { this.userId = userId; }
}
public class JsonObjectBodyTest {
@Test
public void testJsonObjectBody() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
Post post = new Post("Test Post", "This is a test post", 1);
given()
.contentType("application/json")
.body(post)
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("Test Post"))
.body("userId", equalTo(1));
}
}
Explanation:
Post
: A Java class representing the JSON structure.body(post)
: REST Assured serializes thePost
object to JSON automatically.- This approach is cleaner and less error-prone than writing JSON strings manually.
Sending an XML Request Body
Some APIs require XML request bodies. REST Assured supports XML just as easily as JSON, using a similar approach.
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class XmlBodyTest {
@Test
public void testXmlBody() {
RestAssured.baseURI = "https://api.example.com"; // Replace with an XML-based API
String xmlBody = "John Doe john@example.com ";
given()
.contentType("application/xml")
.body(xmlBody)
.when()
.post("/users")
.then()
.statusCode(201)
.body("user.name", equalTo("John Doe"));
}
}
Explanation:
contentType("application/xml")
: Sets the Content-Type header for XML.body(xmlBody)
: Sends the XML string as the request body.- Note: This example uses a placeholder API. For practice, find an XML-based public API, as
jsonplaceholder.typicode.com
primarily uses JSON.
Pro Tip: For XML-based APIs, ensure the XML is well-formed. Use tools like XML validators to check your payload before sending it.
Using Request Specification for Request Bodies
To reuse common request body settings, include them in a Request Specification.
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class RequestSpecBodyTest {
private static RequestSpecification requestSpec;
@BeforeAll
public static void setup() {
requestSpec = new RequestSpecBuilder()
.setBaseUri("https://jsonplaceholder.typicode.com")
.setContentType("application/json")
.build();
}
@Test
public void testPostWithSpec() {
String jsonBody = "{\"title\": \"Test Post\", \"body\": \"This is a test\", \"userId\": 1}";
given()
.spec(requestSpec)
.body(jsonBody)
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("Test Post"));
}
}
Explanation:
setContentType("application/json")
: Sets the default content type in the specification.spec(requestSpec)
: Applies the specification, while the test adds the specific JSON body.
Verify Setup with pom.xml
Ensure your pom.xml
includes dependencies for REST Assured, JUnit, and Jackson (for JSON serialization):
io.rest-assured
rest-assured
5.4.0
test
org.junit.jupiter
junit-jupiter
5.10.2
test
org.hamcrest
hamcrest
2.2
test
com.fasterxml.jackson.core
jackson-databind
2.15.2
test
Run the tests using mvn test
or your IDE’s test runner to confirm the setup.
Tips for Beginners
- Validate Payloads: Use JSON or XML validators to ensure your request body is correctly formatted.
- Use Java Objects: Prefer Java objects over strings for JSON to reduce errors and improve readability.
- Check API Docs: Verify the expected request body structure in the API documentation.
- Enable Logging: Use
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails()
to debug payload issues.
Troubleshooting Tip: If the API returns a 400 Bad Request error, check the request body format and Content-Type
header. Ensure they match the API’s requirements.
What’s Next?
In the next post, we’ll cover Headers and Cookies, exploring how to manage HTTP headers and cookies in REST Assured for more robust API testing. Stay tuned for more hands-on examples!