Cleicy Guião
Cleicy Guião

Reputation: 111

How to request a POST API send token and body values using Rest-Assured?

I'm trying to create an Test Automation for a POST API using Rest-Assured and Java. This POST API have a body as Application/JSON, like this:

{
    "customer":{
        "email": "[email protected]"
    },
    "password":"Teste@12"
}

To make this request I'm using the follow code, but it's returning Status code "400", but I'm sending the same information on Postman and it's returning "200":

@And("envio as informacoes da chamada: (.*), (.*), (.*), (.*) e (.*)")
        public void enviarDados (String srtEmail, String srtSenha, String srtAmbiente, String srtAPI, String srtToken) {
HashMap<String,String> postContent = new HashMap<String,String>();
            postContent.put("email", srtEmail);
            postContent.put("password", srtSenha);
            //System.out.println("{\"customer\":" +postContent+ "}");
            given().contentType(ContentType.JSON).header("Authorization", "Bearer"+srtToken).header("Content-Type", "application/json").
            //with().body(postContent).
            with().body("{\"customer\":" +postContent+ "}").
            when().post(srtAmbiente+srtAPI).
            then().statusCode(200); 
}

The "400" response is:

{
"status": 400,
"message": "Malformed request",
"additional_error": ""
}

Upvotes: 0

Views: 1417

Answers (2)

Vibha Singh
Vibha Singh

Reputation: 69

You can try below approach also. For this, you need to add org.json dependency to the pom.xml.:

 @Test
    public void test() throws JSONException {
        JSONObject obj1 = new JSONObject();
        obj1.put("email","[email protected]");

        JSONObject obj2 = new JSONObject();
        obj2.put("customer",obj1);
        obj2.put("password","Teste@12");

       System.out.println("Request :" + obj2);

        given()
             .contentType(ContentType.JSON).header("Authorization", "Bearer"+srtToken)
              .header("Content-Type", "application/json")
              .body(obj2)
       .when()
              .post(srtAmbiente+srtAPI)
       .then()
              .statusCode(200);

    }

Upvotes: 0

bhusak
bhusak

Reputation: 1390

You are sending an incorrect body with POST.

//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")

As a result your payload will look this way:

{"customer":{password=password, [email protected]}}

which is not a valid JSON. Try this:

Map<String, String> emailContent = new HashMap<>();
emailContent.put("email", "[email protected]");
Map<String, Object> postContent = new HashMap<>();
postContent.put("customer", emailContent);
postContent.put("password", "password");
given().contentType(ContentType.JSON)
    .header("Authorization", "Bearer "+srtToken)
    .with().body(postContent)
    .when().post(srtAmbiente+srtAPI)
    .then().statusCode(200); 

Upvotes: 2

Related Questions