APIRequestContext
该API用于Web API测试。您可以使用它来触发API端点、配置微服务、为端到端测试准备环境或服务。
每个Playwright浏览器上下文都关联着一个APIRequestContext实例,该实例与浏览器上下文共享cookie存储,可以通过browser_context.request或page.request访问。也可以通过调用api_request.new_context()手动创建新的APIRequestContext实例。
Cookie管理
APIRequestContext 由 browser_context.request 和 page.request 返回,与对应的 BrowserContext 共享 cookie 存储。每个 API 请求都会用浏览器上下文中的值填充 Cookie
头。如果 API 响应包含 Set-Cookie
头,它将自动更新 BrowserContext 的 cookies,并且从页面发出的请求会获取这些 cookies。这意味着如果您使用此 API 登录,您的端到端测试也会保持登录状态,反之亦然。
如果您希望API请求不影响浏览器cookie,您应该通过调用api_request.new_context()来创建一个新的APIRequestContext。这样的APIRequestContext
对象将拥有自己独立的cookie存储空间。
- Sync
- 异步
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())
方法
删除
Added in: v1.16发送HTTP(S) DELETE请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
api_request_context.delete(url)
api_request_context.delete(url, **kwargs)
参数
-
目标URL。
-
data
str | bytes | Dict (可选) 添加于: v1.17#允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,
content-type
头将被设置为application/json
。否则,如果没有明确设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过此数字将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选) 添加于: 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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
dispose
Added in: v1.16通过api_request_context.get()及类似方法返回的所有响应都存储在内存中,以便您稍后可以调用api_response.body()。此方法会释放所有资源,对已释放的APIRequestContext调用任何方法都将抛出异常。
用法
api_request_context.dispose()
api_request_context.dispose(**kwargs)
参数
返回
fetch
Added in: v1.16发送HTTP(S)请求并返回其响应。该方法将从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
JSON对象可以直接传递给请求:
data = {
"title": "Book Title",
"body": "John Doe",
}
api_request_context.fetch("https://example.com/api/createBook", method="post", data=data)
在请求体中发送文件的常见方式是使用multipart/form-data
编码将它们作为表单字段上传,通过指定multipart
参数来实现:
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或Request对象,用于获取所有参数。
-
允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,
content-type
头将被设置为application/json
。否则,如果没有明确设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应状态码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选)#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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
获取
Added in: v1.16发送HTTP(S) GET请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
请求参数可以通过params
选项进行配置,它们将被序列化为URL搜索参数:
query_params = {
"isbn": "1234",
"page": "23"
}
api_request_context.get("https://example.com/api/getText", params=query_params)
参数
-
目标URL。
-
data
str | bytes | Dict (可选) 添加于: v1.26#允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果未显式设置,
content-type
头将被设置为application/json
。否则,如果未显式设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过此数字将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选) 添加于: 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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
头部
Added in: v1.16发送HTTP(S) HEAD请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
api_request_context.head(url)
api_request_context.head(url, **kwargs)
参数
-
目标URL。
-
data
str | bytes | Dict (可选) 添加于: v1.26#允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果未显式设置,
content-type
头将被设置为application/json
。否则,如果未显式设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过此数字将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选) 添加于: 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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
补丁
Added in: v1.16发送HTTP(S) PATCH请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
api_request_context.patch(url)
api_request_context.patch(url, **kwargs)
参数
-
目标URL。
-
允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,
content-type
头将被设置为application/json
。否则,如果没有明确设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应状态码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选)#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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
发布
Added in: v1.16发送HTTP(S) POST请求并返回其响应。该方法将从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
JSON对象可以直接传递给请求:
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
表单编码来发送文件):
formData = {
"title": "Book Title",
"body": "John Doe",
}
api_request_context.post("https://example.com/api/findBook", form=formData)
在请求体中发送文件的常见方式是使用multipart/form-data
编码将它们作为表单字段上传。使用[FormData]构建请求体,并将其作为multipart
参数传递给请求:
api_request_context.post(
"https://example.com/api/uploadScript'",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})
参数
-
目标URL。
-
允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,
content-type
头将被设置为application/json
。否则,如果没有明确设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应状态码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选)#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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
put
Added in: v1.16发送HTTP(S) PUT请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。
用法
api_request_context.put(url)
api_request_context.put(url, **kwargs)
参数
-
目标URL。
-
允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,
content-type
头将被设置为application/json
。否则,如果没有明确设置,content-type
头将被设置为application/octet-stream
。 -
fail_on_status_code
bool (可选)#是否在响应状态码非2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。
-
form
Dict[str, str | float | bool] (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 specifiedcontent-type
header will be set toapplication/x-www-form-urlencoded
unless explicitly provided. -
允许设置HTTP头信息。这些头部将应用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors
bool (可选)#发送网络请求时是否忽略HTTPS错误。默认为
false
。 -
max_redirects
int (可选) 添加于: v1.26#自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为
20
。传递0
表示不跟随重定向。 -
max_retries
int (可选) 添加于: v1.46#网络错误应重试的最大次数。当前仅会重试
ECONNRESET
错误。不会基于HTTP响应码进行重试。如果超过限制将抛出错误。默认为0
- 不重试。 -
multipart
Dict[str, str | float | bool | [ReadStream] | Dict] (可选)#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 specifiedcontent-type
header will be set tomultipart/form-data
unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. -
params
Dict[str, str | float | bool] | str (可选)#要随URL一起发送的查询参数。
-
请求超时时间,单位为毫秒。默认为
30000
(30秒)。传入0
表示禁用超时。
返回
storage_state
Added in: v1.16返回此请求上下文的存储状态,如果传递给了构造函数,则包含当前cookie和本地存储快照。
用法
api_request_context.storage_state()
api_request_context.storage_state(**kwargs)
参数
-
indexed_db
bool (可选) 添加于: v1.51#设置为
true
以在存储状态快照中包含 IndexedDB。 -
path
Union[str, pathlib.Path] (可选参数)#存储状态要保存到的文件路径。如果path是相对路径,则会相对于当前工作目录进行解析。如果没有提供路径,存储状态仍会返回,但不会被保存到磁盘。
返回