Zum Inhalt

_

_ _

_

REST Assured Cheatsheet

• Installation

Maven Installation (pom.xml)

<dependencies>
    <!-- Core REST Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Schema Validation -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-path</artifactId>
        <version>5.4.0</version>
    </dependency>

    <!-- XML Path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>xml-path</artifactId>
        <version>5.4.0</version>
    </dependency>
</dependencies>

Gradle Installation (build.gradle)

dependencies {
    testImplementation 'io.rest-assured:rest-assured:5.4.0'
    testImplementation 'io.rest-assured:json-schema-validator:5.4.0'
    testImplementation 'io.rest-assured:json-path:5.4.0'
    testImplementation 'io.rest-assured:xml-path:5.4.0'
}

Platform-Specific Voraussetzungen

Platform Installation Command
Ubuntu/Debian INLINE_CODE_17
macOS INLINE_CODE_18
Windows INLINE_CODE_19 (using Chocolatey)
Verify Java INLINE_CODE_20
Verify Maven INLINE_CODE_21
_
Erforderliche Importe
// Static imports for fluent API
import static io.rest-assured.RestAssured.*;
import static io.rest-assured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

// Additional imports
import io.rest-assured.response.Response;
import io.rest-assured.specification.RequestSpecification;
import io.rest-assured.http.ContentType;

Standard HTTP Methoden

Command Description
INLINE_CODE_22 Execute GET request
INLINE_CODE_23 Execute POST request
INLINE_CODE_24 Execute PUT request
INLINE_CODE_25 Execute PATCH request
INLINE_CODE_26 Execute DELETE request
INLINE_CODE_27 Execute HEAD request
INLINE_CODE_28 Execute OPTIONS request
INLINE_CODE_29 Shorthand GET without given/when
INLINE_CODE_30 Shorthand POST without given/when
INLINE_CODE_31 Shorthand DELETE without given/when
_
Beschreibung anfordern
Command Description
INLINE_CODE_32 Set base URI for requests
INLINE_CODE_33 Set base path for all endpoints
INLINE_CODE_34 Set port number
INLINE_CODE_35 Set Content-Type header
INLINE_CODE_36 Set Accept header
INLINE_CODE_37 Add single header
INLINE_CODE_38 Add multiple headers from map
INLINE_CODE_39 Add cookie
INLINE_CODE_40 Add query parameter
INLINE_CODE_41 Add multiple query parameters
INLINE_CODE_42 Add path parameter
INLINE_CODE_43 Add form parameter
INLINE_CODE_44 Set request body (auto-serialized)
INLINE_CODE_45 Set raw JSON/XML body
INLINE_CODE_46 Add multipart file upload
_
Antwortvalidierung
Command Description
INLINE_CODE_47 Assert HTTP status code
INLINE_CODE_48 Assert full status line
INLINE_CODE_49 Assert response content type
INLINE_CODE_50 Assert header value
INLINE_CODE_51 Assert JSON field equals value
INLINE_CODE_52 Assert field is not null
INLINE_CODE_53 Assert array/list size
INLINE_CODE_54 Assert array contains items
INLINE_CODE_55 Assert string contains text
INLINE_CODE_56 Assert numeric comparison
INLINE_CODE_57 Assert regex match
INLINE_CODE_58 Assert response time < 2000ms
INLINE_CODE_59 Explicit assertion mode
INLINE_CODE_60 Log entire response
INLINE_CODE_61 Log only on error

JSON Path Validation

Command Description
INLINE_CODE_62 Validate nested field
INLINE_CODE_63 Validate array element
INLINE_CODE_64 Validate array field values
INLINE_CODE_65 Validate array size
INLINE_CODE_66 Filter with Groovy closure
INLINE_CODE_67 Find specific element
INLINE_CODE_68 JsonPath expression
INLINE_CODE_69 Spread operator for collections
INLINE_CODE_70 Escape field with dots
INLINE_CODE_71 Transform collection

Antwortextraktion

