Is your REST assured?

A couple of months ago I introduced a new open source Java framework for simple automated testing of REST/HTTP services called REST Assured. A lot of things have happended to the framework since then and it’s now better than ever. In this blog I’m going to summarize some of the most important new features that have been added since the last blog post.

Easy parsing of the response body

JSON

Let’s assume that a REST service at localhost:8080/json returns:

As a recap let’s say you want to validate that the lottoId is equal to 5 and winnerIds are 23 and 54 you can do like this:

where “equalTo” and “hasItems” are standard Hamcrest matchers. But what if you want to return the lottoId or winnder id’s and do something with the values? For this reason JsonPath has been added to REST Assured. Example:

You can also set a so called “root path” so that you don’t have to repeat the entire path for every “get”:

XML

The equilvant of JsonPath for XML is called XmlPath and it works in very much the same way as JsonPath but arguably a bit more complex because of the nature of XML. Consider the following XML available at localhost:8080/xml:

Now let’s make a request and parse the XML:

As with JsonPath you can also set a root path to make it a bit more efficient:

Filters

Another powerful feature is support for filters. A filter allows you to inspect and alter a request before it’s actually committed and also inspect and alter the response before it’s returned to the expectations. You can regard it as an “around advice” in AOP terms. Filters can be used to implement custom authentication schemes, session management, logging etc. To create a filter you need to implement the com.jayway.restassured.filter.log.Filter interface. Here’s an example filter that simply logs the response body to the console:

You can then apply your filter like this:

REST Assured already comes with two pre-defined logging filters called ResponseLoggingFilter and ErrorLoggingFilter are there’s also shortcuts for using these filters (see below).

Logging

When writing a test it’s often useful to see what the response body actually looks like. To easily accomodate this REST Assured provides a shortcut for adding the two logging filters introduced in the previous section. So to log the response body regardless of the status code you can just do:

If you only which to log when an error occurs you can do:

Form authentication

Form authentication is one of the most popular authentication techniques on the net today and using REST Assured it’s very simple to test services requiring this scheme. Imagine that the request to localhost:8080/json requires form authentication, we can then do:

In many cases it’s as simple as that! Basically what happens is that REST Assured parses the login page and logs in for you before making the original request. But if you have many tests or if REST Assured is not able to parse the login page you can supply something called a FormAuthConfig to tell REST Assured how to login. What you provide is the form action and the user name and password input tags. This option will also make your test run faster since there’s no need for REST Assured to make an additional requests and parse the login page. For example:

If you’re using Spring Security there’s a pre-defined FilterAuthConfig:

Reusable specifications

Instead of having to duplicate response expectations and/or request parameters for different tests you can re-use an entire specification. To do this you define a specification using either the RequestSpecBuilder or ResponseSpecBuilder.

E.g. let’s say you want to make sure that the expected status code is 200 and that JSON the size of the JSON array “x.y” has size 2 in several tests you can define a ResponseSpecBuilder like this:

In this example the data defined in “responseSpec” is merged with the additional body expectation and all expectations must be fulfilled in order for the test to pass.

You can do the same thing if you need to re-use request data in different tests. E.g.

Here the request’s data is merged with the data in the “requestSpec” so the request will contain two parameters (“parameter1” and “parameter2”) and one header (“header1”).

Summary

As you’ve hopefully seen there are many new useful features added to REST Assured. Other new features that have not been mentioned in this post are e.g. improved HTML parsing, very simple XSD/DTD validation, multi-value parameters, setting root path on expectations, improved configuration of default settings etc etc. In the future we’ll hope to add support for JSONP, better XML parsing using XmlPath and a more BDD-like (given, when, then) syntax. Please visit our homepage for more information and downloads.

