com.jayway.restassured
Class RestAssured

java.lang.Object
  extended by com.jayway.restassured.RestAssured

public class RestAssured
extends Object

REST Assured is a Java DSL for simplifying testing of REST based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE and HEAD requests and to verify the response of these requests. Usage examples:

  1. Assume that the GET request (to http://localhost:8080/lotto) returns JSON as:
     {
     "lotto":{
       "lottoId":5,
       "winning-numbers":[2,45,34,23,7,5,3],
       "winners":[{
         "winnerId":23,
         "numbers":[2,45,34,23,3,5]
       },{
         "winnerId":54,
         "numbers":[52,3,12,11,18,22]
       }]
      }
     }
     
    REST assured can then help you to easily make the GET request and verify the response. E.g. if you want to verify that lottoId is equal to 5 you can do like this:
     expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");
     
    or perhaps you want to check that the winnerId's are 23 and 54:
      expect().body("lotto.winners.winnerId", hasItems(23, 54)).when().get("/lotto");
     
  2. XML can be verified in a similar way. Imagine that a POST request to http://localhost:8080/greetXML returns:
     <greeting>
         <firstName>{params("firstName")}</firstName>
         <lastName>{params("lastName")}</lastName>
       </greeting>
     
    i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. You can easily perform and verify e.g. the firstName with REST assured:
     with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
     
    If you want to verify both firstName and lastName you may do like this:
     with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).and().body("greeting.lastName", equalTo("Doe")).when().post("/greetXML");
     
    or a little shorter:
     with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John"), "greeting.lastName", equalTo("Doe")).when().post("/greetXML");
     
  3. You can also verify XML responses using x-path. For example:
     expect().body(hasXPath("/greeting/firstName", containsString("Jo"))).given().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML");
     
    or
     expect().body(hasXPath("/greeting/firstName[text()='John']")).with().parameters("firstName", "John", "lastName", "Doe").post("/greetXML");
     
  4. XML response bodies can also be verified against an XML Schema (XSD) or DTD.
    XSD example:
     expect().body(matchesXsd(xsd)).when().get("/carRecords");
     
    DTD example:
     expect().body(matchesDtd(dtd)).when().get("/videos");
     
    matchesXsd and matchesDtd are Hamcrest matchers which you can import from RestAssuredMatchers.
  5. Besides specifying request parameters you can also specify headers, cookies, body and content type.
    • Cookie:
       given().cookie("username", "John").then().expect().body(equalTo("username")).when().get("/cookie");
       
    • Headers:
       given().header("MyHeader", "Something").and(). ..
       given().headers("MyHeader", "Something", "MyOtherHeader", "SomethingElse").and(). ..
       
    • Content Type:
       given().contentType(ContentType.TEXT). ..
       
    • Body:
       given().request().body("some body"). .. // Works for POST and PUT requests
       given().request().body(new byte[]{42}). .. // Works for POST
       
  6. You can also verify status code, status line, cookies, headers, content type and body.
    • Cookie:
       expect().cookie("cookieName", "cookieValue"). ..
       expect().cookies("cookieName1", "cookieValue1", "cookieName2", "cookieValue2"). ..
       expect().cookies("cookieName1", "cookieValue1", "cookieName2", containsString("Value2")). ..
       
    • Status:
       expect().statusCode(200). ..
       expect().statusLine("something"). ..
       expect().statusLine(containsString("some")). ..
       
    • Headers:
       expect().header("headerName", "headerValue"). ..
       expect().headers("headerName1", "headerValue1", "headerName2", "headerValue2"). ..
       expect().headers("headerName1", "headerValue1", "headerName2", containsString("Value2")). ..
       
    • Content-Type:
       expect().contentType(ContentType.JSON). ..
       
    • REST Assured also supports mapping a request body and response body to and from a Java object using Jackson, Gson or JAXB. Usage example:
       Greeting greeting = get("/greeting").as(Greeting.class);
       
       Greeting greeting = new Greeting();
       greeting.setFirstName("John");
       greeting.setLastName("Doe");
      
       given().body(greeting).when().post("/greeting");
       
      See the javadoc for the body method for more details.
    • Full body/content matching:
       expect().body(equalsTo("something")). ..
       expect().content(equalsTo("something")). .. // Same as above
       
  7. REST assured also supports some authentication schemes, for example basic authentication:
     given().auth().basic("username", "password").expect().statusCode(200).when().get("/secured/hello");
     
    Other supported schemes are OAuth and certificate authentication.
  8. By default REST assured assumes host localhost and port 8080 when doing a request. If you want a different port you can do:
     given().port(80). ..
     
    or simply:
     .. when().get("http://myhost.org:80/doSomething");
     
  9. Parameters can also be set directly on the url:
     ..when().get("/name?firstName=John&lastName=Doe");
     
  10. You can use the XmlPath or JsonPath to easily parse XML or JSON data from a response.
    1. XML example:
                  String xml = post("/greetXML?firstName=John&lastName=Doe").andReturn().asString();
                  // Now use XmlPath to get the first and last name
                  String firstName = with(xml).get("greeting.firstName");
                  String lastName = with(xml).get("greeting.firstName");
      
                  // or a bit more efficiently:
                  XmlPath xmlPath = new XmlPath(xml).setRoot("greeting");
                  String firstName = xmlPath.get("firstName");
                  String lastName = xmlPath.get("lastName");
              
    2. JSON example:
                  String json = get("/lotto").asString();
                  // Now use JsonPath to get data out of the JSON body
                  int lottoId = with(json).getInt("lotto.lottoId);
                  List winnerIds = with(json).get("lotto.winners.winnerId");
      
                  // or a bit more efficiently:
                  JsonPath jsonPath = new JsonPath(json).setRoot("lotto");
                  int lottoId = jsonPath.getInt("lottoId");
                  List winnderIds = jsonPath.get("winnders.winnderId");
              
  11. REST Assured providers predefined parsers for e.g. HTML, XML and JSON. But you can parse other kinds of content by registering a predefined parser for unsupported content-types by using:
     RestAssured.registerParser(<content-type>, <parser>);
     
    E.g. to register that content-type 'application/vnd.uoml+xml' should be parsed using the XML parser do:
     RestAssured.registerParser("application/vnd.uoml+xml", Parser.XML);
     
    You can also unregister a parser using:
     RestAssured.unregisterParser("application/vnd.uoml+xml");
     
    If can also specify a default parser for all content-types that do not match a pre-defined or registered parser. This is also useful if the response doesn't contain a content-type at all:
     RestAssured.defaultParser = Parser.JSON;
     
  12. If you need to re-use a specification in multiple tests or multiple requests you can use the ResponseSpecBuilder and RequestSpecBuilder like this:
     RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build();
     ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
    
     given().
             spec(requestSpec).
     expect().
             spec(responseSpec).
             body("x.y.z", equalTo("something")).
     when().
            get("/something");
     
  13. You can also create filters and add to the request specification. 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. E.g.
     given().filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(302)). ..
     
    will log/print the response body to after each request.
  14. You can also change the default base URI, base path, port, authentication scheme, root path and filters for all subsequent requests:
     RestAssured.baseURI = "http://myhost.org";
     RestAssured.port = 80;
     RestAssured.basePath = "/resource";
     RestAssured.authentication = basic("username", "password");
     RestAssured.rootPath = "store.book";
     
    This means that a request like e.g. get("/hello") goes to: http://myhost.org:8080/resource/hello which basic authentication credentials "username" and "password". See rootPath for more info about setting the root paths, filters(java.util.List) for setting default filters and keystore(String, String) for setting the default keystore when using SSL.
    You can reset to the standard baseURI (localhost), basePath (empty), standard port (8080), default authentication scheme (none), default parser (none) and default root path (empty string) using:
     RestAssured.reset();
     

