Saltar a contenido

REST Assured Cheatsheet

Instalación

Maven Instalación (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 Instalación (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 Prerequisites

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

Importaciones requeridas

// 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;

Basic HTTP Métodos

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

Request Specification

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

Response Validation

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

__TABLE_172_

Response Extraction

__TABLE_173_

Advanced Authentication

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

Request Specifications (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

Response Specifications (Reusable)

// 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

Logging

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 Validation

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 Data

// 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

Filters (Request/Response Interceptors)

// 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

Configuración

Configuración Global

// 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

Configuración SSL/TLS

// 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");
__TABLE_183_

Common Use Cases

Use Case 1: Simple GET Solicitud con validación

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 Request with 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: File Upload with 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 Validación con 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"));
}

Buenas prácticas

  1. Utilizar las importaciones estaticas para la legibilidad
  2. Importar io.rest-assured.RestAssured.* y org.hamcrest.Matchers.*_ para un código de prueba más limpio y legible
  3. La sintaxis dada-cuando-entonces se vuelve más natural y BDD-como