APIRequestContext
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 associated with it APIRequestContext instance which shares cookie storage with the browser context and can be accessed via browser_context.request or page.request. It is also possible to create a new APIRequestContext instance manually by calling api_request.new_context(**kwargs).
Cookie management
APIRequestContext returned by browser_context.request and page.request shares cookie storage with the corresponding BrowserContext. Each API request will have Cookie
header populated with the values from the browser context. If the API response contains Set-Cookie
header it will automatically update BrowserContext cookies and requests made from the page will pick them up. This means that if you log in using this API, your e2e test will be logged in and vice versa.
If you want API requests to not interfere with the browser cookies you should create a new APIRequestContext by calling api_request.new_context(**kwargs). Such APIRequestContext
object will have its own isolated cookie storage.
- Sync
- Async
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"}'
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())
- api_request_context.delete(url, **kwargs)
- api_request_context.dispose()
- api_request_context.fetch(url_or_request, **kwargs)
- api_request_context.get(url, **kwargs)
- api_request_context.head(url, **kwargs)
- api_request_context.patch(url, **kwargs)
- api_request_context.post(url, **kwargs)
- api_request_context.put(url, **kwargs)
- api_request_context.storage_state(**kwargs)
api_request_context.delete(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set. Added in: v1.17#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. Added in: v1.17#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content. Added in: v1.17#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
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.
api_request_context.dispose()
Added in: v1.16All responses returned by api_request_context.get(url, **kwargs) and similar methods are stored in the memory, so that you can later call api_response.body(). This method discards all stored responses, and makes api_response.body() throw "Response disposed" error.
api_request_context.fetch(url_or_request, **kwargs)
Added in: v1.16url_or_request
<str|Request> Target URL or Request to get all parameters from.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set.#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided.#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#method
<str> If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content.#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
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.
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 encode it as form fields with multipart/form-data
encoding. You can achieve that with Playwright API like this:
api_request_context.fetch(
"https://example.com/api/uploadScrip'",
method="post",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})
api_request_context.get(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set. Added in: v1.26#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. Added in: v1.26#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content. Added in: v1.26#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
Sends 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.
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)
api_request_context.head(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set. Added in: v1.26#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. Added in: v1.26#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content. Added in: v1.26#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
Sends 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.
api_request_context.patch(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set.#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided.#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content.#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
Sends 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.
api_request_context.post(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set.#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided.#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content.#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
Sends 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.
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. You can achieve that with Playwright API like this:
api_request_context.post(
"https://example.com/api/uploadScrip'",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})
api_request_context.put(url, **kwargs)
Added in: v1.16url
<str> Target URL.#data
<str|bytes|Serializable> Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-type
header will be set toapplication/json
if not explicitly set. Otherwise thecontent-type
header will be set toapplication/octet-stream
if not explicitly set.#fail_on_status_code
<bool> Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.#form
<Dict[str, str|float|bool]> Provides an object that will be serialized as html form usingapplication/x-www-form-urlencoded
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided.#headers
<Dict[str, str]> Allows to set HTTP headers.#ignore_https_errors
<bool> Whether to ignore HTTPS errors when sending network requests. Defaults tofalse
.#max_redirects
<int> Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to20
. Pass0
to not follow redirects. Added in: v1.26#multipart
<Dict[str, str|float|bool|[ReadStream]|Dict]> Provides an object that will be serialized as html form usingmultipart/form-data
encoding and sent as this request body. If this parameter is specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed either asfs.ReadStream
or as file-like object containing file name, mime-type and its content.#params
<Dict[str, str|float|bool]> Query parameters to be sent with the URL.#timeout
<float> Request timeout in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout.#- returns:APIResponse># <
Sends 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.
api_request_context.storage_state(**kwargs)
Added in: v1.16path
<Union[str, pathlib.Path]> The file path to save the storage state to. Ifpath
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:Dict># <
Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.