This Post Has 33 Comments

  1. Hi, learned a lot from your writings and I use rest-assured for API testing. Although, I have an issue that I trying to resolve and can’t find appropriate solution.

    Have following form info:

    AuthKey:

    DeviceID:

    The page has multiple form inputs each doing different thing. If it was a single form, I know I’ll be fine but handling multiple form in single request is something that I can’t get into my hand… Any thoughts on how to do it?

    Basically, the only different thing that identifies the different form input tag from one another is the hidden tag with value=”create”. Other form has value=”delete” and value=”edit” respectively.

  2. looks the my html was stripped but the idea was that there are three forms each responsible for separate action (create, delete, edit). Not sure how to handle them using hidden input tag

  3. Hi,

    Could you please post this on the mailing list instead?

    /Johan

  4. Impresses by your rest-assured, here I am requesting you to please provide us a step by step tutorial on “How to add rest-assured to our projects to test?” we are facing lot of troubles
    Thanks,
    Sai

    1. Please read the getting start page followed by the usage guide at the web page.

      1. I have understood what the rest assured is about and how to use it but we are facing problems while adding the maven dependencies please help in this scenario.

        1. Please use the mailing list and describe your problems there.

  5. I have one question on matchesXsd(xsd1). Actually i am getting one xml response and i am validating it against xsd1. But this xsd1 internally refers to xsd2. So it fails.
    Can anyone please help me on this?

    Thanks in advance

    1. You can probably configure this using a feature in com.jayway.restassured.path.xml.config.XmlPathConfig. There’s even a shortcut for disabling external DTD validation, XmlPathConfig.disableLoadingOfExternalDtd(). Perhaps that helps.

  6. In REST Assured can I able to log in using req username and password?

    1. If you do given().log().all(). .. then REST Assured will print all request attributes, body and headers.

      1. Hello Johan,

        This is my code :
        RestAssured.baseURI=”http://v-itig31″;
        RestAssured.basePath=”/qcbin”;

        Response response=given().auth().form(“pratik_patil”, “pat123”, new FormAuthConfig(“/j_spring_security_check”, “j_username”, “j_password”)).when().get(“/rest/?login-form-required=y”);

        I want to login using req UN and PWD. But it is not able to login. When I am sysout(response.asString()) so its showing login page only. How m I able to login to this page and validate it whether I logged in or not? Please help me to get out of this tricky situation.
        Thanks in advance Johan.

        Regards,
        pratik

        1. Please use the mailing list and also describe what your login page looks like and I’ll try to help.

          1. Hi Johan,

            This link will tell you what exactly I want to do. When I hit URL manually & log in to that, I get response as XML, thats fine. But when I am trying to login using rest assured I am getting HTML response. I tried so many things to get out of this problem, but no use. Even I changed my code little bit,
            Response response=given().that().parameter(“j_username”,userName).parameter(“j_password”, password).when().post(“http://x-xxxxYY:YYYY/qcbin/authentication-point/login.jsp?redirect-url=http%3A%2F%2Fx-yyyyAA%3A1111%2Fqcbin%2Frest%2Fis-authenticated%3Flogin-form-required%3Dy”).then().extract().response();
            System.out.println(response.asString());
            But still the response is same i.e. HTML. Please Johan help me out for this.

            Please refer the link also that I provided you. If you want more information, we can discuss this on mail.
            Regards,
            Pratik

  7. We’re using Pivotal Cloud Foundry to host our microservices. We’ve newly got the PCF’s login server in action which authenticates using oauth.
    My baseurl gets redirected to the login page which I’m not able to automate using rest-assured.
    I tried basic, form – with FormAuthConfig- Spring Security and oauth as well. Can you pls help me?

    1. Please use the REST Assured mailing list

  8. The examples you gave are very understandable. Thank you for helping people like me.
    This example says only if yo have a response in Json format.

    I am new to automation testing, I am given a login API which takes email, password and domain which returns a token. I don’t know how to initiate a call and then store the token in a variable and use to another tests. I am looking for a code snippet which actually makes a POST call to an API /login and stores the response. Appreciate your help.
    My code
    response = with().parameters(“email”, email, “password”, password, “domain”, domain).baseUri(url).toString();

    response is returned as “com.jayway.restassured.internal.RequestSpecificationImpl@e7edb54”

  9. This is a very helpful article, thanks for taking eh time to write it up!

    But regarding your comment below (from one of the code snippets):

    // Assuming we’ve statically imported the “from” method in JsonPath we can do:

    I have not been able to use the from() method from the JsonPath class and have not been able to import it specifically, even though I’ve tried importing the JsonPath class itself like so:

    import com.jayway.jsonpath.JsonPath;

    and

    import com.jayway.jsonpath.JsonPath.*;

    What am I doing wrong? The get() method appears to be exactly what I need, but I can’t use it because I haven’t been able to import it in my Java project.

    Any feedback here on how I can actually access the get() method would be deeply appreciated!

    Thanks,

    Wulf

    1. The JsonPath you’re referring to is NOT the same as the one used in REST Assured (it’s confusing, I agree). The JsonPath is RA is using GPath. See docs.

  10. Hi Johan,
    I am unable to use login session id as header for another post call(it may be rest console or another @testng method),but i am able login successfully with json as response,

    1. Please use the mailing list and I’ll try to respond.

  11. HI,

    I have a requirement for my tests.My tests are mostly of data driven type.
    I am using some external json files(ex: testdata.json) where i keep the response body which is the expected data.
    Now in my test, i do a get or post to a api with the above json.
    for ex: to post, i use the above json file as a param with the post request
    my question here is:
    i need to validate the response body objects with the json file testdata i have.

    i have a sample code for get where i call the json file and convert it into of type JSONObject and keep the elements in json array.
    Since the return type of ResponseBody object is string .how do i convert this string into an JSONArray so that i can validate the response element data with my json file data
    public class SampleTest {
    String jsonFile = “testdata.json”;
    String baseURL = “http://erp.creyate.biz:6006/”;
    String path = “bom/api/billofmaterial/v1/generate/erp/OW3-497877/CMSH-W3-QNQUT”;

    @Test
    public void sampleTest() throws IOException, ParseException {
    String url = baseURL + path;
    Response response = get(url);
    assertTrue(response.getStatusCode() == 200);

    ResponseBody body = response.getBody();

    FileReader reader = new FileReader(jsonFile);
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(reader);

    JSONArray jsonUsers = (JSONArray) json.get(“erp”);
    Iterator it = jsonUsers.iterator();
    while (it.hasNext()) {
    JSONObject jsonUser = (JSONObject) it.next();

    String Name = (String) jsonUser.get(“Name”);
    String Quantity = (String) jsonUser.get(“Quantity”);
    String erpId = (String) jsonUser.get(“Erp Id”);
    String Unit = (String) jsonUser.get(“Unit”);

    }

    }

    }

  12. Hi,

    I am trying to assert the presence if a header value in a response, asserting that a header has a non null value.

    is this possible?

    regards

  13. answering my own question:

    header(“TOKEN”, is(notNullValue())).

    1. That’s right.

  14. Exceptional post but I was wondering iff you could write a litte more on this
    subject? I’d be very thankful if you could elaborate
    a little bit further. Many thanks!

  15. whoah this blog is great i like reading your posts.

    Keep up the great work! You understand, lots of persons are searching round for this information,
    you could help them greatly.

  16. This is very attention-grabbing, You’re an overly professional blogger.
    I have joined your feed and sit up ffor in qest of extra of your excellent post.
    Also, I have shared your site in my social networks

  17. I must thank you for the efforts you have put in penning this blog.
    I’m hoping to check out the same high-grade blog posts from you later
    on as well. In fact, your creative writing abilities has motivated me to
    get my own site now ;)

  18. Can you please help me in the ‘form’ method usage?
    I am not able to use it. do i need to import anything specifically or add maven dependency?
    List winnerIds = from(response).get(“lotto.winners.winnderId”);
    thank you

  19. Hi,
    Do we need to use Jayway Jsonpath and Document context to update my json attributes without POJO classes?
    Thanks,
    Pavan

  20. Hi,
    I would like to know the best choice among Restassured.JsonPath and Jayway.JsonPath.
    I am getting confused here , what can be used?

Leave a Reply

Close Menu