How to test Rest API which require authentication using Rest assured

undefined picture undefined · Jan 5, 2014 · Viewed 47.8k times · Source

I want to test a Rest API which require authentication, before getting the Json response. FOr exa. If i want to visit rest API: http://192.168.xx.xx:9000/dashboards/all/list/m1/p1/sch1

then

if I am not already logged in , then this will redirect me to Login HTML page, and after login, this will show me the Json output.

Now I want to write a Rest assured code in java for same: I dont know , whether this is possible to do login using this or not.

SO I written a simple code for same::

public class TestNGSimpleTest1 {

    @Test
    public void testAdd() {
            //expect().
            //statusCode(400).
            //body("Status", equalTo("Success")).
            //when().
            //get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            //System.out.println("Response received is ::" +res);   
            Response res = get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            assertEquals(200,res.getStatusCode());
            String json = res.asString();
            System.out.println("Response received is :: " +json);
    }

So here instead of getting the Json response, I am getting the HTML source page response.

So, my question is if possible, how to do login and get the Json response.

Thanks in advance.

Answer

Powpow picture Powpow · Sep 1, 2016

If you are using default authentication from JIRA, then preemptive authentication is what you need. Below are the sample code.

RestAssured.baseURI = System.getProperty("baseurl");
PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("admin");
authScheme.setPassword("admin");
RestAssured.authentication = authScheme;

The sample code will help you do the authentication before every request you send.