Java DSL for easy testing of REST services
npx @tessl/cli install tessl/maven-io-rest-assured--rest-assured@5.5.0REST Assured is a comprehensive Java library that provides a domain-specific language (DSL) for testing and validating REST web services. It brings the simplicity of dynamic languages like Ruby and Groovy to Java, making REST service testing more accessible and readable with fluent API syntax and powerful assertion capabilities.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;For specific classes:
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
// Simple GET request with assertion
get("/users/1").then()
.statusCode(200)
.body("name", equalTo("John Doe"));
// POST request with JSON body
given()
.contentType("application/json")
.body("{\"name\":\"Jane\",\"email\":\"jane@example.com\"}")
.when()
.post("/users")
.then()
.statusCode(201)
.body("id", notNullValue());
// Configuration and fluent API
RestAssured.baseURI = "https://api.example.com";
RestAssured.port = 443;
given()
.auth().basic("username", "password")
.header("Accept", "application/json")
.queryParam("limit", 10)
.when()
.get("/api/users")
.then()
.statusCode(200)
.body("users.size()", greaterThan(0))
.body("users[0].name", containsString("John"));REST Assured is built around several key components:
RestAssured class providing static methods for common HTTP operations and global configurationgiven().when().then() for readable test constructionRequestSpecification interface for configuring HTTP requests (headers, body, auth, etc.)ResponseSpecification interface for defining expected response characteristicsRequestSpecBuilder and ResponseSpecBuilder for creating reusable specificationsCore HTTP request methods with path parameters, query parameters, and various response handling options.
// Static methods for immediate requests
static Response get(String path, Object... pathParams);
static Response post(String path, Object... pathParams);
static Response put(String path, Object... pathParams);
static Response delete(String path, Object... pathParams);
static Response head(String path, Object... pathParams);
static Response patch(String path, Object... pathParams);
static Response options(String path, Object... pathParams);
// Custom HTTP methods
static Response request(Method method, String path, Object... pathParams);
static Response request(String method, String path, Object... pathParams);Fluent API for constructing HTTP requests with headers, parameters, body content, authentication, and configuration.
// Entry points for request building
static RequestSpecification given();
static RequestSpecification with();
static RequestSender when();
interface RequestSpecification {
// Body methods
RequestSpecification body(String body);
RequestSpecification body(Object object);
RequestSpecification body(File file);
// Parameter methods
RequestSpecification param(String parameterName, Object... parameterValues);
RequestSpecification queryParam(String parameterName, Object... parameterValues);
RequestSpecification formParam(String parameterName, Object... parameterValues);
RequestSpecification pathParam(String parameterName, Object parameterValue);
// Header and cookie methods
RequestSpecification header(String headerName, Object headerValue);
RequestSpecification cookie(String cookieName, Object cookieValue);
// Content type and authentication
RequestSpecification contentType(ContentType contentType);
RequestSpecification auth();
}Comprehensive response validation including status codes, headers, cookies, body content, and custom matchers.
// Response validation entry point
static ResponseSpecification expect();
interface ResponseSpecification {
// Status validation
ResponseSpecification statusCode(int expectedStatusCode);
ResponseSpecification statusLine(String expectedStatusLine);
// Body validation
ResponseSpecification body(String path, Matcher<?> matcher);
ResponseSpecification body(String path, Matcher<?> matcher, Object... additionalKeyMatcherPairs);
// Header and cookie validation
ResponseSpecification header(String headerName, Matcher<?> expectedValueMatcher);
ResponseSpecification cookie(String cookieName, Matcher<?> expectedValueMatcher);
}
interface ValidatableResponse {
ValidatableResponse statusCode(int expectedStatusCode);
ValidatableResponse body(String path, Matcher<?> matcher);
ValidatableResponse header(String headerName, Matcher<?> expectedValueMatcher);
ExtractableResponse<Response> extract();
}Support for multiple authentication schemes including basic, digest, OAuth, certificate-based, and form authentication.
// Authentication schemes
static AuthenticationScheme basic(String userName, String password);
static AuthenticationScheme digest(String userName, String password);
static AuthenticationScheme oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken);
static AuthenticationScheme oauth2(String accessToken);
static AuthenticationScheme certificate(String certURL, String password);
static AuthenticationScheme form(String userName, String password);
static PreemptiveAuthProvider preemptive();
interface AuthenticationSpecification {
RequestSpecification basic(String userName, String password);
RequestSpecification digest(String userName, String password);
RequestSpecification oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken);
RequestSpecification oauth2(String accessToken);
RequestSpecification certificate(String certURL, String password);
RequestSpecification form(String userName, String password);
RequestSpecification none();
}Extensive configuration options for HTTP client behavior, SSL settings, logging, object mapping, and global defaults.
// Global configuration fields
static String baseURI;
static int port;
static String basePath;
static AuthenticationScheme authentication;
static RestAssuredConfig config;
static RequestSpecification requestSpecification;
static ResponseSpecification responseSpecification;
// Configuration methods
static void reset();
static void useRelaxedHTTPSValidation();
static void keyStore(String pathToJks, String password);
static void trustStore(String pathToJks, String password);
static void proxy(String host, int port);
class RestAssuredConfig {
SSLConfig getSSLConfig();
HttpClientConfig getHttpClientConfig();
LogConfig getLogConfig();
ObjectMapperConfig getObjectMapperConfig();
JsonConfig getJsonConfig();
XmlConfig getXmlConfig();
}Automatic serialization and deserialization of Java objects to/from JSON and XML using Jackson, Gson, or JAXB.
// Object mapping in requests
RequestSpecification body(Object object);
// Object mapping in responses
<T> T as(Class<T> cls);
<T> T as(TypeRef<T> typeRef);
// Object mapper configuration
enum ObjectMapperType {
JACKSON_1, JACKSON_2, GSON, JAXB
}
interface ObjectMapper {
Object serialize(ObjectMapperSerializationContext context);
<T> T deserialize(ObjectMapperDeserializationContext context);
}Extensible filter system for request/response processing, logging, timing, and custom behavior injection.
interface Filter {
Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx);
}
// Built-in filters
class RequestLoggingFilter implements Filter;
class ResponseLoggingFilter implements Filter;
class SessionFilter implements Filter;
class CookieFilter implements Filter;
// Filter configuration
RequestSpecification filter(Filter filter);
static void filters(Filter filter, Filter... additionalFilters);// Core response interface
interface Response extends ResponseBody<Response>, ResponseOptions<Response>,
Validatable<ValidatableResponse, Response> {
int getStatusCode();
String getStatusLine();
Headers getHeaders();
Cookies getCookies();
String getContentType();
long getTime();
}
// HTTP method enumeration
enum Method {
GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, TRACE
}
// Content type enumeration with common MIME types
enum ContentType {
JSON("application/json"),
XML("application/xml"),
HTML("text/html"),
TEXT("text/plain"),
URLENC("application/x-www-form-urlencoded"),
MULTIPART("multipart/form-data");
}
// HTTP headers and cookies collections
class Headers implements Iterable<Header> {
Header get(String name);
List<Header> getList(String name);
boolean hasHeaderWithName(String name);
}
class Cookies implements Iterable<Cookie> {
Cookie get(String name);
boolean hasCookieWithName(String name);
}
// Header and cookie individual representations
class Header {
String getName();
String getValue();
}
class Cookie {
String getName();
String getValue();
String getDomain();
String getPath();
Date getExpiryDate();
boolean isSecured();
boolean isHttpOnly();
}