๐Ÿ’ก If you like this website, please share it with your friends and network! ๐Ÿš€
API Automation
REST-Assured & Playwright

Rest Assured 100+ Commands
Advanced & Framework Level

A dynamic, search-optimized cheat sheet for backend test engineers. Master REST-Assured payload mapping, header injection, security validations, database transaction rollbacks via JDBC, and server mocks using WireMock.

Level:
๐ŸŽฏ

Hybrid API + UI Verification Track

Seamlessly connect back-end database audits with RESTful endpoint calls and Selenium/Playwright UI actions to design robust E2E validation frameworks.

REST-Assured Basics

Standard GET Request

Core

Dispatches a basic HTTP GET request to the target resource and captures the complete server response envelope.

Response response = RestAssured.get("https://api.careerraah.com/v1/users");
ID: #1
REST-Assured Basics

GET Request with Path Parameter

Core

Binds a named path variable dynamically into the endpoint URI string during dispatch execution.

Response response = RestAssured
    .given()
        .pathParam("userId", "1024")
    .when()
        .get("https://api.careerraah.com/v1/users/{userId}");
๐Ÿ’ก

Pro-Tip: You can chain multiple pathParam() calls or use pathParams() with a map for cleaner multi-parameter syntax!

ID: #2
REST-Assured Basics

GET Request with Query Parameters

Core

Appends standard URL search query parameters (e.g., ?role=admin&status=active) to the request payload destination.

Response response = RestAssured
    .given()
        .queryParam("role", "admin")
        .queryParam("status", "active")
    .when()
        .get("https://api.careerraah.com/v1/users");
ID: #3
REST-Assured Basics

POST Request with JSON String Body

Core

Submits a resource creation request utilizing a raw serialized JSON string as the request payload.

String payload = "{\"name\":\"Jane\",\"email\":\"jane@example.com\"}";

Response response = RestAssured
    .given()
        .contentType(ContentType.JSON)
        .body(payload)
    .when()
        .post("https://api.careerraah.com/v1/users");
ID: #4
REST-Assured Basics

POST Request with Map Payload

Core

Leverages REST-Assured's automatic object serialization to convert standard Java Map collections to JSON format utilizing active Jackson or Gson dependencies.

Map<String, Object> payload = new HashMap<>();
payload.put("username", "dev_tester");
payload.put("active", true);

Response response = RestAssured
    .given()
        .contentType(ContentType.JSON)
        .body(payload)
    .when()
        .post("https://api.careerraah.com/v1/register");
๐Ÿ’ก

Pro-Tip: Using Maps is a fast way to generate payloads without creating dedicated class files.

ID: #5
REST-Assured Basics

PUT Request with JSON Update

Core

Replaces or updates the target resource entirely with the provided payload representation.

Response response = RestAssured
    .given()
        .contentType(ContentType.JSON)
        .body(updatedPayloadObject)
    .when()
        .put("/v1/users/1024");
ID: #6
REST-Assured Basics

PATCH Request for Partial Updates

Core

Performs a partial modification to an existing resource (e.g., toggling an operational status flag).

Response response = RestAssured
    .given()
        .contentType(ContentType.JSON)
        .body("{\"status\":\"suspended\"}")
    .when()
        .patch("/v1/users/1024");
ID: #7
REST-Assured Basics

DELETE Request

Core

Sends an HTTP DELETE request to remove a specific resource from the server datastore.

Response response = RestAssured.delete("/v1/users/1024");
ID: #8
REST-Assured Basics

GET with Custom Request Headers

Core

Injects custom operational headers into the request context, commonly required for correlation logging or client identification.

Response response = RestAssured
    .given()
        .header("User-Agent", "AutomationEngine/1.0")
        .header("X-Correlation-ID", "unique-uuid-123")
    .when()
        .get("/v1/health");
ID: #9
REST-Assured Basics

Extract Status Code

Core

Retrieves the standard HTTP response status code integer (e.g., 200, 201, 400, 404, 500).

int statusCode = response.getStatusCode();
ID: #10
REST-Assured Basics

Extract Response Headers

Core

Fetches metadata headers returned in the server response payload.

Headers headers = response.getHeaders();
String cacheControl = response.getHeader("Cache-Control");
ID: #11
REST-Assured Basics

Extract Cookie Value

Core

Extracts a specific cookie string value from the Set-Cookie response headers.

String sessionCookie = response.getCookie("JSESSIONID");
ID: #12
REST-Assured Basics

Extract Raw Body String

