REST Assured – Or how to easily test REST services in Java

Testing and validating REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured is a Java DSL (built on top of HTTP Builder) that brings the simplicity of these languages into the Java domain.

Example 1 – JSON

Assume that a GET request to http://localhost:8080/lotto returns JSON as:

REST assured can then help you to easily make the GET request and verify the response. E.g. if you want to verify that lottoId is equal to 5 you can do like this:

or perhaps you want to check that the winnerId’s are 23 and 54:

Note that equalTo and hasItems are standard Hamcrest matchers.

Example 2 – XML

XML can be verified in a similar way. Image that a POST request to http://localhost:8080/greetXML returns:

i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. You can easily perform and verify e.g. the firstName with REST assured:

You can also verify XML responses using X-Path. For example:

Authentication

REST assured also supports some authentication schemes, for example basic authentication:

Other supported schemes are OAuth, Digest and certificate authentication.

Conclusion

As you can see it can be really simple to test REST services in Java. REST Assured supports the POST, GET, PUT, DELETE and HEAD http methods and includes specifying and validating e.g. parameters, headers, cookies and body easily. Visit our homepage for more info and downloads.

This Post Has 36 Comments

  1. Interesting work. It seem really useful for testing REST services when the response data is not that complex/big. I actually had to create my own framework for simplify the creation of tests for a REST service. It was not nearly as fancy or user friendly in its design as this, but could handle more complex/big xml data responses. I would like to rewrite it some time though.

    How I handled the validation of response was simply to create a xml element class which you use to create an object representation of the expected response, It is then just a paramater to the assert method I wrote for testing REST.

    pseudo-code:
    //init xml data object
    XmlElement expect = new MyBigxmlResponse(…); //inherits from XmlElement (ugly, I know :)

    //do get and assert response
    assertRESTGet(contextUrl, resourceUrl, expect);

  2. Johan Sjöberg:

    Sorry for the late response. I understand that it can be awkward to verify large responses with REST Assured but there’s a first embryo implemented whose purpose is to accommodate it a bit more nicely. Right now it’s much the same syntax as normally but you can split the request and verification in multiple lines, e.g.

    RequestSpecification requestSpecification = given().contentType(ContentType.TEXT).with().parameters(“firstName”, “John”);

    ResponseSpecification responseSpecification = expect().contentType(ContentType.JSON).and().body(“greeting”, equalTo(“Greetings John Doe”));

    given(requestSpecification, responseSpecification).get(“/greet”);

    What I’d like to have is something more like this:

    RequestSpecification requestSpecification = new RequestSpecificationBuilder().setContentType(TEXT).setParameters(“..”);

    ResponseSpecification responseSpecification = new ResponseSpecificationBuilder().expectBody(“greeting”, containsString(“Greetings”)). .. ;

    given(requestSpecification, responseSpecification).get(“/greet”);

    The invocation to “get” should also return the response so you could simply pass the request specification if you like:

    Response resp = given(requestSpecification).get(“/greet”);

    Is this kind of what you’re lookinf for? You’re very welcome to help out if you like.

  3. I like your separation much better than mine when it comes to the method calls, a more declarative approach is better, in my opinion. The difference from what I have done is that my “ResponseSpecification” is locked to only work with xml and is very specialized for the scenarios it is used in, mostly because this is not a hobby project but work for a client, so that’s just the way it went :)

    So what I actually did was to make a object representation of a xml response, by implementing a XmlElement class that can have children, parents, attributes etc. everything that an Xml can have (almost). So for a test I build up the expected xml response using XmlElement to describe the response. My assertion method then goes through all elements in the expect object and calculates its xpath and verifies the response to have the same values in the response as in the expect object. This works well for large responses, but when implementing tests most of the work involves constructing these expect objects.

    Now to what I would like to do. I want to assert the following in an xml response:
    1. the xml should be valid
    2. validate against a xsd (either if it is given in the response or if we actually implement one for the test, without there existing one for the actual REST API)
    3. validate values in the response

    so what I have done is solve 1 and 2, but not exactly in the way I would have wanted. Is this an open source project? It would be nice to have a look, and if time presents itself maybe I can contribute :)

  4. sorry.. I should have been more attentive. I actually missed the homepage link in the post. Will have a look..

  5. Yes the project is open source. The latest version supports parsing XML and JSON responses very easily:

    // Example with JsonPath
    String json = get(“/lotto”).asString()
    List winnderIds = with(json).get(“lotto.winners.winnerId”);

    // Example with XmlPath
    String xml = post(“/shopping”).andReturn().body().asString()
    Node category = with(xml).get(“shopping.category[0]”);

    Check out the web-page for examples. I’ll definitely add support for validating against a DTD or XSD as well.

  6. Is there any way/plan to get REST-assured to work with JSONP services?

  7. Well it depends on what you mean. I suppose you mean that you want to do something like this:

    expect().body(“something.xyz”, equalTo(“x”)).when().get(“/jsonp&callback=y”);

    This will not work but it’s an excellent idea so I’ll add it as an issue. You can of course do something like e.g.:

    expect().body(containsString(“x”).when().get(“/jsonp&callback=y”);

    or

    String jsonp = get(“/jsonp&callback=y”).asString();

    to actually return the response. But it would be really cool to add better support for it. I’ll add it as an issue and I’ll see what I can do.

    Thanks for your feedback.

  8. That should be:

    expect().body(containsString(“x”)).when().get(“/jsonp&callback=y”);

  9. When I call a service with multiple parameters with the same name
    Ex: http://localhost:8080/list?listVal=1&listval=2.

    I get a response only for the last parameter.

    However when I try it on rest client. I get the complete Information.

  10. As it’s implemented today the second parameter will override the first one. I’ll add an issue for it.

  11. The new release (1.1.7) now supports multiple parameters.

  12. Is it possible to test file-upload with POST?

    I have a multipart form with a text-field and a file-upload-field which need to be send with a POST.

    Regards,
    Tim

  13. Hi Tim,

    Unfortunately multi-form uploads are not available yet (it’s not supported by http builder afaik). I’ll add an issue for it and I’ll see what can be done in the future.

    You can do how ever easily send small “files” as a byte-array using:

    given().body(myByteArray).when().post(..);

  14. Multipart form data uploads are now available since version 1.3

  15. Is it possible to have a mocked version of REST assured. Currently I need a server that is up on localhost

  16. Can REST-Assured be used to automation test REST APIs in a programmatical fashion so that the test scripts can be maintained without making changes to the scripts every time any aspect of the REST API is changed?. If so, what is the best programming language to use i.e Java.

  17. @peter: We make heavy use of automated REST Assured test written in Java. Use it in combination with surefire or failsafe to start the server before the test are being executed.

  18. hi,
    I need some explanation on limitation of RestAssured API.

    Scenario One : Accessing the Rest End Point Directly –
    resource pojos directly accessing hydra rest endpoints .
    REST assured works fine and provides results.

    Scenario Two: we have 2 servers
    chimera server and hydra server .
    the http request goes to chimera server which interacts with which in spring framework via controllers turn calls the hydra rest endpoints. Will REST Assured work in this scenario ??

    Please reply thanks

    1. Yes it will work, REST Assured doesn’t know or care if you’re accessing a remote server from your REST API.

  19. I have been using REST assured for testing my REST API’s. It is really good but till now I have tested only GET request. How to test a PUT request and verify the JSON response..??

    1. Hi,

      Just change form get(“..”) to put(“..”) in the code. Check out the documentation at the REST Assured web site.

      Regards,
      /Johan

  20. I am trying to do a get on a URL that contains a list of values (between 0.2.17.5215 and 0.2.17.5216)

    http://localhost:8082/demo/titles/0.2.17.5215,0.2.17.5216/?expand=assets

    I tried different things like

    get(“http://localhost:8082/demo/titles/0.2.17.5215,0.2.17.5216/?expand=assets”).then().log().body()

    but without luck. what is the appropriate way of calling get?

  21. Hi,
    First of all i thank for creating this tool. I just love using RestAssured. Its pretty simple and straight forward. I am able to successsfully automate one of the products completely without any issues.

    Now have another product to be automated but facing the below issue.
    I have a login endpoint (A POST method) with query parameters . I am using it a s below.

    Response res=given()
    .accept(ContentType.JSON)
    .contentType(ContentType.URLENC)
    .param(“email”, “xx@xx.biz”,”password”, “Password1″,”rememberMe”,false)
    .when()
    .post(“https://xx.xx/core/rest/auth/login”);

    System.out.println(res.asString());

    But i get the below response using rest assured

    403 Forbidden

    Forbidden
    You don’t have permission to access /core/rest/auth/login
    on this server.

    where as i get the proper response from RestClient with Mozilla or using curl command.

    What is that i am missing.

    Need this urgently. It would be great if we get help.

    Thanks,
    SHama Ugale

  22. Excellent Restful WS testing tool – I make use of it for automation testing with Jenkins. One question, do you have a SOAP WS sibling project?

    1. Nope, sorry. But you should be able to test SOAP services as well with REST Assured. If there are things we can do to improve the SOAP support I’d like to get your feedback. Please use the mailing list if you want to discuss things further.

      1. Hi,

        I am curious, how can we do it? Same methods , no change?

  23. Hi,
    Can we run parallel test in Rest Assured?
    Can we create a test suite?

Leave a Reply

Close Menu