Testing RESTful Web Services made easy using the REST-assured Framework

October 23rd, 2011 by

REST-assured Integration Test Tutorial Logo There are many frameworks out there to facilitate testing RESTful webservices but there is one framework I’d like to acquaint you with my favourite framework named REST-assured.

REST-assured offers a bunch of nice features like a DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads and those features we’re going to explore in the following article.

With a few lines of code and Jersey I have written a RESTful web service that allows us to explore the features of the REST-assured framework and to run tests against this service.

 

Prerequisites

We’re going to need a JDK and Maven .. nothing more …

The REST Service to be tested

I have added a demo web application that exposes a RESTful service (Jersey used here) and allows us to run our tests against it. There are two possible ways to run the web app:

  • Check out the tutorial sources (see chapter “Tutorial Sources Download“) and run
    mvn tomcat:run
  • Or simply download the following war file from my Bitbucket repository and deploy it to a valid web container like Tomcat, Jetty etc..
  • If you’re running the app and open the URL http://localhost:8080 in your browser you should be able to see a nice overview of the exported service methods
    REST Service Overview

    REST Service Overview

Adding REST-assured to your Maven project

You only need to add the following dependencies to your pom.xml to use REST-assured  and – of course JUnit..

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.10</version>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>com.jayway.restassured</groupId>
 <artifactId>rest-assured</artifactId>
 <version>1.4</version>
 <scope>test</scope>
</dependency>

Examples

I have added some examples for different scenarios to test .. headers, status codes, cookies, file uploads etc ..

Verify JSON GET Request

We’re testing a simple response containing some JSON data here ..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body:
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test case:

@Test
public void testGetSingleUser() {
  expect().
    statusCode(200).
    body(
      "email", equalTo("test@hascode.com"),
      "firstName", equalTo("Tim"),
      "lastName", equalTo("Testerman"),
      "id", equalTo("1")).
    when().
    get("/service/single-user");
}

Using JsonPath

This time we’re using JsonPath to programatically test the returned JSON structure..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testGetSingleUserProgrammatic() {
  Response res = get("/service/single-user");
  assertEquals(200, res.getStatusCode());
  String json = res.asString();
  JsonPath jp = new JsonPath(json);
  assertEquals("test@hascode.com", jp.get("email"));
  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals("1", jp.get("id"));
}

Using Groovy Closures

JsonPath allows us to use Groovy closures to perform searches on the returned JSON structure.

  • Request URL: /service/persons/json
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
    	"person":[
    	{
    		"@id":"1",
    		"email":"test@hascode.com",
    		"firstName":"Tim",
    		"lastName":"Testerman"
    	},{
    		"@id":"20",
    		"email":"dev@hascode.com",
    		"firstName":"Sara",
    		"lastName":"Stevens"
    	},{
    		"@id":"11",
    		"email":"devnull@hascode.com",
    		"firstName":"Mark",
    		"lastName":"Mustache"
    	}
    	]
    }

And this is our test – we’re searching for a person whose email matches the pattern /test@/:

@Test
public void testFindUsingGroovyClosure() {
  String json = get("/service/persons/json").asString();
  JsonPath jp = new JsonPath(json);
  jp.setRoot("person");
  Map person = jp.get("find {e -> e.email =~ /test@/}");
  assertEquals("test@hascode.com", person.get("email"));
  assertEquals("Tim", person.get("firstName"));
  assertEquals("Testerman", person.get("lastName"));
}

Verifying XML

Now we’re going to validate returned XML

  • Request URL: /service/single-user/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user>
      <email>test@hascode.com</email>
      <firstName>Tim</firstName>
      <id>1</id>
      <lastName>Testerman</lastName>
    </user>

And this is our test:

@Test
public void testGetSingleUserAsXml() {
  expect().
    statusCode(200).
    body(
      "user.email", equalTo("test@hascode.com"),
      "user.firstName", equalTo("Tim"),
      "user.lastName", equalTo("Testerman"),
      "user.id", equalTo("1")).
    when().
    get("/service/single-user/xml");
}

XML using XPath

To validate complex XML structure XPath is way more comfortable here..

  • Request URL: /service/persons/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <people>
      <person id="1">
        <email>test@hascode.com</email>
        <firstName>Tim</firstName>
        <lastName>Testerman</lastName>
      </person>
      <person id="20">
        <email>dev@hascode.com</email>
        <firstName>Sara</firstName>
        <lastName>Stevens</lastName>
      </person>
      <person id="11">
        <email>devnull@hascode.com</email>
        <firstName>Mark</firstName>
        <lastName>Mustache</lastName>
      </person>
    </people>

And this is our test:

@Test
public void testGetPersons() {
 expect()
 .statusCode(200)
 .body(hasXPath("//*[self::person and self::person[@id='1'] and self::person/email[text()='test@hascode.com'] and self::person/firstName[text()='Tim'] and self::person/lastName[text()='Testerman']]"))
 .body(hasXPath("//*[self::person and self::person[@id='20'] and self::person/email[text()='dev@hascode.com'] and self::person/firstName[text()='Sara'] and self::person/lastName[text()='Stevens']]"))
 .body(hasXPath("//*[self::person and self::person[@id='11'] and self::person/email[text()='devnull@hascode.com'] and self::person/firstName[text()='Mark'] and self::person/lastName[text()='Mustache']]"))
 .when().get("/service/persons/xml");
}

XML verification vs a Schema

Now we’re going to validate the xml returned against a XML schema file

  • Request URL: /service/single-user/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user>
      <email>test@hascode.com</email>
      <firstName>Tim</firstName>
      <id>1</id>
      <lastName>Testerman</lastName>
    </user>

This is the schema we’re using to validate in a file named user.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
 
	<element name="user">
		<complexType>
			<sequence>
				<element name="email">
					<simpleType>
						<restriction base="string">
							<pattern value=".+@.+"></pattern>
						</restriction>
					</simpleType>
				</element>
				<element name="firstName" type="string"></element>
				<element name="id" type="int"></element>
				<element name="lastName" type="string"></element>
			</sequence>
		</complexType>
	</element>
</schema>

And this is our test case:

@Test
public void testGetSingleUserAgainstSchema() {
  InputStream xsd = getClass().getResourceAsStream("/user.xsd");
  assertNotNull(xsd);
  expect().
  statusCode(200).
  body(
    matchesXsd(xsd)).
  when().
  get("/service/single-user/xml");
}

Handling Request Parameters

This is a simple example how to add some request parameters

  • Request URL: /service/user/create
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testCreateuser() {
  final String email = "test@hascode.com";
  final String firstName = "Tim";
  final String lastName = "Tester";
 
  given().
    parameters(
      "email", email,
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("email", equalTo(email)).
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/service/user/create");
}

HTTP Status Code

Now an example how to verify HTTP headers – in the following example, a 404 Page Not Found is returned ..

  • Request URL: /service/status/notfound
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Status: 404 / Page Not Found

And this is our test:

@Test
public void testStatusNotFound() {
  expect().
    statusCode(404).
  when().
  get("/service/status/notfound");
}

Authentication

In this example we’re handling basic authentication ..

Basic Authentication secured REST Service

Basic Authentication secured REST Service

  • Request URL: /service/secure/person
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)

And this is our test:

@Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/service/secure/person");
 
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/service/secure/person");
}

Setting HTTP Headers

In the following example we’re setting some HTTP headers. The value of the HTTP header named “myparam” is returned by the REST service in the response body..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Body: #value-of-myparam#

And this is our test:

