跳至主要内容

APIRequestContext

该API用于Web API测试。您可以使用它来触发API端点、配置微服务、为端到端测试准备环境或服务。

每个Playwright浏览器上下文都关联着一个APIRequestContext实例,该实例与浏览器上下文共享cookie存储,可以通过browserContext.requestpage.request访问。也可以通过调用apiRequest.newContext()手动创建新的APIRequestContext实例。

Cookie管理

APIRequestContextbrowserContext.requestpage.request 返回,它与对应的 BrowserContext 共享 cookie 存储。每个 API 请求都会用浏览器上下文中的值填充 Cookie 头。如果 API 响应包含 Set-Cookie 头,它将自动更新 BrowserContext 的 cookies,并且从页面发出的请求会获取它们。这意味着如果你使用此 API 登录,你的端到端测试也会保持登录状态,反之亦然。

如果您希望API请求不干扰浏览器cookie,应该通过调用apiRequest.newContext()来创建一个新的APIRequestContext。这样的APIRequestContext对象将拥有自己独立的cookie存储空间。


方法

删除

Added in: v1.16 apiRequestContext.delete

发送HTTP(S) DELETE请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

await apiRequestContext.delete(url);
await apiRequestContext.delete(url, options);

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选) 添加于: v1.17#

      允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,content-type头将被设置为application/json。否则,如果没有明确设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选) 添加于: 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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


dispose

Added in: v1.16 apiRequestContext.dispose

所有由apiRequestContext.get()及类似方法返回的响应都存储在内存中,以便您稍后可以调用apiResponse.body()。此方法会释放所有资源,在已释放的APIRequestContext上调用任何方法都将抛出异常。

用法

await apiRequestContext.dispose();
await apiRequestContext.dispose(options);

参数

  • options Object (optional)
    • reason string (可选) 添加于: v1.45#

      要报告给因上下文销毁而中断的操作的原因。

返回


fetch

Added in: v1.16 apiRequestContext.fetch

发送HTTP(S)请求并返回其响应。该方法将从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

JSON对象可以直接传递给请求:

await request.fetch('https://example.com/api/createBook', {
method: 'post',
data: {
title: 'Book Title',
author: 'John Doe',
}
});

在请求体中发送文件的常见方式是使用multipart/form-data编码将它们作为表单字段上传,通过指定multipart参数来实现:

const form = new FormData();
form.set('name', 'John');
form.append('name', 'Doe');
// Send two file fields with the same name.
form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
await request.fetch('https://example.com/api/uploadForm', {
multipart: form
});

参数

  • urlOrRequest string | Request#

    目标URL或Request,用于获取所有参数。

  • options Object (可选)

    • data string | Buffer | Serializable (可选)#

      允许设置请求的post数据。如果data参数是对象,它将被序列化为json字符串,并且如果未显式设置,content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • method string (可选)#

      如果设置将更改fetch方法(例如PUTPOST)。如果未指定,则使用GET方法。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选)#

      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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


获取

Added in: v1.16 apiRequestContext.get

发送HTTP(S) GET请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

请求参数可以通过params选项进行配置,它们将被序列化为URL搜索参数:

// Passing params as object
await request.get('https://example.com/api/getText', {
params: {
'isbn': '1234',
'page': 23,
}
});

// Passing params as URLSearchParams
const searchParams = new URLSearchParams();
searchParams.set('isbn', '1234');
searchParams.append('page', 23);
searchParams.append('page', 24);
await request.get('https://example.com/api/getText', { params: searchParams });

// Passing params as string
const queryString = 'isbn=1234&page=23&page=24';
await request.get('https://example.com/api/getText', { params: queryString });

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选) 添加于: v1.26#

      允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,content-type头将被设置为application/json。否则,如果没有明确设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选) 添加于: 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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


头部

Added in: v1.16 apiRequestContext.head

发送HTTP(S) HEAD请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

await apiRequestContext.head(url);
await apiRequestContext.head(url, options);

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选) 添加于: v1.26#

      允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果没有明确设置,content-type头将被设置为application/json。否则,如果没有明确设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选) 添加于: 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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