Command Description
INLINE_CODE_72 Extract full Response object
INLINE_CODE_73 Extract response as String
INLINE_CODE_74 Extract specific field value
INLINE_CODE_75 Get JsonPath object
INLINE_CODE_76 Get XmlPath object
INLINE_CODE_77 Deserialize to object
INLINE_CODE_78 Extract status code
INLINE_CODE_79 Extract header value
INLINE_CODE_80 Extract cookie value
INLINE_CODE_81 Extract response time

Erweiterte Authentifizierung

Command Description
INLINE_CODE_82 HTTP Basic authentication
INLINE_CODE_83 HTTP Digest authentication
INLINE_CODE_84 Form-based authentication
INLINE_CODE_85 OAuth 2.0 Bearer token
INLINE_CODE_86 Preemptive Basic auth
INLINE_CODE_87 Explicitly no authentication
INLINE_CODE_88 Manual Bearer token
INLINE_CODE_89 Custom API key auth

Spezifikationen anfordern (Reusable)

// Create reusable specification
RequestSpecification requestSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .setBasePath("/v1")
    .addHeader("Authorization", "Bearer token")
    .setContentType(ContentType.JSON)
    .build();

// Use specification
given()
    .spec(requestSpec)
    .when()
    .get("/users");
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_90__ | Create request specification builder |
| __INLINE_CODE_91__ | Set base URI in spec |
| __INLINE_CODE_92__ | Set base path in spec |
| __INLINE_CODE_93__ | Add header to spec |
| __INLINE_CODE_94__ | Set content type in spec |
| __INLINE_CODE_95__ | Add query param to spec |
| __INLINE_CODE_96__ | Set authentication in spec |
| __INLINE_CODE_97__ | Build the specification |
| __INLINE_CODE_98__ | Apply specification to request |
_
Antwort-Spezifikationen (Reusable)

```java
// Create reusable response specification
ResponseSpecification responseSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .expectResponseTime(lessThan(2000L))
    .build();

// Use specification
given()
    .when()
    .get("/users")
    .then()
    .spec(responseSpec);
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_99__ | Create response specification builder |
| __INLINE_CODE_100__ | Expect status code in spec |
| __INLINE_CODE_101__ | Expect content type in spec |
| __INLINE_CODE_102__ | Expect header in spec |
| __INLINE_CODE_103__ | Expect response time constraint |
| __INLINE_CODE_104__ | Expect body validation |
| __INLINE_CODE_105__ | Build the specification |
| __INLINE_CODE_106__ | Apply specification to response |
_
(Login)

| Command | Description |
|---------|-------------|
| __INLINE_CODE_107__ | Log all request details |
| __INLINE_CODE_108__ | Log request body only |
| __INLINE_CODE_109__ | Log request headers only |
| __INLINE_CODE_110__ | Log request cookies only |
| __INLINE_CODE_111__ | Log request parameters only |
| __INLINE_CODE_112__ | Log HTTP method only |
| __INLINE_CODE_113__ | Log request URI only |
| __INLINE_CODE_114__ | Log request if validation fails |
| __INLINE_CODE_115__ | Log all response details |
| __INLINE_CODE_116__ | Log response body only |
| __INLINE_CODE_117__ | Log response headers only |
| __INLINE_CODE_118__ | Log response status only |
| __INLINE_CODE_119__ | Log response only on error |
| __INLINE_CODE_120__ | Conditional logging by status |
| __INLINE_CODE_121__ | Conditional logging by matcher |
_
JSON Schema Validierung

```java
import static io.rest-assured.module.jsv.JsonSchemaValidator.*;

// Validate against JSON schema
given()
    .when()
    .get("/users/1")
    .then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath("user-schema.json"));
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_122__ | Validate against schema in classpath |
| __INLINE_CODE_123__ | Validate against schema file |
| __INLINE_CODE_124__ | Validate against schema string |
| __INLINE_CODE_125__ | Static import for validation |
_
XML Path Validation

| Command | Description |
|---------|-------------|
| __INLINE_CODE_126__ | Validate XML element |
| __INLINE_CODE_127__ | Validate XML attribute |
| __INLINE_CODE_128__ | Validate XML list size |
| __INLINE_CODE_129__ | Validate XML list element |
| __INLINE_CODE_130__ | XPath validation |
| __INLINE_CODE_131__ | XPath existence check |
_
Multipart/Form-Daten