In order to use REST assured effectively it's recommended to statically import methods from the following classes:


Field Summary
static AuthenticationScheme authentication
          Set an authentication scheme that should be used for each request.
static String basePath
          A base path that's added to the baseURI by REST assured when making requests.
static String baseURI
          The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request.
static RestAssuredConfig config
          Define a configuration for redirection settings and http client parameters (default is null).
static AuthenticationScheme DEFAULT_AUTH
           
static String DEFAULT_BODY_ROOT_PATH
           
static String DEFAULT_PATH
           
static int DEFAULT_PORT
           
static String DEFAULT_SESSION_ID_VALUE
           
static String DEFAULT_URI
           
static boolean DEFAULT_URL_ENCODING_ENABLED
           
static Parser defaultParser
          Specify a default parser.
static int port
          The port that's used by REST assured when it's left out of the specified URI when making a request.
static RequestSpecification requestSpecification
          Specify a default request specification that will be sent with each request.
static ResponseSpecification responseSpecification
          Specify a default response specification that will be sent with each request.
static String rootPath
          Set the default root path of the response body so that you don't need to write the entire path for each expectation.
static String sessionId
          Set the default session id value that'll be used for each request.
static boolean urlEncodingEnabled
          Specifies if Rest Assured should url encode the URL automatically.
 
