Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright Java’s APIRequestContext.patch() to send a PATCH request, pass JSON through RequestOptions.setData(), and assert the status and response behavior required by your API’s contract. The example below is a starting point: replace its endpoint, authentication, payload, and assertions with the details your service documents.

Send a PATCH request with Playwright Java

Playwright’s API request interface is intended for Web API testing and can send HTTP(S) requests without opening a page. Its Java APIRequestContext.patch() method accepts a URL, optionally with request options, and returns an APIResponse. The method updates cookies from the response and follows redirects automatically. See the Playwright Java APIRequestContext documentation.

This example sends a JSON object to a fictional user endpoint. It deliberately uses a standalone request context and environment-based bearer token; adapt those choices to your test setup.

import com.microsoft.playwright.*;
import java.util.*;

public class PatchApiTest {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      APIRequestContext request = playwright.request().newContext(
        new APIRequest.NewContextOptions()
          .setBaseURL("https://api.example.test")
          .setExtraHTTPHeaders(Map.of(
            "Accept", "application/json",
            "Authorization", "Bearer " + System.getenv("API_TOKEN"),
            "Content-Type", "application/json")));

      try {
        Map<String, Object> patch = new HashMap<>();
        patch.put("displayName", "Updated name");
        patch.put("enabled", true);

        APIResponse response = request.patch(
          "/users/123",
          RequestOptions.create().setData(patch));

        if (response.status() != 200) {
          throw new AssertionError("Unexpected status: " + response.status());
        }

        String body = response.text();
        if (!body.contains("Updated name")) {
          throw new AssertionError("Updated field missing from response: " + body);
        }
      } finally {
        request.dispose();
      }
    }
  }
}

The endpoint and expected response above are illustrative, not a promise that an API returns status 200 or echoes the updated field. Choose both from the endpoint’s contract. Supply a real token through API_TOKEN if the service requires bearer authentication.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Pass a JSON body and set request options

Build the patch document as a Map<String, Object> and pass it to RequestOptions.create().setData(patch). Playwright serializes object data as JSON and uses application/json when a content type has not already been set. Set headers explicitly when the API requires particular values, as the example does.

Include only fields the API defines as patchable. A PATCH body’s meaning is determined by the endpoint: it may accept a partial object, a specific patch-document format, or another schema. Do not assume that sending a field means the service will accept it or interpret it as a merge.

Choose a request context that matches your authentication

There are two common ways to create the request context, and their cookie behavior differs:

Approach Cookie relationship Useful when
BrowserContext.request() or Page.request() Associated with the browser context and its cookie jar The API call should use browser-associated cookies or authentication state
playwright.request().newContext() Standalone context with isolated cookie storage You want an independent API client, such as one using explicit authorization headers

See the Playwright Java APIRequestContext reference for context details. If the API relies on an authenticated browser session, use the associated context or configure the standalone context with the appropriate state. Playwright’s API testing guide covers API testing workflows, including creating state and validating server results.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Assert what the endpoint promises

A successful PATCH does not have one universal status code, response schema, or persistence rule. Derive assertions from the specific API contract rather than copying the illustrative 200 check.

  • Status: Assert the documented success status for the endpoint.
  • Response body: Check changed fields only if the contract says the response includes them; validate the promised schema rather than searching the raw body for a substring in production tests.
  • Persistence: If the response is sparse, asynchronous, or has no body, issue a GET for the resource and check the stored values.
  • Negative behavior: Test documented outcomes for missing authentication, an unknown resource ID, malformed JSON, invalid or immutable fields, and an empty patch document.

For an endpoint that returns 204 No Content, assert that status and verify the updated resource with a follow-up GET instead of parsing an empty response body.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make the test repeatable and safe to retry

Start with a known resource state, preferably by creating or selecting isolated test data. Avoid reusing identifiers in a way that makes retries collide. If the PATCH result is not immediately visible, follow the service’s documented consistency behavior before checking with GET.

Do not assume PATCH is idempotent: repeating the same request can have different effects depending on the operation. If the API uses ETags or If-Match, test stale-version handling and concurrent updates according to its contract. Delete test resources when appropriate, or use an isolated test tenant, and dispose of the APIRequestContext when its lifecycle ends.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check Playwright version support

The Playwright Java API reference marks APIRequestContext.patch() as added in v1.16 and its Java request parameters as added in v1.18. If the method or options are unavailable in a project, check the Playwright dependency version and use the API reference for that version.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.