Show List
Testing POST Request
Below is an example Java program that demonstrates how to use Rest Assured to test a POST request to a REST API endpoint:
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
public class ApiPostTest {
public static void main(String[] args) {
// Set base URI of the REST API
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
// Define POST request body
String requestBody = "{"
+ "\"title\": \"Test Title\","
+ "\"body\": \"Test Body\","
+ "\"userId\": 1"
+ "}";
// Send POST request to /posts endpoint
Response response = RestAssured.given()
.contentType(ContentType.JSON)
.body(requestBody)
.post("/posts");
// Get and print the response body
String responseBody = response.getBody().asString();
System.out.println("Response Body:");
System.out.println(responseBody);
// Get and print the status code
int statusCode = response.getStatusCode();
System.out.println("\nStatus Code: " + statusCode);
}
}
In this example:
- We set the base URI of the REST API using
RestAssured.baseURI
. - We define the JSON request body for the POST request.
- We send a POST request to the
/posts
endpoint usingRestAssured.given().contentType(ContentType.JSON).body(requestBody).post("/posts")
. - We retrieve the response body and status code from the response object and print them out.
You can modify the base URI, request body, and endpoint according to the API you want to test. Make sure you have Rest Assured and its dependencies added to your project's classpath. Additionally, you may need to handle exceptions such as IOException
or NullPointerException
depending on your specific requirements and error handling strategy.
Leave a Comment