Search code examples
restrest-assuredrest-assured-jsonpath

Rest Assured: Why do I get IllegalStateException exception?


I am in the process of studying Rest-Assured framework.

I am using http://ziptasticapi.com free API for my drills.

When I call:

final static String BASE_URI = "http://ziptasticapi.com/";

final static String ADAK_ZIP_CODE = "99546"; //{"country":"US","state":"AK","city":"ADAK"}
final static String ATKA_ZIP_CODE = "99547";

public static final String GET_METHOD = "GET";
    RestAssured.baseURI = BASE_URI;

    String responseString = when().get(ADAK_ZIP_CODE).then()
            .statusCode(200)
            .and()
            .extract()
            .asString();

    System.out.println(responseString);

I get the following string:

{"country":"US","state":"AK","city":"ADAK"}

as responseString value.

When I am trying:

 RestAssured.baseURI = BASE_URI;      

 ZipData zipdata = when().get(ADAK_ZIP_CODE).then()
            .statusCode(200)
            .and()
            .extract()
            .as(ZipData.class);

public class ZipData {

    public String country;
    public String state;
    public String city;

}

I crash on :

java.lang.IllegalStateException: Cannot parse object because no supported Content-Type was specified in response. Content-Type was 'text/html;charset=UTF-8'.

Why is that? Could it be the rest returns an Html and not Json? How do I handle this?

Thanks!


Solution

  • First of all, keep in mind that REST Assured is a HTTP client primarily designed for testing HTTP APIs. So let me highlight that you shouldn't use REST Assured for anything other than testing.


    Looks like the endpoint you are attempting to consume is returning a JSON document in the response payload, but the value of the Content-Type header is text/html;charset=UTF-8, so REST Assured cannot parse the response as a JSON document and convert it to an instance of ZipData. That's not what you expect from a sound HTTP API.

    You could work around it and write a filter to override the Content-Type header, as show below:

    public class OverrideContentTypeFilter implements Filter {
    
        @Override
        public Response filter(FilterableRequestSpecification requestSpec,
                               FilterableResponseSpecification responseSpec,
                               FilterContext ctx) {
    
            Response next = ctx.next(requestSpec, responseSpec);
            return new ResponseBuilder().clone(next).setContentType(ContentType.JSON).build();
        }
    }
    

    Then use it as follows:

    ZipData zipdata =
            given()
                .filter(new OverrideContentTypeFilter())
            .when()
                .get(uri)
            .then()
                .statusCode(200)
                .extract()
                .as(ZipData.class);