How to add Content Type to request in Rest Assured

HOME

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;

public class WithoutContentType_Demo {

    @Test
    public void test() {

        JSONObject data = new JSONObject();

        data.put("name", "William");
        data.put("job", "Manager");

        RestAssured
                .given()
                .body(data.toString())
                .log().all()

                .when()
                .post("https://reqres.in/api/users")

                .then()
                .assertThat().statusCode(201)
                .body("name", equalTo("William"))
                .body("job", equalTo("Manager"))
                .log().all();

    }
}

contentType(ContentType.JSON)

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;

public class WithContentType_Demo {

    @Test
    public void test() {

        JSONObject data = new JSONObject();

        data.put("name", "William");
        data.put("job", "Manager");

        RestAssured
                .given()
                .contentType(ContentType.JSON)
                .body(data.toString())
                .log().all()

                .when()
                .post("https://reqres.in/api/users")

                .then()
                .assertThat().statusCode(201)
                .body("name", equalTo("William"))
                .body("job", equalTo("Manager"))
                .log().all();

    }
}

.header("Content-Type","application/json;charset=utf-8")
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;

public class WithContentType_Demo {

    @Test
    public void test() {

        JSONObject data = new JSONObject();

        data.put("name", "William");
        data.put("job", "Manager");

        RestAssured
                .given()
                .header("Content-Type","application/json;charset=utf-8")
                .body(data.toString())
                .log().all()

                .when()
                .post("https://reqres.in/api/users")

                .then()
                .assertThat().statusCode(201)
                .body("name", equalTo("William"))
                .body("job", equalTo("Manager"))
                .log().all();

    }
}

Leave a comment