APIRequestContext
此 API 用于 Web API 测试。你可以使用它来触发 API 端点、配置微服务、准备环境或为端到端测试准备服务。
🌐 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.
每个 Playwright 浏览器上下文都关联有一个 APIRequestContext 实例,该实例与浏览器上下文共享 cookie 存储,并且可以通过 browser_context.request 或 page.request 访问。也可以通过调用 api_request.new_context() 手动创建一个新的 APIRequestContext 实例。
🌐 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().
Cookie 管理
APIRequestContext 由 browser_context.request 和 page.request 返回,并与对应的 BrowserContext 共享 Cookie 存储。每个 API 请求都会在 Cookie 头部填充来自浏览器上下文的值。如果 API 响应包含 Set-Cookie 头部,它将自动更新 BrowserContext 的 Cookie,并且页面发出的请求将会使用这些 Cookie。这意味着如果你使用此 API 登录,你的端到端测试也会保持登录状态,反之亦然。
如果你希望 API 请求不干扰浏览器的 cookies,你应该通过调用 api_request.new_context() 创建一个新的 APIRequestContext。这样的 APIRequestContext 对象将拥有自己独立的 cookie 存储。
🌐 If you want API requests to not interfere with the browser cookies you should create a new APIRequestContext by calling api_request.new_context(). 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())
方法
🌐 Methods
delete
Added in: v1.16发送 HTTP(S) DELETE 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 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.delete(url)
api_request_context.delete(url, **kwargs)
参数
-
目标网址。
-
datastr | bytes | Dict (optional) Added in: v1.17#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional) Added in: v1.17#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional) Added in: v1.17#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
dispose
Added in: v1.16api_request_context.get() 和类似方法返回的所有响应都会被存储在内存中,以便你以后可以调用 api_response.body()。该方法会释放其所有资源,对已释放的 APIRequestContext 调用任何方法都会抛出异常。
🌐 All 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.
用法
api_request_context.dispose()
api_request_context.dispose(**kwargs)
参数
返回
fetch
Added in: v1.16发送 HTTP(S) 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并从响应中更新上下文 cookie。该方法会自动跟随重定向。
🌐 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 对象可以直接传递给请求:
🌐 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)
在请求正文中发送文件的常见方式是将它们作为表单字段上传,使用 multipart/form-data 编码,通过指定 multipart 参数:
🌐 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);",
},
})
参数
-
从中获取所有参数的目标 URL 或请求。
-
datastr | bytes | Dict (optional)#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional)#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional)#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
get
Added in: v1.16发送 HTTP(S) GET 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 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.
用法
请求参数可以通过 params 选项进行配置,它们将被序列化为 URL 查询参数:
🌐 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)
参数
-
目标网址。
-
datastr | bytes | Dict (optional) Added in: v1.26#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional) Added in: v1.26#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional) Added in: v1.26#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
head
Added in: v1.16发送 HTTP(S) HEAD 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 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.head(url)
api_request_context.head(url, **kwargs)
参数
-
目标网址。
-
datastr | bytes | Dict (optional) Added in: v1.26#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional) Added in: v1.26#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional) Added in: v1.26#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
patch
Added in: v1.16发送 HTTP(S) PATCH 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 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.patch(url)
api_request_context.patch(url, **kwargs)
参数
-
目标网址。
-
datastr | bytes | Dict (optional)#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional)#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional)#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
post
Added in: v1.16发送 HTTP(S) POST 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 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 对象可以直接传递给请求:
🌐 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)
要将表单数据发送到服务器,请使用 form 选项。其值将使用 application/x-www-form-urlencoded 编码方式编码到请求正文中(下面介绍如何使用 multipart/form-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)
在请求体中发送文件的常见方法是将它们作为表单字段上传,并使用 multipart/form-data 编码。使用 [FormData] 构建请求体,并将其作为 multipart 参数传递给请求:
🌐 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);",
},
})
参数
-
目标网址。
-
datastr | bytes | Dict (optional)#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional)#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional)#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
put
Added in: v1.16发送 HTTP(S) PUT 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并从响应中更新上下文的 cookie。该方法会自动跟随重定向。
🌐 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.put(url)
api_request_context.put(url, **kwargs)
参数
-
目标网址。
-
datastr | bytes | Dict (optional)#允许设置请求的 POST 数据。如果 data 参数是一个对象,它将被序列化为 JSON 字符串,并且如果未显式设置,
content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream。 -
fail_on_status_codebool (optional)#是否对除了 2xx 和 3xx 之外的响应代码抛出异常。默认情况下,响应对象会返回所有状态代码。
-
formDict[str, str | float | bool] (optional)#提供一个对象,该对象将使用
application/x-www-form-urlencoded编码序列化为 HTML 表单并作为此请求的主体发送。如果指定了此参数,除非明确提供,否则content-type头将被设置为application/x-www-form-urlencoded。 -
headersDict[str, str] (optional)#允许设置 HTTP 头。这些头将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errorsbool (optional)#发送网络请求时是否忽略 HTTPS 错误。默认值为
false。 -
max_redirectsint (optional) Added in: v1.26#自动跟随的请求重定向的最大次数。如果超过该次数,将抛出错误。默认值为
20。传入0可不跟随重定向。 -
max_retriesint (optional) Added in: v1.46#网络错误应重试的最大次数。目前仅重试
ECONNRESET错误。不基于 HTTP 响应码进行重试。如果超过限制,将抛出错误。默认值为0- 不重试。 -
multipartDict[str, str | float | bool | [ReadStream] | Dict] (optional)#提供一个对象,该对象将使用
multipart/form-data编码序列化为 HTML 表单,并作为此请求的主体发送。如果指定了此参数,则除非明确提供,否则会将content-type头设置为multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。 -
paramsDict[str, str | float | bool] | str (optional)#与 URL 一起发送的查询参数。
-
请求超时时间(毫秒)。默认值为
30000(30 秒)。传入0可禁用超时。
返回
storage_state
Added in: v1.16返回此请求上下文的存储状态,包含当前 cookie 和本地存储快照(如果已传递给构造函数)。
🌐 Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
用法
api_request_context.storage_state()
api_request_context.storage_state(**kwargs)
参数
-
indexed_dbbool (optional) Added in: v1.51#设置为
true以在存储状态快照中包含 IndexedDB。 -
pathUnion[str, pathlib.Path] (optional)#要保存存储状态的文件路径。如果path是相对路径,则相对于当前工作目录解析。如果未提供路径,存储状态仍然会返回,但不会保存到磁盘。
返回