APIRequestContext(类) - 666zhengyan/chinese-playwrightAPI-python GitHub Wiki
APIRequestContext
这个API用于Web API测试。您可以使用它触发API端点,配置微服务,准备环境或服务以进行端到端测试。
每个Playwright浏览器上下文都与一个APIRequestContext实例相关联,该实例与浏览器上下文共享Cookie存储,并可通过browser_context.request或page.request访问。也可以通过调用api_request.new_context()手动创建一个新的APIRequestContext实例。
Cookie管理
由browser_context.request和page.request返回的APIRequestContext与相应的BrowserContext共享Cookie存储。每个API请求都将使用浏览器上下文中的值填充Cookie标头。如果API响应包含Set-Cookie标头,则会自动更新BrowserContext的cookie,并且从页面发出的请求将获取它们。这意味着如果您使用此API登录,则您的端到端测试将被登录,反之亦然。
如果您希望API请求不干扰浏览器的Cookie,则应通过调用api_request.new_context()创建一个新的APIRequestContext。这样的APIRequestContext对象将具有其自己的隔离式Cookie存储。
- 同步
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())
方法
delete
发送HTTP(S) DELETE请求并返回其响应。该方法将从上下文中填充请求的Cookie,并从响应中更新上下文的Cookie。该方法将自动遵循重定向。
用法
api_request_context.delete(url)
api_request_context.delete(url, **kwargs)
参数
-
url 字符串类型
目标url
-
data 字符串、字节或可序列化对象(可选)
允许设置请求的数据。如果数据参数是一个对象,它将被序列化为 JSON 字符串,并且如果没有显式设置,则 content-type 标头将被设置为 application/json。否则,如果没有显式设置,content-type 标头将被设置为 application/octet-stream。
-
fail_on_status_code 布尔类型(可选)
是否在除了2xx和3xx之外的响应代码上抛出异常。默认情况下,对于所有状态码都返回响应对象。
-
form 字典类型(可选)
提供一个对象,该对象将被序列化为 HTML 表单,并使用 application/x-www-form-urlencoded 编码发送作为请求主体。如果指定了此参数,则 content-type 标头将被设置为 application/x-www-form-urlencoded,除非显式提供了其他设置。
-
headers 字典类型(可选)
允许设置HTTP头。这些头将适用于获取的请求以及由其发起的任何重定向。
-
ignore_https_errors 布尔类型(可选)
是否忽略https错误,默认不忽略。
-
max_redirects int类型(可选)
自动跟随的最大请求重定向次数。如果超过此次数,将抛出错误。默认为20。传递0以禁止跟随重定向。
-
multipart 字典类型(可选)
-
name 字符串类型 文件名称
-
mimeType 字符串 文件类型
-
buffer 字节 文件内容
-
提供一个对象,该对象将被序列化为 HTML 表单,并使用 multipart/form-data 编码发送作为请求主体。如果指定了此参数,则 content-type 标头将被设置为 multipart/form-data,除非显式提供了其他设置。文件值可以作为 fs.ReadStream 或包含文件名、mime 类型及其内容的类文件对象传递。
- params 字典类型(可选)
随着url发送的请求参数
- timeout 浮点型(可选)
默认30000ms,即30秒
返回值
- APIResponse
dispose
所有由api_request_context.get()和类似方法返回的响应都存储在内存中,因此您稍后可以调用api_response.body()。此方法丢弃所有其资源,对已释放的APIRequestContext调用任何方法都将抛出异常
用法
- api_request_context.dispose()
返回值
- NoneType
fetch
发送 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编码的表单字段。您可以使用Playwright API来实现这一点,如下所示:
api_request_context.fetch(
"https://example.com/api/uploadScrip'",
method="post",
multipart={
"fileField": {
"name": "f.js",
"mimeType": "text/javascript",
"buffer": b"console.log(2022);",
},
})
参数
-
url_or_request 字符串类型或Response类型
目标URL或请求以获取所有参数。
-
data 字符串、字节或可序列化对象(可选)
允许设置请求的POST数据。如果数据参数是一个对象,则将其序列化为JSON字符串,并且如果没有明确设置,则content-type头将被设置为application/json。否则,如果没有明确设置,则content-type头将被设置为application/octet-stream
-
fail_on_status_code 布尔类型(可选)
是否在响应代码不是2xx和3xx时抛出异常。默认情况下,对于所有状态码都返回响应对象。
-
form 字典类型(可选)
提供一个对象,该对象将以 application/x-www-form-urlencoded 编码的形式序列化为 HTML 表单,并发送作为此请求的主体。如果指定了此参数,则 content-type 标头将被设置为 application/x-www-form-urlencoded,除非显式提供了其他设置。
-
headers 字典类型(可选)
请求头
-
ignore_https_errors 布尔类型(可选)
是否忽略错误,默认不忽略。
-
max_redirects int类型(可选)
自动跟随的最大请求重定向次数。如果超过此次数,将抛出错误。默认为20。传递0以禁止跟随重定向
-
method 字符串类型(可选)
如果设置,将更改获取方法(例如 PUT 或 POST)。如果未指定,则使用 GET 方法。
-
multipart 字典类型(可选)
-
name 字符串类型 文件名称
-
mimeType 字符串类型 文件类型
-
buffer 字节 文件内容
-
提供一个对象,该对象将以 multipart/form-data 编码的形式序列化为 HTML 表单,并发送作为此请求的主体。如果指定了此参数,则 content-type 标头将被设置为 multipart/form-data,除非显式提供了其他设置。文件值可以作为 fs.ReadStream 或包含文件名、mime 类型及其内容的类文件对象传递。
-
params 字典类型(可选)
随着url发送的请求参数
-
timeout 浮点型 可选
超时时间,默认30000ms.
返回值
- APIResponse