alex
alex

Reputation: 31

Send JSON body using Rest Assured, but server ignores it

I was confronted with difficulties when used RestAssered. My goal send POST request for creation user. How I do it (from documentation https://github.com/rest-assured/rest-assured/wiki/Usage):

Map<String, Object>  jsonAsMap = new HashMap<>();
    jsonAsMap.put("username", "John");
    jsonAsMap.put("email", "[email protected]");

    response = restAssured.given()
            .contentType(JSON)
            .header("Authorization", db.getAuthToken())
            .body(jsonAsMap)
            .when()
            .log().all()
            .post(apiCreateManager_POST);
    response.then().log().all();

Request:

Request method: POST
Request URI:    https://myapplication/api/v1/manager/managers
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXU....
                Accept=*/*
                Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "email": "[email protected]",
    "username": "John"
}

Response:

HTTP/1.1 422 Unprocessable Entity
Server: nginx/1.12.0
Date: Tue, 05 Mar 2019 10:52:54 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.1.20-1+ubuntu16.04.1+deb.sury.org+1
Cache-Control: private, must-revalidate
pragma: no-cache
expires: -1

{
    "errors": {
        "username": [
            "This value should not be null.",
            "This value should not be blank."
        ],
        "email": [
            "This value should not be blank."       
        ]
    }
}

Server did not see my JSON parameters. I checked server using Postman and everything was OK.

Upvotes: 1

Views: 362

Answers (1)

alex
alex

Reputation: 31

I found solution! The problem was in Content-Type=application/json; charset=UTF-8

You should avoid adding the charset to content-type header automatically:

RestAssured.config = RestAssured.config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));

And after that we have:

Content-Type=application/json

Upvotes: 2

Related Questions