@Test
public void testSetRequestHeaders() {
  expect().
    body(equalTo("TEST")).
  when().
    with().
    header("myparam", "TEST").
  get("/service/header/print");
 
  expect().
    body(equalTo("foo")).
  when().
    with().
    header("myparam", "foo").
  get("/service/header/print");
}

Verifying HTTP Headers

Now we’re going to verify HTTP response headers

  • Request URL: /service/header/multiple
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Header: customHeader1:foo, anotherHeader:bar

And this is our test:

@Test
public void testReturnedHeaders() {
  expect().
    headers("customHeader1", "foo", "anotherHeader", "bar").
  when().
  get("/service/header/multiple");
}

Setting Cookies

The following example shows how to set cookies. The REST service sends a 403 / Forbidden until a cookie with name=authtoken and value=abcdef is send.

  • Request URL: /service/access/cookie-token-secured
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Status: 403 / 200

And this is our test:

@Test
public void testAccessSecuredByCookie() {
  expect().
    statusCode(403).
  when().
  get("/service/access/cookie-token-secured");
 
  given().
    cookie("authtoken", "abcdef").
  expect().
    statusCode(200).
  when().
  get("/service/access/cookie-token-secured");
}

Verifying Cookies

This is how to verify cookies set by the service. The service returns the request parameter “name” as the value of the cookie named “userName”:

  • Request URL: /service/cookie/modify
  • Request Method: GET
  • Request Parameter: name
  • Response Cookie: userName:#value-of-name#

And this is our test:

@Test
public void testModifyCookie() {
  expect().
    cookie("userName", equalTo("Ted")).
  when().
    with().param("name", "Ted").
  get("/service/cookie/modify");
 
  expect().
    cookie("userName", equalTo("Bill")).
  when().
    with().param("name", "Bill").
  get("/service/cookie/modify");
}

File Uploads

The following example shows how to handle file uploads. We’re sending a text file to the REST service and the service returns the file content as a string in the response body.

  • Request URL: /service/file/upload
  • Request Method: GET
  • Request Content-Type: multipart/form-data
  • Response Content-Type: text/plain
  • Response Body: #file-content#

And this is our test:

@Test
public void testFileUpload() {
  final File file = new File(getClass().getClassLoader()
      .getResource("test.txt").getFile());
  assertNotNull(file);
  assertTrue(file.canRead());
  given().
    multiPart(file).
  expect().
    body(equalTo("This is an uploaded test file.")).
  when().
  post("/service/file/upload");
}

Registering custom parsers for MIME-types

Sometimes you’ve got to handle a RESTful service that returns an invalid content type so that REST-assured does not know which parser to use to process the response. This is not a real problem though because the framework allows you to register parsers for a given content type as shown in the example below:

  • Request URL: /service/detail/json
  • Request Method: GET
  • Response Content-Type: text/json
  • Response Body:
    {"test":true}

And this is our test:

@Test
public void testRegisterParserForUnknownContentType() {
  RestAssured.registerParser("text/json", Parser.JSON);
  expect().
    body("test", equalTo(true)).
  when().
  get("/service/detail/json");
}

Specification reuse

Another nice feature of the REST-assured framework the possibility to create specifications and reuse, modify or extend them in several tests.

  • Request URL: /service/single-user / /service/user/create
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testSpecReuse() {
  ResponseSpecBuilder builder = new ResponseSpecBuilder();
  builder.expectStatusCode(200);
  builder.expectBody("email", equalTo("test@hascode.com"));
  builder.expectBody("firstName", equalTo("Tim"));
  builder.expectBody("lastName", equalTo("Testerman"));
  builder.expectBody("id", equalTo("1"));
  ResponseSpecification responseSpec = builder.build();
 
  // now we're able to use this specification for this test
  expect().
    spec(responseSpec).
  when().
  get("/service/single-user");
 
  // now re-use for another test that returns similar data .. you may
  // extend the specification with further tests as you wish
  final String email = "test@hascode.com";
  final String firstName = "Tim";
  final String lastName = "Testerman";
 
  expect().
    spec(responseSpec).
  when().
    with().
    parameters(
      "email", email,
      "firstName", firstName,
      "lastName",lastName).
  get("/service/user/create");
}

Troubleshooting

  • WARNING: Cannot find parser for content-type: text/json — using default parser.” – The framework does not know for sure which parser to use. Register the corresponding parser like this: e.g. RestAssured.registerParser(“text/json”, Parser.JSON);
  • “If I use the War file, the path is no longer localhost:8080, but becomes http://localhost:8080/rest-assured-example/.” -  specify the changed context path in the get() method or – more comfortable – define it as a global setting e.g. like this one
    @Before
     public void setUp(){
     RestAssured.basePath = "yourbasepath";
     }

Tutorial Sources

I have put the source from this tutorial on my Bitbucket repository – download it ther.

Slideshow

View presentation on slideshare.

View more presentations of mine.

Resources

Additional REST articles of mine

Please feel free to have a look at these tutorials of mine covering different aspects of handling or creating RESTful webservices.

Article Updates

  • 2021-06-16: Added link to sources on GitHub
  • 2018-06-01: Embedded Slideshare presentation removed (GDPR/DSGVO).
  • 2015-10-22: Link list updated.
  • 2015-08-06: Links to other REST articles of mine added.

Tags: , , , , , , , , ,