Constructor Summary
RestAssured()
           
 
Method Summary
static AuthenticationScheme basic(String userName, String password)
          Create a http basic authentication scheme.
static AuthenticationScheme certificate(String certURL, String password)
          Sets a certificate to be used for SSL authentication.
static Response delete(String path, Map<String,?> pathParams)
          Perform a DELETE request to a path.
static Response delete(String path, Object... pathParams)
          Perform a DELETE request to a path.
static AuthenticationScheme digest(String userName, String password)
          Use http digest authentication.
static ResponseSpecification expect()
          Start building the response part of the test com.jayway.restassured.specification.
static List<Filter> filters()
           
static void filters(Filter filter, Filter... additionalFilters)
          The the default filters to apply to each request.
static void filters(List<Filter> filters)
          The the default filters to apply to each request.
static AuthenticationScheme form(String userName, String password)
          Use form authentication.
static AuthenticationScheme form(String userName, String password, FormAuthConfig config)
          Use form authentication with the supplied configuration.
static Response get(String path, Map<String,?> pathParams)
          Perform a GET request to a path.
static Response get(String path, Object... pathParams)
          Perform a GET request to a path.
static RequestSpecification given()
          Start building the request part of the test com.jayway.restassured.specification.
static RequestSender given(RequestSpecification requestSpecification, ResponseSpecification responseSpecification)
          When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines.
static Response head(String path, Map<String,?> pathParams)
          Perform a HEAD request to a path.
static Response head(String path, Object... pathParams)
          Perform a HEAD request to a path.
static KeystoreSpec keystore()
           
static KeystoreSpec keystore(File pathToJks, String password)
          Use a keystore located on the file-system.
static KeystoreSpec keystore(String password)
          Uses the user default keystore stored in @{user.home}/.keystore
static KeystoreSpec keystore(String pathToJks, String password)
          The following documentation is taken from http://groovy.codehaus.org/modules/http-builder/doc/ssl.html:
static AuthenticationScheme oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken)
          Excerpt from the HttpBuilder docs:
OAuth sign the request.
static Response post(String path, Map<String,?> pathParams)
          Perform a POST request to a path.
static Response post(String path, Object... pathParams)
          Perform a POST request to a path.
static PreemptiveAuthProvider preemptive()
          Return the http preemptive authentication specification for setting up preemptive authentication requests.
static Response put(String path, Object... pathParams)
          Perform a PUT request to a path.
static void registerParser(String contentType, Parser parser)
          Register a custom content-type to be parsed using a predefined parser.
static Object requestContentType()
           
static void requestContentType(ContentType contentType)
          Specify the default content type
static void requestContentType(String contentType)
          Specify the default content type
static void reset()
          Resets the baseURI, basePath, port, authentication and rootPath, requestContentType(com.jayway.restassured.http.ContentType), responseContentType(com.jayway.restassured.http.ContentType), filters(java.util.List), requestSpecification, responseSpecification.
static Object responseContentType()
           
static void responseContentType(ContentType contentType)
          Specify the default content type (also sets the accept header).
static void responseContentType(String contentType)
          Specify the default content type (also sets the accept header).
static void unregisterParser(String contentType)
          Unregister the parser associated with the provided content-type
static RequestSpecification with()
          Start building the request part of the test com.jayway.restassured.specification.
static List<Argument> withArgs(Object firstArgument, Object... additionalArguments)
          Slightly shorter version of withArguments(Object, Object...).
static List<Argument> withArguments(Object firstArgument, Object... additionalArguments)
          Create a list of arguments that can be used to create parts of the path in a body/content expression.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_URI

public static final String DEFAULT_URI
See Also:
Constant Field Values

DEFAULT_BODY_ROOT_PATH

public static final String DEFAULT_BODY_ROOT_PATH
See Also:
Constant Field Values

DEFAULT_PORT