Core

Extracts the response payload as a raw, human-readable string. Great for debugging or logging.

String jsonResponse = response.getBody().asString();
ID: #13
REST-Assured Basics

Extract Response Time

Core

Returns the roundtrip server response time in milliseconds.

long responseTimeMs = response.getTime();
๐Ÿ’ก

Pro-Tip: Use this to verify Service Level Agreement (SLA) performances on your APIs.

ID: #14
REST-Assured Basics

Configure Base URI Globals

Core

Sets global path prefixes to simplify endpoint parameters inside individual test scripts.

RestAssured.baseURI = "https://api.careerraah.com";
RestAssured.basePath = "/v1";
ID: #15
REST-Assured Basics

Reset RestAssured Globals

Core

Resets baseURI, basePath, filters, and parser configurations back to default settings.

RestAssured.reset();
ID: #16
REST-Assured Basics

Log Request Details

Core

Logs the complete request envelope (method, URI, headers, parameters, and body) directly to standard output.

Response response = RestAssured
    .given()
        .log().all()
    .when()
        .get("/v1/users");
ID: #17
REST-Assured Basics

Log Response Details

Core

Prints only the server response body text to standard output.

Response response = RestAssured.get("/v1/users");
response.then().log().body();
ID: #18
REST-Assured Basics

Conditional Logging (If Error)

Core

Saves stdout bloat by printing logs only when assertions or status validations fail.

RestAssured
    .given()
        .log().ifValidationFails()
    .when()
        .get("/v1/secure-data")
    .then()
        .statusCode(200);
๐Ÿ’ก

Pro-Tip: Excellent standard for CI/CD builds to keep deployment pipeline log files small.

ID: #19
REST-Assured Basics

Multi-Part Form Data (File Upload)

Core

Simulates multipart HTML form submission, frequently required for dynamic profile uploads.

File uploadFile = new File("src/test/resources/avatar.jpg");

Response response = RestAssured
    .given()
        .multiPart("file", uploadFile)
        .multiPart("description", "User avatar")
    .when()
        .post("/v1/profile/upload");
ID: #20
REST-Assured Advanced

Preemptive Basic Authentication

Advanced

Sends HTTP Basic authentication headers immediately with the initial request, avoiding roundtrip challenges.

Response response = RestAssured
    .given()
        .auth().preemptive().basic("admin", "secret123")
    .when()
        .get("/v1/admin/dashboard");
ID: #21
REST-Assured Advanced

Challenged Basic Authentication

Advanced

Waits for the server to reply with a 401 Unauthorized challenge before delivering Basic credentials.

Response response = RestAssured
    .given()
        .auth().basic("username", "password")
    .when()
        .get("/v1/secure");
ID: #22
REST-Assured Advanced

OAuth 2.0 Bearer Token Authorization

Advanced

Attaches a secure Bearer validation token inside the HTTP Authorization request header.

String token = "eyJhbGciOiJIUzI1NiIsIn...";

Response response = RestAssured
    .given()
        .auth().oauth2(token)
    .when()
        .get("/v1/transactions");
ID: #23
REST-Assured Advanced

OAuth 1.0 Authorization Flow

Advanced

Applies cryptographic OAuth 1.0 signatures to authorization parameters.

Response response = RestAssured
    .given()
        .auth().oauth("consumerKey", "consumerSecret", "accessToken", "tokenSecret")
    .when()
        .get("/v1/legacy-feed");
ID: #24
REST-Assured Advanced

Bypass SSL Verification

Advanced

Instructs REST-Assured to accept self-signed or untrusted SSL certificates on local development environments.

Response response = RestAssured
    .given()
        .relaxedHTTPSValidation()
    .when()
        .get("https://self-signed.example.com/api");
๐Ÿ’ก

Pro-Tip: โš ๏ธ Do not use relaxedHTTPSValidation() in production suites! Keep it strictly inside QA/local test configurations.

ID: #25
REST-Assured Advanced

Specify Custom SSL Keystore

Advanced

Integrates client-side SSL certificates to authorize secure peer-to-peer microservices.

Response response = RestAssured
    .given()
        .keyStore("src/test/resources/mykeystore.jks", "keystorePassword")
    .when()
        .get("/secure");
ID: #26
REST-Assured Advanced

Set Connection Timeout

Advanced

Limits network connection waits and socket read timeouts to prevent pipelines hanging on dead nodes.

