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": "teste@mailinator.com"
},
"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": ""
}
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, customer=example@example.com}}
which is not a valid JSON. Try this:
Map<String, String> emailContent = new HashMap<>();
emailContent.put("email", "example@example.com");
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);