public static final int DEFAULT_PORT
See Also:
Constant Field Values

DEFAULT_PATH

public static final String DEFAULT_PATH
See Also:
Constant Field Values

DEFAULT_AUTH

public static final AuthenticationScheme DEFAULT_AUTH

DEFAULT_URL_ENCODING_ENABLED

public static final boolean DEFAULT_URL_ENCODING_ENABLED
See Also:
Constant Field Values

DEFAULT_SESSION_ID_VALUE

public static final String DEFAULT_SESSION_ID_VALUE

baseURI

public static String baseURI
The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request. Default value is "http://localhost".


port

public static int port
The port that's used by REST assured when it's left out of the specified URI when making a request. Default value is 8080.


basePath

public static String basePath
A base path that's added to the baseURI by REST assured when making requests. E.g. let's say that the baseURI is http://localhost and basePath is /resource then
 ..when().get("/something");
 
will make a request to http://localhost/resource. Default basePath value is empty.


urlEncodingEnabled

public static boolean urlEncodingEnabled
Specifies if Rest Assured should url encode the URL automatically. Usually this is a recommended but in some cases e.g. the query parameters are already be encoded before you provide them to Rest Assured then it's useful to disable URL encoding. For example:
 RestAssured.baseURI = "https://jira.atlassian.com";
 RestAssured.port = 443;
 RestAssured.urlEncodingEnabled = false; // Because "query" is already url encoded
 String query = "project%20=%20BAM%20AND%20issuetype%20=%20Bug";
 String response = get("/rest/api/2.0.alpha1/search?jql={q}",query).andReturn().asString();
 ...
 
The query is already url encoded so you need to disable Rest Assureds url encoding to prevent double encoding.


authentication

public static AuthenticationScheme authentication
Set an authentication scheme that should be used for each request. By default no authentication is used. If you have specified an authentication scheme and wish to override it for a single request then you can do this using:
     given().auth().none()..
 


config

public static RestAssuredConfig config
Define a configuration for redirection settings and http client parameters (default is null). E.g.
 RestAssured.config = config().redirect(redirectConfig().followRedirects(true).and().maxRedirects(0));
 
config() can be statically imported from RestAssuredConfig.


rootPath

public static String rootPath
Set the default root path of the response body so that you don't need to write the entire path for each expectation. E.g. instead of writing:
 expect().
          body("x.y.firstName", is(..)).
          body("x.y.lastName", is(..)).
          body("x.y.age", is(..)).
          body("x.y.gender", is(..)).
 when().
          get(..);
you can use a root and do:
 RestAssured.rootPath = "x.y";
 expect().
          body("firstName", is(..)).
          body("lastName", is(..)).
          body("age", is(..)).
          body("gender", is(..)).
 when().
          get(..);
 


requestSpecification

public static RequestSpecification requestSpecification
Specify a default request specification that will be sent with each request. E,g.
 RestAssured.requestSpecification = new RequestSpecBuilder().addParameter("parameter1", "value1").build();
 
means that for each request by Rest Assured "parameter1" will be equal to "value1".


defaultParser

public static Parser defaultParser
Specify a default parser. This parser will be used if the response content-type doesn't match any pre-registered or custom registered parsers. Also useful if the response doesn't contain a content-type at all.


responseSpecification

public static ResponseSpecification responseSpecification
Specify a default response specification that will be sent with each request. E,g.
 RestAssured.responseSpecification = new ResponseSpecBuilder().expectStatusCode(200).build();
 
means that for each response Rest Assured will assert that the status code is equal to 200.


sessionId

public static String sessionId
Set the default session id value that'll be used for each request. This value will be set in the SessionConfig so it'll override the session id value previously defined there (if any). If you need to change the sessionId cookie name you need to configure and supply the SessionConfig to RestAssured.config.

Constructor Detail

RestAssured

public RestAssured()
Method Detail

keystore

public static KeystoreSpec keystore(String pathToJks,
                                    String password)
The following documentation is taken from http://groovy.codehaus.org/modules/http-builder/doc/ssl.html:

SSL Configuration

SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information.

SSLPeerUnverifiedException

If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so:
 $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt
 Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
 Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
 Serial number: 1
 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020
 Certificate fingerprints:
 MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC
 SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45
 Signature algorithm name: MD5withRSA
 Version: 3
 ....
 