补丁

Added in: v1.16 apiRequestContext.patch

发送HTTP(S) PATCH请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

await apiRequestContext.patch(url);
await apiRequestContext.patch(url, options);

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选)#

      允许设置请求的post数据。如果data参数是一个对象,它将被序列化为json字符串,并且如果未显式设置,content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选)#

      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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


发布

Added in: v1.16 apiRequestContext.post

发送HTTP(S) POST请求并返回其响应。该方法将从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

JSON对象可以直接传递给请求:

await request.post('https://example.com/api/createBook', {
data: {
title: 'Book Title',
author: 'John Doe',
}
});

要将表单数据发送到服务器,请使用 form 选项。其值将被编码为 application/x-www-form-urlencoded 格式的请求体(下文将介绍如何使用 multipart/form-data 表单编码来发送文件):

await request.post('https://example.com/api/findBook', {
form: {
title: 'Book Title',
author: 'John Doe',
}
});

在请求体中发送文件的常见方式是使用multipart/form-data编码将它们作为表单字段上传。使用FormData构建请求体,并将其作为multipart参数传递给请求:

const form = new FormData();
form.set('name', 'John');
form.append('name', 'Doe');
// Send two file fields with the same name.
form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
await request.post('https://example.com/api/uploadForm', {
multipart: form
});

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选)#

      允许设置请求的post数据。如果data参数是对象,它将被序列化为json字符串,并且如果未显式设置,content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选)#

      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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


put

Added in: v1.16 apiRequestContext.put

发送HTTP(S) PUT请求并返回其响应。该方法会从上下文中填充请求cookie,并根据响应更新上下文cookie。该方法会自动跟随重定向。

用法

await apiRequestContext.put(url);
await apiRequestContext.put(url, options);

参数

  • url string#

    目标URL。

  • options Object (可选)

    • data string | Buffer | Serializable (可选)#

      允许设置请求的post数据。如果data参数是对象,它将被序列化为json字符串,并且如果未显式设置,content-type头将被设置为application/json。否则,如果未显式设置,content-type头将被设置为application/octet-stream

    • failOnStatusCode boolean (可选)#

      是否在响应码不是2xx和3xx时抛出异常。默认情况下会返回所有状态码的响应对象。

    • form Object<string, string | number | 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.

    • headers Object<string, string> (可选)#

      允许设置HTTP头信息。这些头信息将应用于获取的请求以及由其发起的任何重定向。

    • ignoreHTTPSErrors boolean (可选)#

      发送网络请求时是否忽略HTTPS错误。默认为false

    • maxRedirects number (可选) 添加于: v1.26#

      自动跟随的最大请求重定向次数。如果超过该次数将抛出错误。默认为20。传递0表示不跟随重定向。

    • maxRetries number (可选) 添加于: v1.46#

      网络错误应重试的最大次数。目前仅会重试ECONNRESET错误。不会根据HTTP响应码进行重试。如果超过限制将抛出错误。默认为0 - 不重试。

    • multipart FormData | Object<string, string | number | boolean | ReadStream | Object> (可选)#

      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 either as fs.ReadStream or as file-like object containing file name, mime-type and its content.

    • params Object<string, string | number | boolean> | URLSearchParams | string (可选)#

      要随URL一起发送的查询参数。

    • timeout number (可选)#

      请求超时时间,单位为毫秒。默认为 30000 (30秒)。传入 0 表示禁用超时。

返回


storageState

Added in: v1.16 apiRequestContext.storageState

返回此请求上下文的存储状态,如果传递给了构造函数,则包含当前cookie和本地存储快照。

用法

await apiRequestContext.storageState();
await apiRequestContext.storageState(options);

参数

  • options Object (optional)
    • indexedDB boolean (可选) 添加于: v1.51#

      设置为 true 以在存储状态快照中包含 IndexedDB。

    • path string (可选)#

      存储状态要保存到的文件路径。如果path是相对路径,则相对于当前工作目录解析。如果未提供路径,仍会返回存储状态,但不会保存到磁盘。

返回