To test a POST API using Rest Assured with a JSONObject
in Java, follow these steps:
Step-by-Step Implementation
1. Add Rest Assured Dependency
<dependencies> <!-- Rest Assured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency> <!-- JSON Library --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20230618</version> </dependency> </dependencies>
API to be tested:
POST https://reqres.in/api/users
Sample request body:
{ "name": "Himanshu", "job": "QA Engineer" }
Expected response (201 Created):
{ "name": "Himanshu", "job": "QA Engineer", "id": "123", "createdAt": "2025-07-28T..." }
3. Java Code to Test POST API using JSONObject
import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.http.ContentType; import org.json.JSONObject; public class PostAPITest { public static void main(String[] args) { // Step 1: Set Base URI RestAssured.baseURI = "https://reqres.in/api"; // Step 2: Create Request Payload using JSONObject JSONObject requestBody = new JSONObject(); requestBody.put("name", "Himanshu"); requestBody.put("job", "QA Engineer"); // Step 3: Make POST Request Response response = RestAssured .given() .contentType(ContentType.JSON) .body(requestBody.toString()) .log().all() .when() .post("/users") .then() .log().all() .statusCode(201) .extract().response(); // Step 4: Print Response Fields System.out.println("ID: " + response.jsonPath().getString("id")); System.out.println("Created At: " + response.jsonPath().getString("createdAt")); } }
Code Explanation:
Line | Purpose |
---|---|
RestAssured.baseURI | Sets the base URL. |
JSONObject | Builds the JSON body using key-value pairs. |
given().contentType().body() | Prepares the request with headers and body. |
post("/users") | Sends POST request to the endpoint. |
statusCode(201) | Verifies the response status. |
response.jsonPath() | Extracts values from JSON response. |
Sample Output:
Request method: POST Request URI: https://reqres.in/api/users Request body: { "name": "Himanshu", "job": "QA Engineer" } Response Status Code: 201 Response body: { "name": "Himanshu", "job": "QA Engineer", "id": "867", "createdAt": "2025-07-28T14:30:55.098Z" }
No comments:
Post a Comment