RestAssuredConfig config = RestAssured.config()
    .httpClient(HttpClientConfig.httpClientConfig()
        .setParam("http.connection.timeout", 5000)
        .setParam("http.socket.timeout", 5000));

Response response = RestAssured.given().config(config).get("/slow-endpoint");
ID: #27
REST-Assured Advanced

Reuse Cookie Configuration

Advanced

Applies individual cookie settings with configured domain boundaries directly onto the request.

Cookie cookie = new Cookie.Builder("session", "active-uuid-998").setDomain("api.com").build();

Response response = RestAssured
    .given()
        .cookie(cookie)
    .when()
        .get("/v1/profile");
ID: #28
REST-Assured Advanced

Deliver Multiple Cookies

Advanced

Incorporates multiple session cookies using key-value string arguments.

Response response = RestAssured
    .given()
        .cookies("theme", "dark", "view", "grid")
    .when()
        .get("/v1/settings");
ID: #29
REST-Assured Advanced

Redirect Handling (Disable Redirects)

Advanced

Prevents automatic HTTP redirects (e.g., 301, 302 codes) from being processed, returning the source redirection headers instead.

Response response = RestAssured
    .given()
        .redirects().follow(false)
    .when()
        .get("/v1/redirect-source");
ID: #30
REST-Assured Advanced

Redirect Handling (Set Max Redirects)

Advanced

Prevents infinite redirect loops by limiting maximum redirect hops to 3.

Response response = RestAssured
    .given()
        .redirects().max(3)
    .when()
        .get("/v1/redirect-loop");
ID: #31
REST-Assured Advanced

Deliver Query Parameters Map

Advanced

Saves chaining calls by injecting all query variables from a Java Map collection.

Map<String, String> queryParams = new HashMap<>();
queryParams.put("page", "2");
queryParams.put("limit", "50");

Response response = RestAssured.given().queryParams(queryParams).get("/v1/logs");
ID: #32
REST-Assured Advanced

Specify ContentType Headers

Advanced

Configures explicit server content negotiation headers for custom REST payloads.

Response response = RestAssured
    .given()
        .contentType("application/vnd.api+json")
    .when()
        .get("/v1/custom-resources");
ID: #33
REST-Assured Advanced

Extract Response to POJO

Advanced

Deserializes the server JSON/XML response payload into a structured Java Plain Old Java Object (POJO).

UserResponse user = response.as(UserResponse.class);
๐Ÿ’ก

Pro-Tip: Define standard Lombok getter/setter models to easily map complex JSON responses.

ID: #34
REST-Assured Advanced

Gzip Encoding Support

Advanced

Declares client support for compression formats, decreasing payload transfers on large datasets.

Response response = RestAssured
    .given()
        .header("Accept-Encoding", "gzip, deflate")
    .when()
        .get("/v1/large-dataset");
ID: #35
REST-Assured Advanced

REST-Assured Custom Request Filter

Framework

Injects custom functional interceptors or execution hooks to record metrics or insert dynamic headers on every transaction.

Response response = RestAssured
    .given()
        .filter((requestSpec, responseSpec, ctx) -> {
            System.out.println("Request URI: " + requestSpec.getURI());
            return ctx.next(requestSpec, responseSpec);
        })
    .when()
        .get("/health");
ID: #36
REST-Assured Advanced

Request Specification Builder

Framework

Encapsulates common request components into a reusable template, simplifying test scripting boilerplate.

RequestSpecification spec = new RequestSpecBuilder()
    .setBaseUri("https://api.careerraah.com")
    .setContentType(ContentType.JSON)
    .addHeader("Auth", "Secret")
    .build();
๐Ÿ’ก

Pro-Tip: Initialize your RequestSpecification in @BeforeSuite configs to enforce global project headers.

ID: #37
REST-Assured Advanced

Response Specification Builder

Framework

Encapsulates standard assertion expectations, reducing redundant validation code across scripts.

ResponseSpecification resSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .expectHeader("Server", "Cloudflare")
    .build();
ID: #38
REST-Assured Advanced

Apply Specifications Together

Framework

Executes an endpoint call combining both request and response templates simultaneously.

RestAssured
    .given()
        .spec(requestSpec)
    .when()
        .get("/v1/users")
    .then()
        .spec(responseSpec);
ID: #39
REST-Assured Advanced

Multi-Part Form Data (Byte Array)

Advanced

Transfers raw file byte arrays in multipart requests without relying on local system pathing.

byte[] fileBytes = Files.readAllBytes(Paths.get("invoice.pdf"));

