When it comes to REST API testing, Rest Assured is one of the most widely used libraries in Java due to its simplicity and effectiveness. If you’re working with APIs that require POST requests, understanding how to send JSON payloads with Rest Assured is essential. In this post, we'll walk through testing a POST request using a JSON object with Rest Assured.
Why Use POST Requests?
POST requests are used to send data to the server to create a new resource. In RESTful services, this often involves sending a JSON payload to the server endpoint, which is then processed to store data, initiate a process, or perform other tasks. Testing POST requests ensures that your API handles data creation correctly and responds as expected.
What Is Rest Assured?
Rest Assured is a Java library that simplifies testing RESTful APIs. It provides a clean, fluent syntax for making HTTP requests and validating responses, making it ideal for automated testing of REST APIs.
Prerequisites
Before we dive into the code, ensure you have the following:
1. Java: Make sure Java is installed and set up in your system.
2. Maven: This example assumes you're using Maven to manage dependencies.
3. Rest Assured Library: Add Rest Assured to your project’s pom.xml
if it’s not already present.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
Steps to Test a POST Request with JSON Object
In this example, we’ll create a JSON payload in Java and use it in a POST request to test the endpoint.
Step 1: Set Up JSON Payload Data
You can create a JSON payload using various methods in Java. Here, we’ll create a HashMap
and convert it to JSON. Alternatively, you can use JSONObject
from the org.json library or create a JSON string directly.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
public class PostRequestTest {
@Test
public void testPostRequestWithJsonObject() {
// Create a JSON object using a HashMap
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("name", "John Doe");
requestBody.put("email", "john.doe@example.com");
requestBody.put("age", 30);
// Specify the base URI
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
// Send the POST request
Response response = RestAssured.given()
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.post("/users");
// Print response details
System.out.println("Response Status Code: " + response.getStatusCode());
System.out.println("Response Body: " + response.asString());
// Assertions to verify the response
response.then().statusCode(201);
response.then().assertThat().body("name", equalTo("John Doe"));
response.then().assertThat().body("email", equalTo("john.doe@example.com"));
response.then().assertThat().body("age", equalTo(30));
}
}
In this example:
- We created a JSON object using a
HashMap
and added key-value pairs forname
,email
, andage
. - We set the base URI to
https://jsonplaceholder.typicode.com
(a mock API for testing purposes). - We defined the endpoint
/users
, which accepts POST requests.
Step 2: Send the POST Request and Validate the Response
- Content Type: Set the content type to JSON using
ContentType.JSON
in the.contentType()
method. - Request Body: Add the JSON payload to the request using
.body(requestBody)
. - Execute POST: Send the request with
.post("/users")
.
Step 3: Verify the Response
After the request is sent, Rest Assured allows for response validation. Here’s what we checked:
- Status Code:
.statusCode(201)
verifies that the server responds with a201
status code, indicating a successful creation. - Body Content: Using
.body()
assertions, we check if the server response contains the correct data values forname
,email
, andage
.
Best Practices and Tips
- Use JSON Schema Validation: Instead of verifying individual fields, validate the entire JSON structure using JSON schema validation.
- Parameterized Tests: Use parameterized tests to test different payloads and responses with minimal code duplication.
- Reusable Functions: If you have multiple POST tests, create a helper method to send the request and verify the response, which reduces code repetition.