Now, import that into a Java keystore file:
 $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore.jks -storepass test1234
 Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
 Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
 Serial number: 1
 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020
 Certificate fingerprints:
 MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC
 SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45
 Signature algorithm name: MD5withRSA
 Version: 3
 ...
 Trust this certificate? [no]:  yes
 Certificate was added to keystore
 
Now you want to use this truststore in your client:
 RestAssured.keystore("/truststore.jks", "test1234");
 
or
 given().keystore("/truststore.jks", "test1234"). ..
 

Parameters:
pathToJks - The path to the JKS. REST Assured will first look in the classpath and if not found it will look for the JKS in the local file-system
password - The store pass

keystore

public static KeystoreSpec keystore(File pathToJks,
                                    String password)
Use a keystore located on the file-system. See keystore(String, String) for more details.

Parameters:
pathToJks - The path to JKS file on the file-system
password - The password for the keystore
Returns:
The request specification
See Also:
keystore(String, String)

keystore

public static KeystoreSpec keystore(String password)
Uses the user default keystore stored in @{user.home}/.keystore

Parameters:
password - - Use null for no password
Returns:

filters

public static void filters(List<Filter> filters)
The the default filters to apply to each request.

Parameters:
filters - The filter list

filters

public static void filters(Filter filter,
                           Filter... additionalFilters)
The the default filters to apply to each request.

Parameters:
filter - The filter to set
additionalFilters - An optional array of additional filters to set

filters

public static List<Filter> filters()
Returns:
The current default filters

requestContentType

public static Object requestContentType()

responseContentType

public static Object responseContentType()

keystore

public static KeystoreSpec keystore()

requestContentType

public static void requestContentType(ContentType contentType)
Specify the default content type

Parameters:
contentType - The content type

requestContentType

public static void requestContentType(String contentType)
Specify the default content type

Parameters:
contentType - The content type

responseContentType

public static void responseContentType(ContentType contentType)
Specify the default content type (also sets the accept header).

Parameters:
contentType - The content type

responseContentType

public static void responseContentType(String contentType)
Specify the default content type (also sets the accept header).

Parameters:
contentType - The content type

expect

public static ResponseSpecification expect()
Start building the response part of the test com.jayway.restassured.specification. E.g.
 expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");
 
will expect that the response body for the GET request to "/lotto" should contain JSON or XML which has a lottoId equal to 5.

Returns:
A response com.jayway.restassured.specification.

with

public static RequestSpecification with()
Start building the request part of the test com.jayway.restassured.specification. E.g.
 with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
 
will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John. The only difference between with() and given() is syntactical.

Returns:
A request specification.

withArguments

public static List<Argument> withArguments(Object firstArgument,
                                           Object... additionalArguments)
Create a list of arguments that can be used to create parts of the path in a body/content expression. This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example:
 String someSubPath = "else";
 int index = 1;
 expect().body("something.%s[%d]", withArgs(someSubPath, index), equalTo("some value")). ..
 
or if you have complex root paths and don't wish to duplicate the path for small variations:
 expect().
          root("filters.filterConfig[%d].filterConfigGroups.find { it.name == 'Gold' }.includes").
          body("", withArgs(0), hasItem("first")).
          body("", withArgs(1), hasItem("second")).
          ..
 
The key and arguments follows the standard formatting syntax of Java.

Returns:
A list of arguments that can be used to build up the

withArgs

public static List<Argument> withArgs(Object firstArgument,
                                      Object... additionalArguments)
Slightly shorter version of withArguments(Object, Object...).

Returns:
A list of arguments.
See Also:
withArguments(Object, Object...)

given

public static RequestSpecification given()
Start building the request part of the test com.jayway.restassured.specification. E.g.
 given().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
 
will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John. The only difference between with() and given() is syntactical.

Returns:
A request specification.

given

public static RequestSender given(RequestSpecification requestSpecification,
                                  ResponseSpecification responseSpecification)
When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines. You can then pass the response and request specifications to this method. E.g.
 RequestSpecification requestSpecification = with().parameters("firstName", "John", "lastName", "Doe");
 ResponseSpecification responseSpecification = expect().body("greeting", equalTo("Greetings John Doe"));
 given(requestSpecification, responseSpecification).get("/greet");
 
This will perform a GET request to "/greet" and verify it according to the responseSpecification.

Returns:
A test com.jayway.restassured.specification.

get