RestAssured
    .given()
        .multiPart("document", "invoice.pdf", fileBytes)
    .when()
        .post("/v1/invoices");
ID: #40
REST-Assured Advanced

Configure Connection Pooling Settings

Framework

Releases idle sockets immediately after validations finish, preserving active descriptors.

RestAssured.config = RestAssured.config()
    .connectionConfig(ConnectionConfig.connectionConfig()
        .closeIdleConnectionsAfterEachResponse());
ID: #41
REST-Assured Advanced

Request URI Encoding Override

Advanced

Disables standard URL encoding to deliver custom, pre-escaped parameter formats.

Response response = RestAssured
    .given()
        .urlEncodingEnabled(false)
    .when()
        .get("/v1/search?query=val%2Bparam");
ID: #42
REST-Assured Advanced

Proxy Server Routing

Advanced

Routes client requests through a corporate network proxy or debugging server (like Charles or Fiddler).

Response response = RestAssured
    .given()
        .proxy("proxy.mycompany.local", 8080)
    .when()
        .get("/v1/endpoints");
ID: #43
REST-Assured Advanced

Proxy Server Auth Credentials

Advanced

Integrates authentication credentials while routing requests through secure corporate proxies.

Response response = RestAssured
    .given()
        .proxy(ProxySpecification.host("proxy.com").withPort(8080).withAuth("user", "pass"))
    .when()
        .get("/v1/data");
ID: #44
REST-Assured Advanced

Form Parameters POST Payload

Core

Sends application/x-www-form-urlencoded POST payloads, typically required by standard OAuth token exchanges.

Response response = RestAssured
    .given()
        .formParam("username", "jane")
        .formParam("grant_type", "password")
    .when()
        .post("/oauth/token");
ID: #45
JSON & XML Assertions

Validate Status Code Inline

Core

Inlines validation logic to verify that the response status code is exactly 200.

RestAssured.get("/v1/users")
    .then()
        .statusCode(200);
ID: #46
JSON & XML Assertions

Assert JSON Body Key (EqualTo)

Core

Uses Hamcrest Matchers to assert a specific root JSON field matches the expected value.

RestAssured.get("/v1/users/1024")
    .then()
        .body("name", Matchers.equalTo("Jane"));
ID: #47
JSON & XML Assertions

Assert JSON Array Length

Core

Asserts that the root JSON array contains more than 5 child entries.

RestAssured.get("/v1/users")
    .then()
        .body("size()", Matchers.greaterThan(5));
ID: #48
JSON & XML Assertions

Assert Value inside Nested Object

Core

Uses standard dot notation paths to navigate and validate values inside nested JSON structures.

RestAssured.get("/v1/users/1024")
    .then()
        .body("address.city", Matchers.equalTo("Chicago"));
ID: #49
JSON & XML Assertions

Assert List Elements Contain Value

Core

Asserts that the response array or list field contains at least one match for the specified value.

RestAssured.get("/v1/users")
    .then()
        .body("roles", Matchers.hasItem("Admin"));
ID: #50
JSON & XML Assertions

JSON Schema Validation

Framework

Ensures the response payload fully matches the structured JSON schema file inside the test classpath.

RestAssured.get("/v1/users/1024")
    .then()
        .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("user-schema.json"));
๐Ÿ’ก

Pro-Tip: Include the json-schema-validator module dependency inside your pom.xml file to enable this feature.

ID: #51
JSON & XML Assertions

JSON Schema from File Path

Framework

Performs JSON schema validation loading the configuration parameters directly from a local File path.

File schema = new File("schemas/error-schema.json");

RestAssured.get("/v1/invalid")
    .then()
        .body(JsonSchemaValidator.matchesJsonSchema(schema));
ID: #52
JSON & XML Assertions

JsonPath Extract Field

Core

Extracts an individual field value from the response body utilizing dot-path notations.

JsonPath jp = response.jsonPath();
String userMail = jp.getString("email");
ID: #53
JSON & XML Assertions

JsonPath Extract List Elements

Core

Extracts all matches of a property inside a list structure into a flat Java List collection.

JsonPath jp = response.jsonPath();
List<String> cities = jp.getList("users.address.city");
ID: #54
JSON & XML Assertions

Groovy Find Method (JsonPath)

Advanced

Uses dynamic Groovy inline expressions to search an array and return the first entry matching conditions.

JsonPath jp = response.jsonPath();
Map<String, Object> adminUser = jp.get("users.find { it.role == 'Admin' }");
๐Ÿ’ก