```java
// File upload
given()
    .multiPart("file", new File("test.pdf"))
    .multiPart("description", "Test file")
    .when()
    .post("/upload");

// Multiple files
given()
    .multiPart("file1", new File("test1.pdf"))
    .multiPart("file2", new File("test2.pdf"))
    .when()
    .post("/upload");
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_132__ | Upload file |
| __INLINE_CODE_133__ | Upload file with MIME type |
| __INLINE_CODE_134__ | Add text multipart field |
| __INLINE_CODE_135__ | Upload byte array |
| __INLINE_CODE_136__ | Add form parameter |
| __INLINE_CODE_137__ | Add multiple form parameters |
_
Filter (Request/Response Interceptors)

```java
// Custom filter
given()
    .filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                             FilterableResponseSpecification responseSpec,
                             FilterContext ctx) {
            // Modify request/response
            return ctx.next(requestSpec, responseSpec);
        }
    })
    .when()
    .get("/users");
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_138__ | Add custom filter |
| __INLINE_CODE_139__ | Add request logging filter |
| __INLINE_CODE_140__ | Add response logging filter |
| __INLINE_CODE_141__ | Add error logging filter |
| __INLINE_CODE_142__ | Add multiple filters |

Konfiguration

### Global Configuration

```java
// Set global configuration
RestAssured.baseURI = "https://api.example.com";
RestAssured.basePath = "/v1";
RestAssured.port = 443;
RestAssured.authentication = basic("user", "pass");
RestAssured.defaultParser = Parser.JSON;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

// Reset to defaults
RestAssured.reset();
```_

| Configuration | Description |
|--------------|-------------|
| __INLINE_CODE_143__ | Set default base URI |
| __INLINE_CODE_144__ | Set default base path |
| __INLINE_CODE_145__ | Set default port |
| __INLINE_CODE_146__ | Set default authentication |
| __INLINE_CODE_147__ | Set default response parser |
| __INLINE_CODE_148__ | Set default request spec |
| __INLINE_CODE_149__ | Set default response spec |
| __INLINE_CODE_150__ | Add global filters |
| __INLINE_CODE_151__ | Auto-log on failure |
| __INLINE_CODE_152__ | Disable SSL validation |
| __INLINE_CODE_153__ | Reset all configurations |

### SSL/TLS Konfiguration

```java
// Relaxed HTTPS validation (testing only)
given()
    .relaxedHTTPSValidation()
    .when()
    .get("https://api.example.com");

// Custom keystore
given()
    .keyStore("/path/to/keystore.jks", "password")
    .when()
    .get("https://api.example.com");

// Custom truststore
given()
    .trustStore("/path/to/truststore.jks", "password")
    .when()
    .get("https://api.example.com");
```_

| Command | Description |
|---------|-------------|
| __INLINE_CODE_154__ | Disable SSL certificate validation |
| __INLINE_CODE_155__ | Set client keystore |
| __INLINE_CODE_156__ | Set truststore |
| __INLINE_CODE_157__ | Set keystore from File object |
| __INLINE_CODE_158__ | Global relaxed HTTPS |

Häufige Anwendungsfälle

### Use Case 1: Simple GET Anfrage mit Validierung

