Answer
Automating POST Method in Rest Assured
POST requests are used to send data to the API server to create or update a resource. The data sent is stored in the request body of the HTTP request.
Method 1: POST with JSON Body from File
Java
@Test(description = "Automate POST method and validate response")
public void methodValidationPOST() throws IOException, ParseException {
FileInputStream file = new FileInputStream(
new File(System.getProperty("user.dir") + "\\TestData\\post.json")
);
Response resp = given()
.header("Content-Type", "application/json")
.body(IOUtils.toString(file, "UTF-8"))
.when()
.post("https://reqres.in/api/users");
assertEquals(resp.getStatusCode(), 201);
assertEquals(resp.path("job"), "tester");
}
Method 2: POST with Inline JSON String
Java
@Test
public void postWithInlineBody() {
String requestBody = "{ \"name\": \"John\", \"job\": \"QA Engineer\" }";
given()
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body("name", equalTo("John"))
.body("job", equalTo("QA Engineer"));
}
Method 3: POST with POJO (Object Serialization)
Java
// POJO class
public class User {
private String name;
private String job;
// getters/setters
}
@Test
public void postWithPOJO() {
User user = new User();
user.setName("Jane");
user.setJob("SDET");
given()
.contentType(ContentType.JSON)
.body(user) // serialized to JSON automatically
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
}
POST vs GET
| Feature | POST | GET |
|---|---|---|
| Purpose | Create resource | Retrieve resource |
| Body | Has request body | No body |
| Status on success | 201 Created | 200 OK |
| Idempotent | No | Yes |