Pro-Tip: Extremely powerful for searching a dynamic database of items without writing manual java loop iterations!

ID: #55
JSON & XML Assertions

Groovy FindAll Method (JsonPath)

Advanced

Filters all users matching active conditions, returning a flat list of their associated email addresses.

JsonPath jp = response.jsonPath();
List<String> activeMails = jp.get("users.findAll { it.active == true }.email");
ID: #56
JSON & XML Assertions

Groovy Max Method (JsonPath)

Advanced

Evaluates list models, filtering and returning the student object containing the highest score value.

int maxScore = response.jsonPath().getInt("students.max { it.score }.score");
ID: #57
JSON & XML Assertions

Assert ContentType Inline

Core

Asserts that the server response header 'Content-Type' matches application/json.

RestAssured.get("/v1/health")
    .then()
        .contentType(ContentType.JSON);
ID: #58
JSON & XML Assertions

Assert Header Values

Core

Verifies the presence and exact value of specific server security and encoding headers.

RestAssured.get("/v1/users")
    .then()
        .header("X-Frame-Options", "DENY")
        .header("Content-Encoding", "gzip");
ID: #59
JSON & XML Assertions

Assert Response Time (SLA)

Advanced

Asserts that the request roundtrip was completed within 800 milliseconds.

RestAssured.get("/v1/fast-api")
    .then()
        .time(Matchers.lessThan(800L));
ID: #60
JSON & XML Assertions

XMLPath Extract Value

Core

Extracts data from standard XML responses utilizing clean path traversing logic.

XmlPath xp = response.xmlPath();
String text = xp.getString("bookstore.book[0].title");
ID: #61
JSON & XML Assertions

Assert XML Value (Matchers)

Core

Directly validates dynamic XML response payload trees utilizing inlined Hamcrest assertions.

RestAssured.get("/v1/books.xml")
    .then()
        .body("bookstore.book[0].author", Matchers.equalTo("J.K. Rowling"));
ID: #62
JSON & XML Assertions

Extract XML Attribute

Advanced

Extracts values from specific XML element attribute variables utilizing the @ prefix notation.

String isbn = response.xmlPath().getString("bookstore.book[0].@isbn");
ID: #63
JSON & XML Assertions

Assert Multiple Fields (Soft Asserts)

Core

Validates multiple assertions within a single code execution, evaluating all rules even if one fails.

RestAssured.get("/v1/users/1024")
    .then()
        .body("name", Matchers.equalTo("Jane"),
              "role", Matchers.equalTo("Editor"),
              "age", Matchers.greaterThan(18));
ID: #64
JSON & XML Assertions

Validate XML Schema (XSD)

Framework

Validates XML response payloads against standard XSD schema definitions loaded from the classpath.

RestAssured.get("/v1/data.xml")
    .then()
        .body(RestAssuredMatchers.matchesXsdInClasspath("schema.xsd"));
ID: #65
Playwright API Testing

Playwright Request Context

Core

Instantiates a new, standalone API request network container inside a Playwright test runner.

APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
    .setBaseURL("https://api.careerraah.com"));
ID: #66
Playwright API Testing

Playwright GET Request

Core

Executes a standalone HTTP GET request using Playwright's native network client API.

APIResponse response = request.get("/v1/users");
ID: #67
Playwright API Testing

Playwright GET with Query Params

Core

Appends clean query parameters to the Playwright API request structure.

APIResponse response = request.get("/v1/users", RequestOptions.create()
    .setQueryParam("role", "admin")
    .setQueryParam("limit", 10));
ID: #68
Playwright API Testing

Playwright POST Request Payload

Core

Sends a POST request with automatically serialized Java Map bodies.

Map<String, Object> data = new HashMap<>();
data.put("name", "Alice");

APIResponse response = request.post("/v1/users", RequestOptions.create()
    .setData(data));
ID: #69
Playwright API Testing

Playwright Custom Request Headers

Core

Incorporate operational request headers onto individual network dispatches.

APIResponse response = request.get("/v1/secure", RequestOptions.create()
    .setHeader("X-Auth-Token", "secret-auth-value"));
ID: #70
Playwright API Testing

Extract Playwright Status Code

Core

Returns the response status code integer from Playwright's network response layer.

int code = response.status();
ID: #71
Playwright API Testing

Extract Playwright Status Text

Core

Retrieves status description text strings (e.g., 'OK' or 'Created').

String statusText = response.statusText();
ID: #72
Playwright API Testing