public static Response get(String path,
                           Object... pathParams)
Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do get("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.
Returns:
The response of the GET request. The response can only be returned if you don't use any REST Assured response expectations.

get

public static Response get(String path,
                           Map<String,?> pathParams)
Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters.
Returns:
The response of the GET request. The response can only be returned if you don't use any REST Assured response expectations.

post

public static Response post(String path,
                            Object... pathParams)
Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do post("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

post

public static Response post(String path,
                            Map<String,?> pathParams)
Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

put

public static Response put(String path,
                           Object... pathParams)
Perform a PUT request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do put("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

delete

public static Response delete(String path,
                              Object... pathParams)
Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do delete("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

delete

public static Response delete(String path,
                              Map<String,?> pathParams)
Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

head

public static Response head(String path,
                            Object... pathParams)
Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

head

public static Response head(String path,
                            Map<String,?> pathParams)
Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:
path - The path to send the request to.
pathParams - The path parameters.
Returns:
The response of the request. The response can only be returned if you don't use any REST Assured response expectations.

basic

public static AuthenticationScheme basic(String userName,
                                         String password)
Create a http basic authentication scheme.

Parameters:
userName - The user name.
password - The password.
Returns:
The authentication scheme

form

public static AuthenticationScheme form(String userName,
                                        String password)
Use form authentication. Rest Assured will try to parse the response login page and determine and try find the action, username and password input field automatically.

Note that the request will be much faster if you also supply a form auth configuration.

Parameters:
userName - The user name.
password - The password.
Returns:
The authentication scheme
See Also:
form(String, String, com.jayway.restassured.authentication.FormAuthConfig)

form

public static AuthenticationScheme form(String userName,
                                        String password,
                                        FormAuthConfig config)
Use form authentication with the supplied configuration.

Parameters:
userName - The user name.
password - The password.
config - The form authentication config
Returns:
The authentication scheme

preemptive

public static PreemptiveAuthProvider preemptive()
Return the http preemptive authentication specification for setting up preemptive authentication requests. This means that the authentication details are sent in the request header regardless if the server challenged for authentication or not.

Returns:
The authentication scheme

certificate

public static AuthenticationScheme certificate(String certURL,
                                               String password)
Sets a certificate to be used for SSL authentication. See Class.getResource(String) for how to get a URL from a resource on the classpath.

Parameters:
certURL - URL to a JKS keystore where the certificate is stored.
password - password to decrypt the keystore
Returns:
The authentication scheme

digest

public static AuthenticationScheme digest(String userName,
                                          String password)
Use http digest authentication.

Parameters:
userName - The user name.
password - The password.
Returns:
The authentication scheme

oauth

public static AuthenticationScheme oauth(String consumerKey,
                                         String consumerSecret,
                                         String accessToken,
                                         String secretToken)
Excerpt from the HttpBuilder docs:
OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. All requests to all domains will be signed for this instance. This assumes you've already generated an accessToken and secretToken for the site you're targeting. For More information on how to achieve this, see the Signpost documentation.

Parameters:
consumerKey -
consumerSecret -
accessToken -
secretToken -
Returns:
The authentication scheme

registerParser

public static void registerParser(String contentType,
                                  Parser parser)
Register a custom content-type to be parsed using a predefined parser. E.g. let's say you want parse content-type application/vnd.uoml+xml with the XML parser to be able to verify the response using the XML dot notations:
 expect().body("document.child", equalsTo("something"))..
 
Since application/vnd.uoml+xml is not registered to be processed by the XML parser by default you need to explicitly tell REST Assured to use this parser before making the request:
 RestAssured.registerParser("application/vnd.uoml+xml, Parser.XML");
 

Parameters:
contentType - The content-type to register
parser - The parser to use when verifying the response.

unregisterParser

public static void unregisterParser(String contentType)
Unregister the parser associated with the provided content-type

Parameters:
contentType - The content-type associated with the parser to unregister.

reset

public static void reset()
Resets the baseURI, basePath, port, authentication and rootPath, requestContentType(com.jayway.restassured.http.ContentType), responseContentType(com.jayway.restassured.http.ContentType), filters(java.util.List), requestSpecification, responseSpecification. keystore(String, String), urlEncodingEnabled , config and sessionId to their default values of "http://localhost", "", 8080, no authentication, "", null, null, "empty list", null, null, none, true, null, null



Copyright © 2010-2012. All Rights Reserved.