APIRequestContext
Added in: v1.16This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare environment or the service to your e2e test.
Each Playwright browser context has an associated APIRequestContext, accessible via browserContext.request() or page.request() (these return the
same instance — page.request is a shortcut for page.context().request). You can also create a standalone, isolated instance with apiRequest.newContext().
Cookie management
The APIRequestContext returned by browserContext.request() and
page.request() uses the same cookie jar as its BrowserContext:
If you want API requests that do not share cookies with the browser, create an isolated context via apiRequest.newContext(). Such APIRequestContext object will have its own isolated cookie storage.
Methods
apiRequestContext.addCookies()
Added in: v1.64Adds cookies into this request context. They will be sent with matching subsequent requests. For browserContext.request() and page.request(), this is equivalent to calling browserContext.addCookies() on the corresponding browser context.
Usage
request.addCookies(Arrays.asList(cookieObject1, cookieObject2));Arguments
namestringvaluestringurlstring(optional)Either
urlor bothdomainandpathare required. Optional.domainstring(optional)For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either
urlor bothdomainandpathare required. Optional.pathstring(optional)Either
urlor bothdomainandpathare required. Optional.expiresfloat(optional)Unix time in seconds. Optional.
httpOnlyboolean(optional)Optional.
secureboolean(optional)Optional.
sameSite"Strict" | "Lax" | "None"(optional)Optional.
partitionKeystring(optional)For partitioned third-party cookies (aka CHIPS), the partition key. Optional.
apiRequestContext.clearCookies()
Added in: v1.64Removes cookies from this request context. Accepts optional filter. For browserContext.request() and page.request(), this is equivalent to calling browserContext.clearCookies() on the corresponding browser context.
Usage
request.clearCookies();
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setName("session-id"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setDomain("my-origin.com"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setPath("/api/v1"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions()
.setName("session-id")
.setDomain("my-origin.com"));Arguments
apiRequestContext.cookies()
Added in: v1.64If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. For browserContext.request() and page.request(), this is equivalent to calling browserContext.cookies() on the corresponding browser context.
Arguments
Returns
Array<Object>
apiRequestContext.delete()
Added in: v1.16Sends HTTP(S) DELETE request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Arguments
Returns
APIResponse
apiRequestContext.dispose()
Added in: v1.16All responses returned by apiRequestContext.get() and similar methods are stored in the memory, so that you can later call apiResponse.body().This method discards all its resources, calling any method on disposed APIRequestContext will throw an exception.
Arguments
apiRequestContext.fetch()
Added in: v1.16Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Usage
JSON objects can be passed directly to the request:
Map<String, Object> data = new HashMap();
data.put("title", "Book Title");
data.put("body", "John Doe");
request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding, by specifiying the multipart parameter:
// Pass file path to the form data constructor:
Path file = Paths.get("team.csv");
APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
RequestOptions.create().setMethod("post").setMultipart(
FormData.create().set("fileField", file)));
// Or you can pass the file content directly as FilePayload object:
FilePayload filePayload = new FilePayload("f.js", "text/javascript",
"console.log(2022);".getBytes(StandardCharsets.UTF_8));
APIResponse response = request.fetch("https://example.com/api/uploadScript",
RequestOptions.create().setMethod("post").setMultipart(
FormData.create().set("fileField", filePayload)));Arguments
Target URL or Request to get all parameters from.
optionsRequestOptions(optional) Added in: v1.18Optional request parameters.
Returns
APIResponse
apiRequestContext.get()
Added in: v1.16Sends HTTP(S) GET request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Usage
Request parameters can be configured with params option, they will be serialized into the URL search parameters:
request.get("https://example.com/api/getText", RequestOptions.create()
.setQueryParam("isbn", "1234")
.setQueryParam("page", 23));Arguments
Returns
APIResponse
apiRequestContext.head()
Added in: v1.16Sends HTTP(S) HEAD request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Arguments
Returns
APIResponse
apiRequestContext.patch()
Added in: v1.16Sends HTTP(S) PATCH request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Arguments
Returns
APIResponse
apiRequestContext.post()
Added in: v1.16Sends HTTP(S) POST request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Usage
JSON objects can be passed directly to the request:
Map<String, Object> data = new HashMap();
data.put("title", "Book Title");
data.put("body", "John Doe");
request.post("https://example.com/api/createBook", RequestOptions.create().setData(data));To send form data to the server use form option. Its value will be encoded into the request body with application/x-www-form-urlencoded encoding (see below how to use multipart/form-data form encoding to send files):
request.post("https://example.com/api/findBook", RequestOptions.create().setForm(
FormData.create().set("title", "Book Title").set("body", "John Doe")
));The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding. Use FormData to construct request body and pass it to the request as multipart parameter:
// Pass file path to the form data constructor:
Path file = Paths.get("team.csv");
APIResponse response = request.post("https://example.com/api/uploadTeamList",
RequestOptions.create().setMultipart(
FormData.create().set("fileField", file)));
// Or you can pass the file content directly as FilePayload object:
FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
"console.log(2022);".getBytes(StandardCharsets.UTF_8));
APIResponse response = request.post("https://example.com/api/uploadScript",
RequestOptions.create().setMultipart(
FormData.create().set("fileField", filePayload)));Arguments
Returns
APIResponse
apiRequestContext.put()
Added in: v1.16Sends HTTP(S) PUT request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
Arguments
Returns
APIResponse
apiRequestContext.storageState()
Added in: v1.16Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
Arguments
indexedDBboolean(optional) Added in: v1.51Set to
trueto include IndexedDB in the storage state snapshot.opfsboolean(optional) Added in: v1.63Set to
trueto include the origin private file system in the storage state snapshot.The file path to save the storage state to. If
pathis a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
Returns
string
Properties
apiRequestContext.tracing()
Added in: v1.60Tracing recorder for requests made through this API request context.
Type
Tracing