Assert Playwright Response Success

Core

Convenient Boolean evaluator to confirm standard successful HTTP status code transactions.

boolean isOk = response.ok();
// Returns true if status code in the 200-299 range
ID: #73
Playwright API Testing

Extract JSON Payload (Playwright)

Core

Parses the response body directly into a typed Google Gson JsonElement model.

JsonElement json = response.json();
ID: #74
Playwright API Testing

Extract Byte Array (Playwright)

Core

Returns response body payloads as raw unparsed byte arrays, ideal for downloading static resources.

byte[] rawBodyBytes = response.body();
ID: #75
Playwright API Testing

Extract String Payload (Playwright)

Core

Extracts response payloads as basic UTF-8 encoded text strings.

String responseString = response.text();
ID: #76
Playwright API Testing

Extract Response Headers (Playwright)

Core

Fetches a full Map representation of all returned server headers.

Map<String, String> headers = response.headers();
ID: #77
Playwright API Testing

Close Request Context (Playwright)

Core

Tears down the network context container, closing idle sockets and clearing associated session memory structures.

request.dispose();
๐Ÿ’ก

Pro-Tip: Always call dispose() in @AfterMethod annotations to prevent resource leaks during large-scale suites.

ID: #78
Playwright API Testing

Configure Global Headers Context

Advanced

Establishes standard default headers that apply automatically to every network execution inside this context.

APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
    .setHeader("Authorization", "Bearer token")
    .setHeader("Accept", "application/json"));
ID: #79
Playwright API Testing

Disable SSL Verification (Playwright)

Advanced

Forces Playwright to bypass SSL validation checks when automating local development environments.

APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
    .setIgnoreHTTPSErrors(true));
ID: #80
Playwright API Testing

Deliver Form UrlEncoded Body (Playwright)

Advanced

Submits urlencoded request payloads using key-value pair parameters.

APIResponse response = request.post("/login", RequestOptions.create()
    .setFormParam("user", "jane")
    .setFormParam("pass", "1234"));
ID: #81
Playwright API Testing

Multipart File Upload (Playwright)

Advanced

Executes standard file uploads utilizing Playwright's native FormData objects.

APIResponse response = request.post("/upload", RequestOptions.create()
    .setMultipart(new FormData()
        .set("file", Paths.get("test.png"))
        .set("name", "Avatar")));
ID: #82
Playwright API Testing

Bypass Auto-Failures (FailOnStatusCode)

Advanced

Prevents Playwright from automatically throwing exceptions on non-success HTTP codes, allowing explicit checks instead.

APIResponse response = request.get("/secure", RequestOptions.create()
    .setFailOnStatusCode(false));
ID: #83
Playwright API Testing

Extract Playwright Cookie State

Framework

Captures complete session states (cookies and LocalStorage) to bypass login requirements on UI tests.

String state = browserContext.storageState();
๐Ÿ’ก

Pro-Tip: Use API calls to authenticate and fetch StorageStates, saving minutes of UI loading on every test run.

ID: #84
Playwright API Testing

Inject Storage State to API Context

Framework

Launches a new API request context pre-populated with captured authentication tokens and cookies.

APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
    .setStorageState(state));
ID: #85
Database & JDBC

Establish JDBC Connection

Core

Initializes a database connection pool to execute backend integrity verifications.

String url = "jdbc:postgresql://localhost:5432/qadb";
Connection conn = DriverManager.getConnection(url, "qa_user", "securePass");
ID: #86
Database & JDBC

Execute Select SQL Query

Core

Sends standard SQL queries and returns a ResultSet wrapper to navigate matched datasets.

Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT email, role FROM users WHERE id=1024");
ID: #87
Database & JDBC

Extract Query Data (String)

Core

Iterates database pointers and retrieves data string values using named table columns.

if (rs.next()) {
    String email = rs.getString("email");
    String role = rs.getString("role");
}
ID: #88
Database & JDBC

Execute Parameterized Prepared Query

Advanced

Uses Prepared Statements to route parameters safely, avoiding SQL injection vulnerabilities.

String query = "SELECT * FROM users WHERE status = ? AND age > ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, "active");
ps.setInt(2, 18);
ResultSet rs = ps.executeQuery();
๐Ÿ’ก

Pro-Tip: Always use PreparedStatement for database interactions to ensure characters like single quotes are properly escaped.

ID: #89
Database & JDBC

Execute Database Update (DML)

Core

Executes SQL modification commands (INSERT, UPDATE, DELETE), returning the row mutation counts.