113 Responses to “Testing RESTful Web Services made easy using the REST-assured Framework”

  1. Fergus MacDermot Says:

    That’s really nice. How do you get the exported view? Is that a default Jersey feature? I know the wadl is produced, but didn’t know this part. Thanks for your examples too. Very helpful. We are trying to work out whether to use something like this, jbehave, or custom….

  2. suranjana Says:

    THANKS!!!!

  3. mark Says:

    Where can I find the demo application war file?

  4. micha kops Says:

    Hi, you can download the war file from my Bitbucket repository.

  5. mark Says:

    Thanks for the .war. I didn’t see it when I was looking at your Bitbucket repository. Now that I’ve got the .war deployed and tomcat running, I tried your example for testGetSingleUser(). I had to change get(“/service/single-user”); to get(“/rest-assured-example/service/single-user”); in order for it to find the resource and return a status code of 200.

  6. mark Says:

    Running the XML using XPath example, I’m getting an error:

    java.lang.AssertionError: Body doesn’t match.
    Expected:
    an XML document with XPath //person[@id='1']/email[.='test@hascode.com'] and firstName=’Tim’ and lastName=’Testerman’
    Actual:
    test@hascode.comTimTestermandev@hascode.comSaraStevensdevnull@hascode.comMarkMustache

    I’m using this code
    expect().statusCode(200)
    .body(hasXPath(“//person[@id='1']/email[.='test@hascode.com'] and firstName=’Tim’ and lastName=’Testerman’”))
    .body(hasXPath(“//person[@id='20']/email[.='dev@hascode.com'] and firstName=’Sara’ and lastName=’Stevens’”))
    .body(hasXPath(“//person[@id='11']/email[.='devnull@hascode.com'] and firstName=’Mark’ and lastName=’Mustache’”))
    .when().get(“/rest-assured-example/service/persons/xml”);

    Thanks for any help you can provide so I can understand how this works.

  7. micha kops Says:

    Works for me .. using mvn tomcat:run as well as using a deployed war archive on a tomcat instance. but I’ve noticed that the xpath expression was not well defined and precise enough .. I’ve fixed this and updated the example .. thanks for mentioning!

  8. mark Says:

    Thanks Micha. The new code works.

  9. Lu Says:

    Hello, Micha. Excellent tutorial. If I use the War file, the path is no longer localhost:8080, but becomes http://localhost:8080/rest-assured-example/. This causes the tests to fail. How do I fix this? I am currently looking at your source code to find it.
    Thanks so much !!

  10. micha kops Says:

    Thanks! You just simply need to specify the new context path – one way is to specify it in the get() method but it is way more comfortable to specify it globally using RestAssured.basePath = “yourbasepath”;

  11. Lu Says:

    Hi again, Micha. I should have found that answer right above. :( Anyway, any ideas why I am
    unable to do your public void testFileUpload() on JUnit? Everything else works.

  12. micha kops Says:

    No problem :) Are you getting any error here? Does the file exist in your classpath? Have you modified the original example somehow? Does the servlet container return any error or is there an error displayed in your server’s logs?

  13. Lu Says:

    final File file = new File( getClass().getClassLoader()
    .getResource( “test.txt” ).getFile() );

    java.lang.NullPointerException
    at it.RestAssuredSampleServiceIT.testFileUpload(RestAssuredSampleServiceIT.java:154)

    I see the file in the project as you listed it, and have not changed anything.

  14. micha kops Says:

    Hmm.. could you please run the test using some external file and an absolute path? Have you included the dependency for jersey-multipart (com.sun.jersey.contribs:jersey-multipart) in your project?

  15. Lu Says:

    Micha, I don’t know why but I searched and the solution was to move the test.txt to the \target\classes folder.

  16. micha kops Says:

    Ok – I’m glad it finally worked somehow :)

  17. Chantme Says:

    Hi Micha

    I took the last war file and deployed it on Tomcat 7, I get a 404 error for every REST call from your welcome test page.

    Tomcat is “Apache Tomcat 7.0.30 Server”, installed as a service on Windows. Java is “C:\Program Files\Java\jre7\bin\client\jvm.dll”

    I took the same war file, and installed it on another machine with Tomcat “Apache Tomcat 6.0.36 “, Java “C:\Program Files\Java\jre7\bin\client\jvm.dll”, everything works fine.

    Does anybody had the same problem ?

  18. micha kops Says:

    Hi,

    what context path did you use for the application? I bet it differs from the one used in my tutorial :)

    Best regards

    Micha

  19. Lisa Says:

    Hi, Micha,

    Thanks for putting together such a nice tutorial! It is really helpful for me to understand rest-assured better. I am trying to figure out what framework to use for my rest web service testing and have some further questions on rest-assured for you.

    Do you happen to have an example to use rest-assured for https web service?

    Also for a web service that supports both xml and json, is there any way to write same test to handle both these two response format? If not, the tests will double :(.

    Also for a test case, say, 1. user A (may be an admin user) logs in, 2. A create a user B, 3. A then retrieves user B’s info to verify that user B is created correctly.
    step 2 and 3 will need to send out the cookies returned from step 1. Will tester have to set cookie in each request? i was hopping that rest-assured will support updating some default cookies based on server response, then the next http request will by default send the updated cookies. Do you happen to know if this is supported by rest-assured?

    Thanks in advance for your help.
    Lisa

  20. Shama Says:

    Hi,

    I am getting error marked in red for “equalTo” when is use
    body(
    “email”, equalTo(“test@hascode.com”),
    “firstName”, equalTo(“Tim”),
    “lastName”, equalTo(“Testerman”),
    “id”, equalTo(“1″))

    Please guide me. Where am i going wrong

    Thanks,
    Shama

  21. micha kops Says:

    Hi, does the test fail because other values are returned? or are you getting an error in your IDE, perhaps have forgotten the static import for equalTo e.g. import static org.hamcrest.Matchers.equalTo;

    Have you assured that your REST-service is responsive? By adding .log().all() to the response and request specification you’ll receive detailed information what the client sends to the server and the server’s response.

  22. Eduardo Silva Says:

    Hi Micha,

    Again, thank you for this very nice tutorial (today is the third document I read from you about REST-Assured and Jersey Testing Framework… I am evaluating which one to use, and inclining to go with REST-Assured)… this very nice coverage of several capabilities of REST-Assure, with code to test as we read!!

    I also had “failing” tests due to the URL/path of the deployed web service (in Tomcat from Eclipse), by adding the following “@Before” it solved the problem (you have also suggested this in another comment above):

    @Before
    public void setUp(){
    RestAssured.basePath = “http://localhost:8080/rest-assured-example”;
    }

    Cheers!

  23. micha kops Says:

    Hi Eduardo,

    thanks for your kind feedback!

    Cheers

    Micha

  24. Vamsi Says:

    Hi Micha,

    Excellent tutorial.

    Do you happen to have an example to use rest-assured for https web service?

    Thanks
    Vamsi

  25. micha kops Says:

    Thanks for the kind feedback!

    In most cases, HTTPS should work out of the box but there are some cases where you might run into trouble:

    1) The server uses an invalid certificate (you’re getting an SSLPeerUnverifiedException)
    given().relaxedHTTPSValidation().when().get("https://yourserver.com");
    or using specifications: RestAssured.useRelaxedHTTPSValidation();

    You may even specify a Java keystore file if you need to:
    given().keystore("/pathToJksInClassPath", )..
    or using specifications: RestAssured.keystore("/pathToJksInClassPath", );

    If you’ve already loaded a keystore, you may use this keystore, too:
    RestAssured.trustStore(keystore);

    2) The server certificate references an invalid hostname
    In this case, you don’t need to import a keystore .. simply use:
    RestAssured.config = RestAssured.config().sslConfig(sslConfig().allowAllHostnames());

    or in a concrete request
    given().config(RestAssured.config().sslConfig(sslConfig().allowAllHostnames()). .. ;

    Further information can be found in the rest-assured documentation.

  26. Vamsi Says:

    Hi Micha,

    Thank you detailed explanation. I am not able to resolve my issue by using relaxed https validation.

    RestAssured.baseURI = “https://stage3.test.com”;

    RestAssured.port = 443;
    RestAssured.urlEncodingEnabled = false;

    String body = given()
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”)
    .header(“IMAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product/”)
    .prettyPrint();

    Output:
    here is the http response what i am getting.

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Fri, 07 Feb 2014 08:18:20 GMT
    Content-Length: 232

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘http://stage3.test.com:81/services/api/v1/product/’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Kindly help me how to resolve this issue.

    Thanks in advance.

    Thanks
    Vamsi

  27. micha kops Says:

    Are you sure that your base URI and port specification is applied? In your response I’m reading “http://stage3…” and port 81?

  28. Vamsi Says:

    Hi Micha,

    Thanks for quick response, i am new to Rest Assured and all our services can access only https.

    I am really not sure how to check port specification applied, but yes…wat ever i change i am getting test is happening only on port81.

    Kindly help me to debug and fix the issue.

    Thanks
    Vamsi

  29. micha kops Says:

    Do you override this setting somewhere? rest assured’s default port is 8080, host=localhost ..
    When running in a JUnit test you could use the setup method to set your requirements here ..

    @Before
    public void setup(){
    // .. your setup
    }

  30. Vamsi Says:

    Hi Micha,

    I am not overriding any settings as i am not aware of these procedure:(. Can you please help me in more detail and i am using testng runner.

    Thanks
    Vamsi

  31. Vamsi Says:

    Hi Micha,

    i just did a small correction in my script

    given()
    .port(1234)

    it returns following error: Connection to https://stage3.test.com:1234 refused.

    Thanks
    Vamsi

  32. micha kops Says:

    Good to hear, that adjusting your test to your specified port and connection type is working for you now!

  33. Vamsi Says:

    sorry, its not correct port.. i just tried with some dummy port which resulted into connection refuse. I need still your help on port overriding to 443. Kindly help me on this.

    i am new to Rest assured and this is my first trial… please let me know how to resolve this issue.

    Thanks
    Vamsi

  34. Vamsi Says:

    Hi Micha,

    sorry for keepon posting.

    little more progress.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    Thanks
    Vamsi

  35. micha kops Says:

    Maybe you need to add your own trust store

  36. vamsi Says:

    Hi Micha,

    I have added trust store, here is the next error i am getting.

    Script:

    import com.jayway.restassured.*;
    import com.jayway.restassured.path.xml.XmlPath;
    import com.jayway.restassured.response.Response;
    import com.jayway.restassured.matcher.RestAssuredMatchers.*;

    import static com.jayway.restassured.RestAssured.*;
    import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
    import com.jayway.restassured.response.Response;
    import static org.hamcrest.Matchers.*;
    import org.hamcrest.Matchers.*;
    import org.testng.Assert;
    import org.testng.annotations.Test;

    import java.util.List;

    import static com.jayway.restassured.RestAssured.given;
    import static org.hamcrest.CoreMatchers.hasItem;

    public class Test_RestAssured {
    @Test
    public static void test(){
    //RestAssured.port = 443;
    RestAssured.baseURI = “https://stage3.test.com”;
    String body = given()
    .port(443)
    .keystore(“c:/users/autolab/truststore_javanet.jks”, “abcdef”)
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”, “ImAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product”)
    .prettyPrint();

    }

    }

    Here is the Https Response and error:

    [TestNG] Running:
    C:\Users\autolab\AppData\Local\Temp\testng-eclipse-660754300\testng-customsuite.xml

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Sat, 08 Feb 2014 10:05:19 GMT
    Content-Length: 228

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘https:/stage3.test.com/services/api/v1/product’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Please help me to proceed further.

    Thanks in advance.

    Thanks
    Vamsi

  37. vamsi Says:

    Hi Micha,

    I’ve added trust store, still i am getting below issue. Please help to proceed further.

    Script:
    public class Test_RestAssured {
    @Test
    public static void test(){
    RestAssured.urlEncodingEnabled = false;

    String body = given()
    .port(443)
    .keystore(“c:/users/autolab/truststore_javanet.jks”, “abcdef”)
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”, “ImAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product”)
    .prettyPrint();
    }

    }

    output:

    [TestNG] Running:
    C:\Users\autolab\AppData\Local\Temp\testng-eclipse-660754300\testng-customsuite.xml

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Sat, 08 Feb 2014 10:05:19 GMT
    Content-Length: 228

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘https://stage3.test.com/services/api/v1/product’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Thanks
    Vamsi

  38. micha kops Says:

    Seems like you’ve managed to handle the HTTPS problems. Is https://stage3.test.com/services/api/v1/product with method=GET and content-type header application/json correct? Are you able to access the webservice using curl or since it’s using GET .. your browser when using the designated target?

  39. Pratik Says:

    Hi dear friend,

    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”);

    This is my code. Actually when I am entering URL using get(), I am getting LOGIN page of ALM.
    I want to login using required UN and PWD. I googled for this and got this solution but its not working for me. Please help me for this if you know, What to do in this.

    Thanks in advance.
    Regards,
    Pratik

  40. micha kops Says:

    Hi Pratik,

    I’m using the following setup to log into my JEE applications secured with form-based authentication:

    String userName = "user";
    String password = "password";
    FormAuthConfig authConfiguration = new FormAuthConfig("j_security_check", "j_username", "j_password");
    RedirectConfig redirectConfiguration = new RedirectConfig().followRedirects(true).allowCircularRedirects(true);

    RestAssured.config = RestAssuredConfig.config().redirect(redirectConfiguration);
    RestAssured.authentication = RestAssured.form(userName, password, authConfiguration);

  41. Pratik Says:

    Hi Micha kops,

    Thnx for your valuable reply and time u have given to me. I used your code. But I am not able to identify how do I check whether I logged in or not. I am using asString() to check whether next page displayed or not but it is showing login page only. Other thing is should I use post() for this or get() will be fine? I did not get form-based authentication? what it means ?

    I am waiting for your reply.

    Thanks once again.

  42. micha kops Says:

    I assume that your application is using Spring Security (“j_spring_security_check”) .. REST-asssured offers a pre-defined filter auth config .. maybe it’s worth a try for you:

    given().auth().form("username", "password", FilterConfig.springSecurity())..

  43. Pratik Says:

    Hi Micha friend,

    Can I get some examples or applications like you provided where I can work on put() and delete() functionality of rest-assured? I already did get() and post() with the help of your application only. Thanks in advance.

    And yes, the last solution you told me about login to QC-ALM not worked. I don’t know what to do. So I skipped that and worked on some other functionality. If you have any other solution, please let me know.

    Thanks again. :)
    Regards,
    Pratik

  44. micha kops Says:

    Hi Pratik,
    use put() or delete() just like you would use get(), but put() accepts a request body though.
    What do you want to know? :)

    Cheers,

    Micha

  45. Pratik Says:

    Hello Micha,

    See the link I am providing you,
    http://www.joecolantonio.com/2013/03/12/alm-how-to-get-started-using-the-alm-rest-api/

    In this I want to login using rest assured(I want to authenticate ALM user with rest assured); step 1 given in this link. If it is successful then I can get or delete any information I want like get a bug or delete bug like that. If login is successful then only I can proceed and rest apis spring security method works for older version of ALM. So for new version it is not working. Can you help me in that?

    Thanks for your valuable reply. :)
    Regards,
    Pratik

  46. micha kops Says:

    Hi Pratik,
    if you don’t know how to reproduce the login, simply work through the log in process in your browser e.g. Chrome or Firefox with Firebug or HTTPLiveHeaders extension installed and record what exactly is needed to complete the login process as documented in the web site that you’ve posted .. cookies, headers, actions/methods used and parameters passed …
    Afterwards you should have gathered everything you need to know to reproduce the login process with rest-assured.

    Please feel free to ask if you’ve got further questions :)

    Cheers,

    Micha

  47. Hari Kiran Says:

    Hi Micha really appreciate for the nice website .

    Thanks a lot

    -Hari

  48. micha kops Says:

    Thanks for your kind feedback!

  49. Tunji Says:

    How do i test @post i have seen a lot of tutorials on @get, but none so clear on @post. Thank you.

  50. micha kops Says:

    Hi Tunji,

    no problem! Given a RESTful webservice consuming JSON data e.g. like this one:

    @Path("book")
    @Consumes(MediaType.APPLICATION_JSON)
    @POST
    public Response saveBook(Book book){
    return Response.ok().build();
    }

    This would be a valid test for the web-service:

    @Test
    public void shouldSaveABook() {
    Book book = new Book(123, "Some title");
    expect().statusCode(200).when().given().contentType("application/json;charset=UTF-8").body(book).post("/book");
    }

  51. Vlad Says:

    Hi, Micha! Is Rest-Assured used only with localhost or can I use it with real URL address?

  52. micha kops Says:

    Hi Vlad,

    you may use rest-assured with every hostname or ip address you like e.g. expect()…get(“http://www.yourdomain.com/”).
    If you’re running multiple tests for a specific base-domain you may set it up for the framework like this: RestAssured.baseURI = “https://jira.atlassian.com”;

    Cheers,

    Micha

  53. Vlad Says:

    Thank you very much, Micha! I really appreciate your help!

  54. micha kops Says:

    You’re welcome! :)

  55. Sek Says:

    Hi Micha,

    I want to do restful web services testing in java 1.5 environment. Is there any tool/package to help me out ?
    I guess rest-assured is for run time environments jvm > 6 .

    I have strict limitation of jdk 1.5 (compilation/run time)

  56. micha kops Says:

    Hi Sek,

    should be working in Java 5 – I’ve added an example using Java 5, jUnit and rest-assured here: https://bitbucket.org/hascode/rest-assured-with-java5

  57. Prakash Says:

    Hi,
    It was really a nice article. I loved the way you explained. I am beginner and this single article is good enough to learn rearest assured. Can you please provide some examples for POST, PUT and DELETE methods.

    Keep going.

  58. lincel Says:

    Hola.
    Consulta, quiero testear un servicio REST con varios puntos de entrada REST. Para probar los puntos de entrada tengo las URL, pero para probar las peticiones en las urls tengo el wildfly levantado (que es el mismo que se utilizará para los datos reales de la BD). Mi consulta es: hay alguna otra forma de probar las entradas REST pero sin utilizar el wildfly? Si existe, cómo podría hacer esta prueba?
    Veo que cuando hacer las llamadas a la entrada REST lo haces de la siguiente forma:
    “Request URL: /service/single-user”, antes levantaste el Widlfly?

    Muchas gracias!!

  59. micha kops Says:

    Hola lincel,

    lo siento, no hablo español. Could you repeat your question in english please? If you’d like to know how to test a RESTful webservice running on a WildFly application server then Arquillian is your tool of choice and I’m using Arquillian and rest-assured to run tests for a couple of Java EE projects by now and it’s working fine.

    Please feel free to ask if there are any questions. In the following article of mine, the Arquillian setup for GlassFish is demonstrated: http://www.hascode.com/2012/04/arquillian-tutorial-writing-java-ee-6-integration-tests-and-more/

    Cheers

    Micha

  60. lincel Says:

    thanks for the reply!

    My question is: is there any other way to test the REST entries but without using the wildfly? If there is, how could I make this test?
    I see that in your example when making calls to the REST entry you do as follows:
    “Request URL: / service / single-user” before you raised the Widlfly?

  61. micha kops Says:

    Hi lincel,

    you don’t need WildFly to run rest-assured. You may use it in a normal JUnit or TestNG test, too. Simply ensure that the RESTful webservice under test is running and add the rest-assured tests.

    Could I help you with this answer or do you need help for a special setup?

  62. MG Says:

    I am using Restassured for checking the API.

    i have one api which redirects with 302 (https://www.qe5.ut1.omniture.com/p/suite/1.3/index.html?a=Landing.Main&ims=1) and ends with opening a new webpage with my login.
    I am using the following call
    response = given()

    // .cookie(“login-token”,loginToken)
    .cookies(“WCDServer”, cookieWCDServer)
    .header(“Authorization”,”Bearer “+ accessToken)
    .parameters(“a”,”Landing.Main”)
    .redirects()
    .follow(true)
    .expect()
    .statusCode(200)
    .when()
    .get(“https://www.qe5.ut1.omniture.com/p/suite/1.3/index.html”)
    .then()
    .extract()
    .response();

    This call always takes me to the login page.
    There are 5 calls in between. What am in missing in this?

  63. micha kops Says:

    Hi MG,

    I could think of these two possibilities:

    1) Assure that following the redirects is working for every request – you can do so by adding the following static configuration to your test:

    RedirectConfig reconf = new RedirectConfig().followRedirects(true).allowCircularRedirects(true);
    RestAssured.config = RestAssuredConfig.config().redirect(reconf);

    2) Write a rest-assure matcher for every single request, don’t follow any redirect, parse the Location-header and write a new rest-assured request for the following necessary request so that you can be sure that your test-setup follows strictly the web application’s requirements for authentication there, be sure to set all headers needed.

  64. Bhoomika Says:

    Hi,

    I am new to rest Assured. I am running Rest api test cases in eclipe with jdev.

    I want to connect to remote “HTTP” server to get auth token.

    So the equivalent curl command is

    curl -i -X GET -H ‘X-Storage-User:STORAGEUSER’ \
    -H ‘X-Storage-Pass:PASSWORD’ http://SERVER:PORT/auth/v1.0

    This will give auth token.

    When i used SERVER with https and setting sslconfig() in setup i could connect.

    But if i use “http” server i am not able to connect itself. Tried by setting proxy as well with given().proxy(“prxy” , port).

    @Test
    public void IAAS_get_AuthToken1(){
    Response response = expect().statusCode(200).
    when().given().relaxedHTTPSValidation().headers(“X-Storage-User”, fixture.STORAGEUSER,”X-Storage-Pass”, fixture.PASSWORD).
    get(fixture.AUTHURL);
    String authToken = response.getHeader(“X-Auth-Token”);
    String storageToken = response.getHeader(“X-Storage-Token”);
    assertNotNull(authToken);
    assertNotNull(storageToken);

    }

    Where
    AUTHURL = http://SERVER:PORT/auth/v1.0

    Can anyone help with this please.

  65. Vlad Says:

    Hi, Micha! For some reason I got HTTP 404 code when trying to use PUT action:

    ***
    .expect().statusCode(200)
    .when().put(“/v1.0/event/1330″)
    .then().contentType(ContentType.JSON)
    .extract().response();
    ****

    When I use POST for the same code – it works perfectly fine. Also PUT works in PostMan.
    Do you know what might be the problem?
    Thank you in advance. Vlad.

  66. micha kops Says:

    Hi Vlad,

    your REST-API does not need require you to send a body our content-header in your PUT request? e.g.

    expect().statusCode(200).when().given().body("").contentType(MediaType.APPLICATION_JSON).put("/v1.0/event/1330").then().contentType(ContentType.JSON).extract().response();

    You could add loggers to your request- and response-specification to receive more details about what rest-assured is doing and receiving e.g.

    expect().log().all()..

    Does the similar request execute without error when you’re using Curl directly like this?

    curl -vi -XPUT "http://url/v1.0/event/1330"

  67. Vlad Says:

    Micha, I appreciate your quick response… No, my request has headers with auth token and body etc.. since I need to update my database with this request… My full code looks like this:
    @Test
    public void editPublicEvent(){

    getAdminAuthorization adminTok = new getAdminAuthorization();
    String adminToken = adminTok.getAdminToken();

    RestAssured.baseURI = baseURI;
    Response resp =
    given().header(“Content-Type”, “application/json”)
    .and().given().header(“Accept”, “application/json”)
    .and().given().header(“auth-token”, adminToken)
    .and().given().header(“peak-api-key”, “Gdz2niEcRkPa3qpvWs”)

    .body(“{\r\n \”eventName\”: \”Updated Event-Vlad\”, \r\n ” +
    “\”description\” : \”Event Description\”, \r\n ” +
    “\”trigger\”: \r\n { \r\n \”query\”: \”{ \\\”index\\\”: ” +
    “\\\”person\\\”, \\\”esl\\\”: \\\” { \\\\\\\”query\\\\\\\” : ” +
    “{ \\\\\\\”filtered\\\\\\\” : { \\\\\\\”filter\\\\\\\” : ” +
    “{ \\\\\\\”and\\\\\\\” : [ { \\\\\\\"term\\\\\\\": " +
    "{\\\\\\\"_type\\\\\\\": \\\\\\\"studentprofile\\\\\\\"} }, " +
    "{ \\\\\\\"term\\\\\\\": " +
    "{\\\\\\\"baseUserName\\\\\\\":\\\\\\\"" + baseUsername + "\\\\\\\"} " +
    "} ] } } } } \\\\\\\” }\” \r\n }, \r\n \”schedule\”: \r\n ” +
    “{ \r\n ” +
    “\”startDate\”: \”2015-02-18T00:00:00Z\”,\r\n ” +
    “\”endDate\”: \”2015-02-18T00:00:00Z\”,\r\n ” +
    “\”times\”: \”0 0 0 ? * SUN,MON,TUE,WED,THU,FRI,SAT\” \r\n }, \r\n ” +
    “\”actions\”: \r\n [\r\n {\r\n " +
    "\"emailAction\":\r\n { \r\n " +
    "\"replyTo\": \"replyTo@k12.com\", \r\n " +
    "\"subject\": \"Subject\", \r\n " +
    "\"messageBody\" : \"Message body\", \r\n " +
    "\"sendCopyToGuardians\" : \"false\"\r\n " +
    "}\r\n }\r\n ] \r\n} \r\n”)

    .expect().statusCode(200)
    .when().put(“/v1.0/event/1330″)
    .then().contentType(ContentType.JSON)
    .extract().response();

    String json = resp.asString();
    JsonPath jp = new JsonPath(json);

    System.out.println(“–Server Response is: ” + json);
    System.out.println(“–Test has PASSED! \”\n******************************\n”);

    }

    –The body is calling Elastic Search query – BUT it is works perfect with POST…
    Appreciate your help!

  68. Vlad Says:

    Micha, please desregard my last message – I found the problem: PUT is working but sometning wrong with my request this time. Your advise to use expect().log().all() was REALLY helpfull..
    Thanks so much!!!

  69. micha kops Says:

    Hi Vlad,

    I’m glad I could be a help! :)

    Btw .. you could shorten your test e.g.

    Response resp = expect()
    .statusCode(200)
    .body(
    "eventName", equalTo("Updated Event-Vlad"),
    "description", equalTo("Event Description"
    ))
    .when()
    .given()
    .contentType(MediaType.APPLICATION_JSON)
    .header("Accept", "application/json")
    .header("auth-token", adminToken)
    .header("peak-api-key", "Gdz2niEcRkPa3qpvWs")
    .put("/v1.0/event/1330")
    .then()
    .contentType(ContentType.JSON)
    .extract()
    .response();

  70. Aman Says:

    I got an error while running simple example :

    FAILED: testGetSingleUser
    java.lang.NoClassDefFoundError: org/apache/http/concurrent/Cancellable
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:415)
    at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:376)
    at groovyx.net.http.HTTPBuilder$request.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:132)
    at com.jayway.restassured.internal.RequestSpecificationImpl.sendHttpRequest(RequestSpecificationImpl.groovy:716)
    at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$sendHttpRequest(RequestSpecificationImpl.groovy)
    at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$sendHttpRequest.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.jayway.restassured.internal.RequestSpecificationImpl.sendRequest(RequestSpecificationImpl.groovy:660)
    at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$sendRequest(RequestSpecificationImpl.groovy)
    at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$sendRequest.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:132)
    at com.jayway.restassured.internal.filter.RootFilter.filter(RootFilter.groovy:28)
    at com.jayway.restassured.filter.Filter$filter.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:132)
    at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:45)
    at com.jayway.restassured.filter.FilterContext$next.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at com.jayway.restassured.internal.RequestSpecificationImpl.invokeFilterChain(RequestSpecificationImpl.groovy:551)
    at com.jayway.restassured.internal.RequestSpecificationImpl$invokeFilterChain.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:880)
    at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy)
    at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$applyPathParamsAndSendRequest.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:118)
    at com.jayway.restassured.specification.RequestSender$get.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at com.jayway.restassured.internal.ResponseSpecificationImpl.get(ResponseSpecificationImpl.groovy:236)
    at pagemodel.snap.Rest.testGetSingleUser(Rest.java:20)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:659)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:771)
    at org.testng.TestRunner.run(TestRunner.java:621)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
    at org.testng.SuiteRunner.run(SuiteRunner.java:259)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1199)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1124)
    at org.testng.TestNG.run(TestNG.java:1032)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    Caused by: java.lang.ClassNotFoundException: org.apache.http.concurrent.Cancellable
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 73 more

    Please help me to resolve this.

  71. micha kops Says:

    Hi Aman,

    I think there is a chance that you’re using conflicting versions of the Apache HTTP client (Groovy’s HTTP Builder is just an adapter to https://hc.apache.org/).

    Under the hood, rest-assured uses Groovy (and therefore it is added as a transitive dependency) – maybe you’re using either Groovy or the Apache HTTP Client somewhere in your project?

    In one project for example I have explicitly excluded the Groovy dependency and specified a newer version in my pom.xml like this:

    <dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>1.8.0</version>
    <scope>test</scope>
    <exclusions>
    <exclusion>
    <artifactId>groovy</artifactId>
    <groupId>org.codehaus.groovy</groupId>
    </exclusion>
    </exclusions>
    </dependency>
    [..]
    <dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.1.2</version>
    <scope>test</scope>
    </dependency>

    Please feel free to keep me up-to-date if you still encounter problems here.

    mvn dependency:list and mvn dependency:tree might help you here when analyzing your project’s dependencies.

    Cheers,

    Micha

  72. Rohan Says:

    Hi Micha,

    I am trying out RestAssured with this code –

    String url = “http://”;
    Response result = given().
    header(“Authorization”,”Basic xxxxx”).
    contentType(“application/json”).
    when().
    get(url);
    String jsonResponse = result.asString();

    At the “asString()”, I am getting the following exception
    >> Exception in thread “main” org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected

    The REST response when validated via Postman, it works fine.

    Following are the headers returned –
    Content-Type → application/json
    Date → Tue, 10 Nov 2015 03:00:56 GMT
    Transfer-Encoding → chunked

    Could you guide me on resolving this.
    Appreciate your help.

  73. micha kops Says:

    Hi Rohan,

    is it possible that you’d like to fetch the response body as string? e.g. response.getBody().asString().

    Best wishes,

    Micha

  74. Avinash Says:

    Good Tutorial ,I am beginning to use rest assured in my project ,but for authentication getting a error:
    for method testAuthenticationWorking:
    basic(“admin”, “admin”)
    java.lang.AssertionError: Expected status code doesn’t match actual status code .
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)

  75. micha kops Says:

    Hi Avinash,

    please provide more detailed information here e.g. the corresponding Curl command that manages to establish the connection using basic auth.

  76. Avinash Says:

    I have used the example in this tutorial without changing anything but the authentication is not working rest all is working fine

    expect().statusCode(200)
    .when()
    .with()
    .authentication()
    .basic(“admin”, “admin”)
    .get(“http://localhost:8080/rest-assured-example/service/secure/person”);

    and my web.xml has:

    SecuredRestService
    /service/secure/*
    GET
    POST

    Let only managers use this app

    admin

    admin

    BASIC

  77. micha kops Says:

    Hi Avinash,

    just to be sure – you’re able to access this address in your browser entering the specific credentials? You’re getting a response with status-code 200 when running the following curl command? Afics the URL to the service is not correct http://localhost:8080/rest-assured-example/service/secure/person should be http://localhost:8080/service/secure/person (in my tutorial’s sample server application).

    The following curl command demonstrates this:

    $ curl -vi -uadmin:admin http://localhost:8080/service/secure/person
    * About to connect() to localhost port 8080 (#0)
    * Trying 127.0.0.1... connected
    * Server auth using Basic with user 'admin'
    > GET /service/secure/person HTTP/1.1
    > Authorization: Basic YWRtaW46YWRtaW4=
    > User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
    > Host: localhost:8080
    > Accept: */*
    >
    < HTTP/1.1 200 OK
    HTTP/1.1 200 OK
    < Server: Apache-Coyote/1.1
    Server: Apache-Coyote/1.1
    < Pragma: No-cache
    Pragma: No-cache
    < Cache-Control: no-cache
    Cache-Control: no-cache
    < Expires: Thu, 01 Jan 1970 01:00:00 CET
    Expires: Thu, 01 Jan 1970 01:00:00 CET
    < Content-Type: text/plain
    Content-Type: text/plain
    < Content-Length: 0
    Content-Length: 0
    < Date: Sun, 29 Nov 2015 19:11:26 GMT
    Date: Sun, 29 Nov 2015 19:11:26 GMT

    <
    * Connection #0 to host localhost left intact
    * Closing connection #0

  78. Vikram VI Says:

    Hi Micha,

    Thanks for nice write up , I tried using framework and struck with below issue

    Also please update framework version to 2.8.0 or give link to find latest one.

    I tried below today

    curl -H “X-Access-Token: XXXXXX07236415e5afa181211fdd37e4074c9a936ef28cad079137XXXXXX” -H “X-Client-ID: b1e84f01bc7b80f0f482” https://a.wunderlist.com/api/v1/user

    this works fine , now I want to achieve same in test case

    @Test
    public void oAuth2(){
    given().
    auth().preemptive().oauth2(“XXXXXX07236415e5afa181211fdd37e4074c9a936ef28cad079137XXXXXX”).
    when().
    get(“https://a.wunderlist.com/api/v1/user”).
    then().
    statusCode(200);
    }

    above always returns 403

    How can I pass Client-ID to make is working ?

    Thanks in advance.

    Regards,
    Vikram

  79. Micha Kops Says:

    Hi Vikram,

    I think I’m going to update my tutorial to use a more recent version of the library and to include and OAuth1 and OAuth2 examples :)

    Meanwhile since the authentication process is working when using curl, you could simply replay the steps by specifying each header sent manually .. e.g.

    expect()
    .statusCode(200)
    .given()
    .header("X-Access-Token", "XXXXXX07236415e5afa181211fdd37e4074c9a936ef28cad079137XXXXXX")
    .header("X-Client-ID", "b1e84f01bc7b80f0f482")
    .when()
    .get("https://a.wunderlist.com/api/v1/user");

  80. bhavitha Says:

    Null pointer exception, am getting an exception at “RestAssured.basePath = “http://localhost:8080/rest-assured-example”;”

    @Before
    public void setUp(){
    RestAssured.basePath = “http://localhost:8080/rest-assured-example”;
    }

    tried in different ways to resolve it, the is running on tomcat,

    Exception details:
    java.lang.NullPointerException
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$DgmMethodRecord.loadDgmInfo(GeneratedMetaMethod.java:168)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.registerMethods(MetaClassRegistryImpl.java:185)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.(MetaClassRegistryImpl.java:95)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.(MetaClassRegistryImpl.java:73)
    at groovy.lang.GroovySystem.(GroovySystem.java:36)
    at org.codehaus.groovy.runtime.InvokerHelper.(InvokerHelper.java:65)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.createMap(ScriptBytecodeAdapter.java:623)
    at com.jayway.restassured.internal.ResponseParserRegistrar.(ResponseParserRegistrar.groovy)
    at com.jayway.restassured.RestAssured.(RestAssured.java:349)
    at com.hascode.ra_samples.TestAssured.setUp(TestAssured.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:24)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:127)
    at org.junit.runner.JUnitCore.runClasses(JUnitCore.java:76)
    at com.hascode.ra_samples.TestRunner.main(TestRunner.java:9)

  81. Reema Says:

    Hi Micha,

    Please help me out with Rest Assured integration with ALM .How can i begin it with>

  82. Harish Malik Says:

    Hi Micha,

    I am facing javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure while using rest-assured. I have tried a lot of things but still its not working. Can you have a look at this and let me know if you can help in this?

    Link : http://stackoverflow.com/q/37714696/5587830

  83. Sukhjinder Singh Says:

    Hi,

    I am restAssured Lib to get status code for the web mycode is
    Response response =
    given().get(url)
    .then().extract().response();

    System.out.println(response.getStatusCode());
    return response.getStatusCode();

    When i execute this code I am getting the following error->
    avax.net.ssl.SSLException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.readV3Record(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)

    Please help me around this problem.
    Thanks

  84. Anil Says:

    How do i pass the certificate in headers using Rest Assured

  85. Waheed Ahmed Says:

    Hello James

    Greetings

    I hope you are doing great. James, I am trying to automate below REST API using RestAssured.

    The web service is accessible at: http://qa-takehome.dev.aetion.com:4440
    The web service exposes the following endpoints:

    /login
    /user/
    /user/{id}
    /user/search
    *For all endpoints other than /login an authorization token needs to be passed as an HTTP Header:*

    X-Auth-Token:
    e.g.

    X-Auth-Token: 1234-56789-12345

    /login

    The service exposes a login endpoint ( /login) which takes a POST request with two parameters: username and password.
    Following a successful login, an authentication token will be returned which must be used to make additional requests to the service.

    Example Request:

    /login
    POST
    Body
    {
    “username”: “admin”,
    “password”: “admin”
    }
    Return
    {
    “token”: “1234-56789-…”
    }

    Thing is that on post request on login I will get back token I need to store this token and pass it in susbsquent request. I tried using below code its not working..First .parameters is deprecated not sure how to replace it and with what?Also not sure how to use JsonPath?

    package com.waheed.restassured.restassured;
    import static io.restassured.RestAssured.*;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.ObjectWriter;

    import org.testng.annotations.Test;

    import io.restassured.RestAssured;
    import io.restassured.authentication.PreemptiveBasicAuthScheme;
    import io.restassured.builder.RequestSpecBuilder;
    import io.restassured.path.json.JsonPath;
    import io.restassured.response.Response;
    import io.restassured.specification.RequestSpecification;

    /**
    * Unit test for simple App.
    */
    public class AppTest

    {
    @Test
    public void testStatusCode(){

    String response =
    given()
    .parameters(“username”, wahmed, “password”, wahmed123)
    .auth()
    .preemptive()
    .when()
    .post(“/oauth/token”)
    .asString();

    JsonPath jsonPath = new JsonPath(response);
    String accessToken = jsonPath.getString(“access_token”);

    }
    }

  86. Micha Kops Says:

    Who is James? My name is Micha.

    You might receive the token like this (might add application/json content-type headers though)

    String token = expect().statusCode(200).when().given()
    .parameters("username", "wahmed", "password", "wahmed123").post("/oauth/token").andReturn()
    .jsonPath().get("token").toString();

    In addition you might create a request-spec to reuse-the auth-token-header for the following requests.

  87. Uday Says:

    Hi Micha,

    Thanks for your nice article.

    I am novice to coding, but have little experience in Coding. I know how to launch(.war) files which i did for Jenkins.

    In command prompt, i just give java -jar “path of jenkins.war file” which launches Jenkins.

    Similarly, i wanted to launch or start your sample web service application. For that i downloaded “rest-assured-example.war” file and tried to launch by java -jar “path of this war file”.

    But i am getting “no main manifest attribute, in C:\Users\XXX\Downloads\rest-assured-example.w
    ar”

    Is this is the right process? or can you please help me with some pointers to start this sample application.

    Looking forward to hear from you.

    Thanks,
    Uday

  88. Uday Says:

    Hi Micha,

    Can you help with detailed steps how to configure this sample application?

    Thanks,
    Uday

  89. Micha Kops Says:

    Hi Uday,

    in the Jenkins war-file there is an embedded servlet container included and a main-class entry in the manifest file allows you to start this embedded server but it is NOT the default way to run war-files – it’s important to know that!

    For your use-case you could download and install a decent servlet container like Tomcat (https://tomcat.apache.org/) or Jetty (http://www.eclipse.org/jetty/), start the server and install the war file .. or if you’ve got the build tool Maven (http://maven.apache.org/) installed – what you’re likely to have installed as a Java developer, simply change into the directory of the sample application and run this command: mvn tomcat:run as documented in my tutorial here.

  90. Mohit Says:

    Hello Micha!
    Thanks for the great tutorial!
    I have question for XML – Request URL: /service/persons/xml
    How can I get all the “id” values from all () to use them as a parameter in another request?

    Thanks in advance!
    Mohit

  91. Micha Kops Says:

    Hi Mohit,

    you might add the following lines at the end to obtain an XMLPath reference: .andReturn().xmlPath()

    Cheers,

    Micha

  92. Sanju Says:

    Hi,

    I have a question about the below response.

    Generally if I have to extract just one element, I do like this.

    boolean isJoin = Response.then()
    .contentType(ContentType.JSON) //
    .extract().path(“responseType”).equals(“JOIN”);

    Now my requirement is I would need to extract participantId for the eventType “MEETING_JOINED” and name “b”

    Could you please help in this one?

    “lastSeqNum”: 47727,

    “events”: [
    {
    “eventType”: “MEETING_STARTED”,
    “timestamp”: “2018-01-04T19:21:11.440Z”,

    },
    {
    “eventType”: “MEETING_JOINED”,
    “timestamp”: “2018-01-04T19:21:11.640Z”,
    “participantId”: “d9ivt8n6st6wk5fphbway9b2s”,
    “name”: “b”,

    },
    {
    “eventType”: “CONTENT_CREATED”,
    “timestamp”: “2018-01-04T19:21:11.655Z”,

    },
    {
    “eventType”: “AUDIO_MEETING_STARTED”,
    “timestamp”: “2018-01-04T19:21:12.438Z”
    },
    {
    “eventType”: “MEETING_JOINED”,
    “timestamp”: “2018-01-04T19:26:47.705Z”,
    “participantId”: “j2szhbsmc58laqe3r6nrttre”,
    “name”: “a”,

    }

  93. Micha Kops Says:

    Hi Sanju,
    just use the following JsonPath expression to match the designated JSON nodes and then use extract() and path() to fetch the participantId.
    The path to query for is: $..events[?(@.name == 'b' && @.eventType == 'MEETING_JOINED')].
    I’ve put a snippet for you here: https://bitbucket.org/snippets/hascode/KednyB
    I hope I could help!
    Cheers,
    Micha

  94. Sanju Says:

    Hi Micha,
    Thank You so much for your reply. Appreciate it.

    I have tried the following.
    //Sending request and saving response in a “eventsResp” variable.
    Response eventsResp = util.getAllEventsResponse(Host.authToken);

    JSONArray events = JsonPath.read(eventsResp , “$..events[?(@.name == 'b' && @.eventType == 'MEETING_JOINED')]“);
    System.out.printf(“%d events filtered:\n”, events.size());
    events.forEach(System.out::println);

    Output:

    0 events filtered:

  95. Sanju Says:

    Looks Like Response eventsResp should be converted to Json String.
    Please correct me if I’m wrong.
    Could you please let me know how to do that conversion?

  96. Micha Kops Says:

    I’m not sure what you’re doing now, but you may get the body string from a response by using response.getBody().asString().

  97. Sanju Says:

    Thank You Micha for the response. It worked.

    Now I got a different question.
    Code:
    ————
    JSONArray events = JsonPath.read(jsonString, “$..events[?(@.name == ‘ABC’ && @.eventType == ‘MEETING_JOINED’)]”);
    System.out.println(events);

    Output:
    ————

    [
    {
    “eventType”:”MEETING_JOINED”,
    “timestamp”:”2018-01-07T15:37:41.257Z”,
    “participantId”:”140zd6uigvsbxzw04hv8ed2nc”,
    “name”:”ABC”,
    },
    {
    “eventType”:”MEETING_JOINED”,
    “timestamp”:”2018-01-07T15:39:12.246Z”,
    “participantId”:”3bc9qkw48ucdpwxm4ymxrqjgs”,
    “name”:”ABC”,
    },
    {
    “eventType”:”MEETING_JOINED”,
    “timestamp”:”2018-01-07T15:48:53.299Z”,
    “participantId”:”2ftcj8r5x1u71f6vwyxwv2pan”,
    “name”:”ABC”,
    }
    ]

    I would need to assert this output to make sure it contains participantId:”3bc9qkw48ucdpwxm4ymxrqjgs”.

    Note: we cannot go by index here.

    Could you please clarify when you get a chance?

    Thank You!
    Sanju

  98. Micha Kops Says:

    Hi Sanju,
    why not make the participantId part of the JsonPath query? Otherwise you always have the terminal choice of iterating over your array and checking the values “oldschool” :)

  99. Sanju Says:

    Hi Micha,

    JSONArray events = JsonPath.read(jsonString, “$..events[?(@.name == 'b' && @.eventType == 'MEETING_JOINED')]“);
    System.out.printf(“%d events filtered:\n”, events.size());
    events.forEach(System.out::println);

    If I have to print only the last last one instead of forEach, how to do that?
    Please clarify.

    Thank You!

  100. Micha Kops Says:

    Hi,
    if index-based, then events.get(events.size() – 1), otherwise stream() and filter() might be a choice (java8).

  101. Sanju Says:

    Thank You so much Micha…My script is working fine :)

  102. Micha Kops Says:

    Hi Sanju,

    I’m glad I could help you out! :)

  103. Sanju Says:

    Hi Micha,
    I have one scenario for automation where I should do the following.
    1. Launch the browser url.
    2. Open Chrome Developer tools by F12 to see the requests, responses and cookies
    3. Enter Loginid, Password and submit

    After successful authentication, I would need to get one of the Cookie value from Application column.
    Could you please help me out?

    Thank You!

  104. Micha Kops Says:

    Why do you need to use chrome?

  105. Sanju Says:

    Application supports Only Chrome.

  106. Sanju Says:

    Hi Micha, Without going to Chrome, can you please suggest how to get all cookies using rest assured?

  107. Micha Kops Says:

    Hi Sanju,

    // Get all cookies as simple name-value pairs
    Map<String, String> allCookies = response.getCookies();
    // Get a single cookie value:
    String cookieValue = response.getCookie(“cookieName”);

  108. Sanju Says:

    Hi Micha,
    I have a below String.
    {event=ID, timestamp=2018-03-27, conversationId=default, member=1j8pqklj854}

    Could you please let me know how to convert to JSON String and get the conversationId value?

  109. Micha Kops Says:

    Hi Sanju,
    you could use regular expressions to extract the information needed.

    Cheers,

    Micha

  110. Sanju Says:

    Thank You Micha!

  111. Sunny Says:

    basic(“admin”, “admin”)
    .get(“http://localhost:8080/rest-assured-example/service/secure/person”); getting HTTP Status 401 – Unauthorized

    but i need to validate for 200 ok scenario please help

  112. Manish Says:

    Getting 404 error the war file from the above example https://bitbucket.org/hascode/rest-assured-samples/downloads/rest-assured-example.war,
    if it is moved could you please share the latest url for the same,

  113. Micha Kops Says:

    Hi Manish,

    seems like my Bitbucket repository is gone, please feel free to visit its mirror on GitHub here: https://github.com/hascode/rest-assured-samples

    I haven’t uploaded the sample war file yet but you may simply build it from the sources there.

Search
Categories