```java
import static io.rest-assured.RestAssured.*;
import static org.hamcrest.Matchers.*;

@Test
public void testGetUser() {
    given()
        .pathParam("id", 1)
    .when()
        .get("https://jsonplaceholder.typicode.com/users/{id}")
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("id", equalTo(1))
        .body("name", notNullValue())
        .body("email", containsString("@"));
}

Use Case 2: POST Anfrage mit JSON Body and Extraction

@Test
public void testCreateUser() {
    // Create user object
    Map<String, String> user = new HashMap<>();
    user.put("name", "John Doe");
    user.put("email", "john@example.com");

    // Send POST and extract ID
    int userId = given()
        .contentType(ContentType.JSON)
        .body(user)
    .when()
        .post("https://api.example.com/users")
    .then()
        .statusCode(201)
        .body("name", equalTo("John Doe"))
        .body("email", equalTo("john@example.com"))
    .extract()
        .path("id");

    System.out.println("Created user ID: " + userId);
}

Use Case 3: Authentication and Reusable Specifications

public class ApiTest {
    private static RequestSpecification requestSpec;
    private static ResponseSpecification responseSpec;

    @BeforeClass
    public static void setup() {
        // Reusable request specification
        requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://api.example.com")
            .setBasePath("/v1")
            .addHeader("Authorization", "Bearer " + getToken())
            .setContentType(ContentType.JSON)
            .build();

        // Reusable response specification
        responseSpec = new ResponseSpecBuilder()
            .expectContentType(ContentType.JSON)
            .expectResponseTime(lessThan(2000L))
            .build();
    }

    @Test
    public void testGetUsers() {
        given()
            .spec(requestSpec)
            .queryParam("page", 1)
        .when()
            .get("/users")
        .then()
            .spec(responseSpec)
            .statusCode(200)
            .body("data.size()", greaterThan(0));
    }

    private static String getToken() {
        return given()
            .contentType(ContentType.JSON)
            .body("{\"username\":\"admin\",\"password\":\"secret\"}")
        .when()
            .post("https://api.example.com/auth/login")
        .then()
            .statusCode(200)
        .extract()
            .path("token");
    }
}

Use Case 4: Datei-Upload mit Multipart

@Test
public void testFileUpload() {
    File file = new File("src/test/resources/test-document.pdf");

    given()
        .multiPart("file", file, "application/pdf")
        .multiPart("description", "Test document")
        .multiPart("category", "reports")
    .when()
        .post("https://api.example.com/upload")
    .then()
        .statusCode(200)
        .body("filename", equalTo("test-document.pdf"))
        .body("size", greaterThan(0))
        .body("status", equalTo("uploaded"));
}

Use Case 5: Complex JSON Validierung mit JsonPath

@Test
public void testComplexJsonValidation() {
    given()
        .queryParam("page", 1)
    .when()
        .get("https://api.example.com/products")
    .then()
        .statusCode(200)
        // Validate array size
        .body("products.size()", equalTo(10))
        // Validate nested fields
        .body("products[0].name", notNullValue())
        .body("products[0].price.amount", greaterThan(0f))
        .body("products[0].price.currency", equalTo("USD"))
        // Validate all items in array
        .body("products.findAll { it.price.amount > 100 }.size()", greaterThan(0))
        // Validate specific item
        .body("products.find { it.id == 'PROD-123' }.name", equalTo("Widget"))
        // Validate collection properties
        .body("products*.category", hasItems("Electronics", "Books"));
}

Use Case 6: Response Deserialization to POJO

// User POJO class
public class User {
    private int id;
    private String name;
    private String email;
    // Getters and setters
}

@Test
public void testResponseDeserialization() {
    // Extract as single object
    User user = given()
        .pathParam("id", 1)
    .when()
        .get("https://api.example.com/users/{id}")
    .then()
        .statusCode(200)
    .extract()
        .as(User.class);

    Assert.assertEquals(1, user.getId());
    Assert.assertNotNull(user.getName());

    // Extract as list of objects
    List<User> users = given()
    .when()
        .get("https://api.example.com/users")
    .then()
        .statusCode(200)
    .extract()
        .jsonPath()
        .getList("data", User.class);

    Assert.assertTrue(users.size() > 0);
}

Use Case 7: JSON Schema Validation

// user-schema.json in src/test/resources
/*
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "id": {"type": "integer"},
    "name": {"type": "string"},
    "email": {"type": "string", "format": "email"}
  },
  "required": ["id", "name", "email"]
}
*/

@Test
public void testJsonSchemaValidation() {
    given()
        .pathParam("id", 1)
    .when()
        .get("https://api.example.com/users/{id}")
    .then()
        .statusCode(200)
        .assertThat()
        .body(matchesJsonSchemaInClasspath("user-schema.json"));
}

oder Best Practices

ANHANG State Importe für Lesbarkeit - Import __INLINE_CODE_159_ und org.hamcrest.Matchers.* statischer für sauberere, lesbarere Testcode - Die Given-When-Then Syntax wird natürlicher und BDD-like