Statement statement = conn.createStatement();
int rowsAffected = statement.executeUpdate("UPDATE users SET active = false WHERE id = 1024");
ID: #90
Database & JDBC

Database Transaction Rollback Setup

Framework

Disables autocommit to run modifications, rolling back changes at the end of the test execution to preserve clean states.

conn.setAutoCommit(false);
// ... Execute database operations
conn.rollback();
๐Ÿ’ก

Pro-Tip: Crucial framework strategy! Prevents automation scripts from corrupting static shared testing databases.

ID: #91
Database & JDBC

Database Transaction Commit

Framework

Attempts database commits, catching failures and safely rolling back transaction states.

try {
    // ... Database operations
    conn.commit();
} catch (SQLException e) {
    conn.rollback();
}
ID: #92
Database & JDBC

Close Database Resource Pool

Core

Releases database resources back to the server pools, preventing memory and socket descriptor leaks.

if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
ID: #93
Database & JDBC

JDBC Connection with Properties

Advanced

Launches database connections routes routing parameters using properties config files.

Properties props = new Properties();
props.setProperty("user", "qa_admin");
props.setProperty("password", "secret");
props.setProperty("ssl", "true");

Connection conn = DriverManager.getConnection("jdbc:postgresql://db.host.com/qadb", props);
ID: #94
Database & JDBC

Verify Row Count (Select Count)

Core

Performs counts on records to verify UI datasets match database outputs.

ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS total FROM users");
if (rs.next()) {
    int count = rs.getInt("total");
}
ID: #95
Database & JDBC

Map ResultSet to Java Object List

Advanced

Iterates through rows, creating collections of Java models to evaluate complex data scenarios.

List<User> users = new ArrayList<>();
while (rs.next()) {
    users.add(new User(rs.getInt("id"), rs.getString("username")));
}
ID: #96
Database & JDBC

Execute SQL Batch Mutations

Advanced

Dispatches database updates in single batches, decreasing network latency.

Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO logs VALUES(1, 'Access')");
stmt.addBatch("INSERT INTO logs VALUES(2, 'Modify')");
int[] results = stmt.executeBatch();
ID: #97
Database & JDBC

Extract Database Schema Metadata

Framework

Fetches table schemas, column data types, and primary key relationships.

DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, "users", null);
ID: #98
Database & JDBC

Database Transaction Savepoint Hook

Advanced

Defines a transactional checkpoint (Savepoint) inside the active JDBC connection, enabling rollbacks to targeted checkpoints rather than reversing the whole transaction block.

Savepoint savepoint = conn.setSavepoint("Savepoint1");
// ... operations
conn.rollback(savepoint);
ID: #99
Database & JDBC

Establish JDBC Connection Pool (HikariCP)

Framework

Initializes a high-performance database connection pool utilizing HikariCP to reuse active connections across parallel execution threads efficiently.

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/qadb");
config.setUsername("qa_user");
HikariDataSource ds = new HikariDataSource(config);
Connection conn = ds.getConnection();
ID: #100
Database & JDBC

Fetch Column Metadata

Advanced

Retrieves table column count and column property metadata directly from database result sets.

ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String columnName = rsmd.getColumnName(1);
ID: #101
Database & JDBC

Call Stored Procedure

Advanced

Prepares and executes a database stored procedure with defined input and output parameters.

CallableStatement cs = conn.prepareCall("{call get_user_by_id(?, ?)}");
cs.setInt(1, 1024);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
String name = cs.getString(2);
ID: #102
API Mocking & Frameworks

Initialize WireMock Mock Server

Framework

Launches a local mock API server to simulate sandbox HTTP responses.

WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8089));
wireMockServer.start();
ID: #103
API Mocking & Frameworks

Stub GET Request (WireMock)

Framework

Creates stub definitions to intercept client requests, returning custom mock payloads.

wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/v1/mock-user"))
    .willReturn(WireMock.aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"status\":\"MockedJane\"}")));
๐Ÿ’ก

Pro-Tip: Crucial for frontend testing when live backend APIs are down or unstable!

ID: #104
API Mocking & Frameworks

Stub GET Request with Delay (Latency Mocking)

Framework

Simulates network latency and endpoint timeout conditions in test suites.

wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/slow-endpoint"))
    .willReturn(WireMock.aResponse()
        .withStatus(200)
        .withFixedDelay(3000))); // Simulates 3s delay
ID: #105
API Mocking & Frameworks

Stub GET Request with Header Matches

