English · Python
Appearance
English · Python
Appearance
This 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 browser_context.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 api_request.new_context().
Cookie management
The APIRequestContext returned by browser_context.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 api_request.new_context(). Such APIRequestContext object will have its own isolated cookie storage.
import os
import asyncio
from playwright.async_api import async_playwright, Playwright
REPO = "test-repo-1"
USER = "github-username"
API_TOKEN = os.getenv("GITHUB_API_TOKEN")
async def run(playwright: Playwright):
# This will launch a new browser, create a context and page. When making HTTP
# requests with the internal APIRequestContext (e.g. `context.request` or `page.request`)
# it will automatically set the cookies to the browser page and vice versa.
browser = await playwright.chromium.launch()
context = await browser.new_context(base_url="https://api.github.com")
api_request_context = context.request
page = await context.new_page()
# Alternatively you can create a APIRequestContext manually without having a browser context attached:
# api_request_context = await playwright.request.new_context(base_url="https://api.github.com")
# Create a repository.
response = await api_request_context.post(
"/user/repos",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
data={"name": REPO},
)
assert response.ok
assert response.json()["name"] == REPO
# Delete a repository.
response = await api_request_context.delete(
f"/repos/{USER}/{REPO}",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
)
assert response.ok
assert await response.body() == '{"status": "ok"}'
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())import os
from playwright.sync_api import sync_playwright
REPO = "test-repo-1"
USER = "github-username"
API_TOKEN = os.getenv("GITHUB_API_TOKEN")
with sync_playwright() as p:
# This will launch a new browser, create a context and page. When making HTTP
# requests with the internal APIRequestContext (e.g. `context.request` or `page.request`)
# it will automatically set the cookies to the browser page and vice versa.
browser = p.chromium.launch()
context = browser.new_context(base_url="https://api.github.com")
api_request_context = context.request
page = context.new_page()
# Alternatively you can create a APIRequestContext manually without having a browser context attached:
# api_request_context = p.request.new_context(base_url="https://api.github.com")
# Create a repository.
response = api_request_context.post(
"/user/repos",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
data={"name": REPO},
)
assert response.ok
assert response.json()["name"] == REPO
# Delete a repository.
response = api_request_context.delete(
f"/repos/{USER}/{REPO}",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
)
assert response.ok
assert await response.body() == '{"status": "ok"}'Adds cookies into this request context. They will be sent with matching subsequent requests. For browser_context.request and page.request, this is equivalent to calling browser_context.add_cookies() on the corresponding browser context.
Usage
await request.add_cookies([cookie_object1, cookie_object2])request.add_cookies([cookie_object1, cookie_object2])Arguments
name string
value string
url string (optional)
Either url or both domain and path are required. Optional.
domain string (optional)
For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either url or both domain and path are required. Optional.
path string (optional)
Either url or both domain and path are required. Optional.
expires float (optional)
Unix time in seconds. Optional.
http_only boolean (optional)
Optional.
secure boolean (optional)
Optional.
same_site "Strict" | "Lax" | "None" (optional)
Optional.
partition_key string (optional)
For partitioned third-party cookies (aka CHIPS), the partition key. Optional.
Removes cookies from this request context. Accepts optional filter. For browser_context.request and page.request, this is equivalent to calling browser_context.clear_cookies() on the corresponding browser context.
Usage
await request.clear_cookies()
await request.clear_cookies(name="session-id")
await request.clear_cookies(domain="my-origin.com")
await request.clear_cookies(path="/api/v1")
await request.clear_cookies(name="session-id", domain="my-origin.com")request.clear_cookies()
request.clear_cookies(name="session-id")
request.clear_cookies(domain="my-origin.com")
request.clear_cookies(path="/api/v1")
request.clear_cookies(name="session-id", domain="my-origin.com")Arguments
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. For browser_context.request and page.request, this is equivalent to calling browser_context.cookies() on the corresponding browser context.
Arguments
Returns
Array<Object>Sends 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
Target URL.
data string | Buffer | Serializable (optional) Added in: v1.17
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional) Added in: v1.17
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional) Added in: v1.17
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string Added in: v1.17
File name
mime_type string Added in: v1.17
File type
buffer Buffer Added in: v1.17
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseAll responses returned by api_request_context.get() and similar methods are stored in the memory, so that you can later call api_response.body().This method discards all its resources, calling any method on disposed APIRequestContext will throw an exception.
Arguments
Sends 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:
data = {
"title": "Book Title",
"body": "John Doe",
}
api_request_context.fetch("https://example.com/api/createBook", method="post", data=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:
api_request_context.fetch(
"https://example.com/api/uploadScript", method="post",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})Arguments
url_or_request string | Request
Target URL or Request to get all parameters from.
data string | Buffer | Serializable (optional)
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional)
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional)
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string
File name
mime_type string
File type
buffer Buffer
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseSends 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:
query_params = {
"isbn": "1234",
"page": "23"
}
api_request_context.get("https://example.com/api/getText", params=query_params)Arguments
Target URL.
data string | Buffer | Serializable (optional) Added in: v1.26
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional) Added in: v1.26
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional) Added in: v1.26
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string Added in: v1.26
File name
mime_type string Added in: v1.26
File type
buffer Buffer Added in: v1.26
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseSends 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
Target URL.
data string | Buffer | Serializable (optional) Added in: v1.26
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional) Added in: v1.26
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional) Added in: v1.26
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string Added in: v1.26
File name
mime_type string Added in: v1.26
File type
buffer Buffer Added in: v1.26
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseSends 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
Target URL.
data string | Buffer | Serializable (optional)
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional)
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional)
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string
File name
mime_type string
File type
buffer Buffer
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseSends 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:
data = {
"title": "Book Title",
"body": "John Doe",
}
api_request_context.post("https://example.com/api/createBook", data=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):
formData = {
"title": "Book Title",
"body": "John Doe",
}
api_request_context.post("https://example.com/api/findBook", form=formData)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:
api_request_context.post(
"https://example.com/api/uploadScript'",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})Arguments
Target URL.
data string | Buffer | Serializable (optional)
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional)
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional)
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string
File name
mime_type string
File type
buffer Buffer
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseSends 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
Target URL.
data string | Buffer | Serializable (optional)
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.
fail_on_status_code boolean (optional)
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
form Object<string, string | float | boolean> | FormData (optional)
Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided. Use FormData to send multiple values for the same field.
headers Object<string, string> (optional)
Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.
ignore_https_errors boolean (optional)
Whether to ignore HTTPS errors when sending network requests. Defaults to false.
max_redirects int (optional) Added in: v1.26
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.
max_retries int (optional) Added in: v1.46
Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.
multipart Object<string, string | float | boolean | ReadStream | Object> | FormData (optional)
Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use FormData to send multiple files in the same field.
name string
File name
mime_type string
File type
buffer Buffer
File content
params Object<string, string | float | boolean> | string (optional)
Query parameters to be sent with the URL.
Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
Returns
APIResponseReturns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
Arguments
indexed_db boolean (optional) Added in: v1.51
Set to true to include IndexedDB in the storage state snapshot.
opfs boolean (optional) Added in: v1.63
Set to true to include the origin private file system in the storage state snapshot.
The file path to save the storage state to. If path is 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
ObjectTracing recorder for requests made through this API request context.
Type
Tracing