Search code examples
javarestpostrest-assuredrest-assured-jsonpath

HTTP POST Request using Rest Assured (Example)


Below POST Method can be used to run the HTTP POST request in Rest Assured using Java

better to go with GSON dependency

{
    RestAssured.baseURI = API_URL;

    RequestSpecification request = RestAssured.given();

    request.header("Key1", "Value1");
    request.header("Key2", ""+Value2+""); //If value is getting capture from other variable

    JSONObject requestParams = new JSONObject();
    requestParams.put("Payload Key1", "Payload Value1"); 
    requestParams.put("Payload Key2", "Payload Value2");

    request.body(requestParams.toString());
    Response response = request.post(""); //last word of URL
    int StatusCode = response.getStatusCode(); //Get Status Code
    System.out.println("Status code : " + StatusCode);       
    System.out.println("Response body: " + response.body().asString()); //Get Response Body
}

Can use this code for POST Request in Rest Assured - Java


Solution

  • If you are doing API testing using Rest Assured. You have to specify the contentType to "application/json" and in post method you need to pass the endpoint.