Framework

Stubs endpoints which execute response mapping only when specific header conditions are satisfied.

wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/secure"))
    .withHeader("Authorization", WireMock.matching("Bearer .*"))
    .willReturn(WireMock.ok()));
ID: #106
API Mocking & Frameworks

Shut Down Mock Server

Framework

Stops WireMock server runtimes and releases occupied ports back to the system.

wireMockServer.stop();
ID: #107
API Mocking & Frameworks

Parse JSON String (JSONObject)

Core

Parses raw response strings into queryable JSON objects utilizing standard org.json library classes.

JSONObject json = new JSONObject(responseString);
String name = json.getString("name");
boolean active = json.getBoolean("active");
ID: #108
API Mocking & Frameworks

Build JSON Payload (JSONObject)

Core

Generates custom serialized JSON payloads programmatically.

JSONObject payload = new JSONObject();
payload.put("name", "Jane");
payload.put("roles", new JSONArray().put("User").put("Editor"));
String body = payload.toString();
ID: #109
API Mocking & Frameworks

Validate JSON Array Iterations

Core

Loops through JSON array elements to check specific fields individually.

JSONArray arr = new JSONArray(responseString);
for (int i = 0; i < arr.length(); i++) {
    JSONObject item = arr.getJSONObject(i);
    System.out.println(item.getString("id"));
}
ID: #110
API Mocking & Frameworks

Jackson ObjectMapper Serialization

Framework

Converts standard Java objects to JSON formatted strings programmatically utilizing Jackson libraries.

ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(new User("Jane", 28));
ID: #111
Playwright API Testing

Playwright API Tracing Capture

Framework

Triggers and captures advanced Playwright action traces, screenshots, and response snapshots to record full network executions for debugging.

browserContext.tracing().start(new Tracing.StartOptions()
    .setScreenshots(true).setSnapshots(true));
// ... run API/UI steps
browserContext.tracing().stop(new Tracing.StopOptions()
    .setPath(Paths.get("trace.zip")));
ID: #112
API Mocking & Frameworks

WireMock Stateful Scenario Emulation

Framework

Sets up stateful stubs in WireMock to return different response values based on the dynamic scenario execution state.

wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/todo"))
    .inScenario("TodoScenario")
    .whenScenarioStateIs(Scenario.STARTED)
    .willReturn(WireMock.aResponse().withBody("Initial list"))
    .willSetStateTo("ItemsAdded"));
ID: #113
API Mocking & Frameworks

Load Application XML Config Parser

Framework

Parses structured XML files to dynamically resolve project automation properties.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("config.xml"));
ID: #114
API Mocking & Frameworks

Gson Deserialization Utility

Framework

Parses JSON string parameters into typed Java objects leveraging Google's Gson library.

Gson gson = new Gson();
UserResponse user = gson.fromJson(jsonString, UserResponse.class);
ID: #115
API Mocking & Frameworks

Load YAML Configuration Files

Framework

Parses advanced YAML files to extract hierarchical environment variables.

Yaml yaml = new Yaml();
Map<String, Object> data = yaml.load(new FileInputStream("config.yaml"));
ID: #116
JSON & XML Assertions

Verify API Performance Response Speed

Advanced

Ensures roundtrip API latency measurements do not exceed standard Service Level Agreement performance boundaries.

RestAssured.get("/status")
    .then()
        .time(Matchers.lessThanOrEqualTo(1200L), TimeUnit.MILLISECONDS);
ID: #117
REST-Assured Advanced

Check REST-Assured Multipart Type Specification

Advanced

Attaches a specific MIME-type multi-part document structure directly inside the request envelope.

RestAssured
    .given()
        .multiPart(new MultiPartSpecBuilder(file)
            .controlName("attachment")
            .mimeType("application/pdf").build())
    .when()
        .post("/upload");
ID: #118
Playwright API Testing

Verify Playwright Session Cookies

Core

Retrieves the active browser authentication and tracking cookies from Playwright's network context.

List<Cookie> cookies = browserContext.cookies();
Assert.assertFalse(cookies.isEmpty());
ID: #119
Database & JDBC

JDBC Connection Timeout Assertion

Advanced

Defines the connection time limit in seconds to prevent database connection failures from hanging pipeline executions.

DriverManager.setLoginTimeout(5);
Connection conn = DriverManager.getConnection(url, user, password);
ID: #120

Want to practice API queries in real-time?

Try routing RESTful calls against dynamic tables inside our interactive **QA Playground** sandbox.