跳至主要内容

APIRequestContext

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

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

Cookie管理

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

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


方法

CreateFormData

Added in: v1.23 apiRequestContext.CreateFormData

创建一个新的FormData实例,用于在发起HTTP请求时提供表单和多部分数据。

用法

ApiRequestContext.CreateFormData

返回


DeleteAsync

Added in: v1.16 apiRequestContext.DeleteAsync

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

用法

await ApiRequestContext.DeleteAsync(url, options);

参数

  • url string#

    目标URL。

  • options ApiRequestContextDeleteOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选) 添加于: v1.17#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional) Added in: 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 as file-like object containing file name, mime-type and its content.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


DisposeAsync

Added in: v1.16 apiRequestContext.DisposeAsync

所有通过ApiRequestContext.GetAsync()及类似方法返回的响应都存储在内存中,以便后续可以调用ApiResponse.BodyAsync()。此方法会释放其所有资源,在已释放的APIRequestContext上调用任何方法都将抛出异常。

用法

await ApiRequestContext.DisposeAsync(options);

参数

  • options ApiRequestContextDisposeOptions? (optional)
    • Reason string? (可选) 新增于: v1.45#

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

返回


FetchAsync

Added in: v1.16 apiRequestContext.FetchAsync

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

用法

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

var data = new Dictionary<string, object>() {
{ "title", "Book Title" },
{ "body", "John Doe" }
};
await Request.FetchAsync("https://example.com/api/createBook", new() { Method = "post", DataObject = data });

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

var file = new FilePayload()
{
Name = "f.js",
MimeType = "text/javascript",
Buffer = System.Text.Encoding.UTF8.GetBytes("console.log(2022);")
};
var multipart = Context.APIRequest.CreateFormData();
multipart.Set("fileField", file);
await Request.FetchAsync("https://example.com/api/uploadScript", new() { Method = "post", Multipart = multipart });

参数

  • urlOrRequest string | Request#

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

  • options ApiRequestContextFetchOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选)#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Method string? (可选)#

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

    • Multipart FormData? (optional)#

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

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


GetAsync

Added in: v1.16 apiRequestContext.GetAsync

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

用法

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

var queryParams = new Dictionary<string, object>()
{
{ "isbn", "1234" },
{ "page", 23 },
};
await request.GetAsync("https://example.com/api/getText", new() { Params = queryParams });

参数

  • url string#

    目标URL。

  • options ApiRequestContextGetOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选) 新增于: v1.26#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional) Added in: 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 as file-like object containing file name, mime-type and its content.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


HeadAsync

Added in: v1.16 apiRequestContext.HeadAsync

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

用法

await ApiRequestContext.HeadAsync(url, options);

参数

  • url string#

    目标URL。

  • options ApiRequestContextHeadOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选) 添加于: v1.26#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional) Added in: 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 as file-like object containing file name, mime-type and its content.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


PatchAsync

Added in: v1.16 apiRequestContext.PatchAsync

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

用法

await ApiRequestContext.PatchAsync(url, options);

参数

  • url string#

    目标URL。

  • options ApiRequestContextPatchOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选)#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional)#

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

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


PostAsync

Added in: v1.16 apiRequestContext.PostAsync

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

用法

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

var data = new Dictionary<string, object>() {
{ "firstName", "John" },
{ "lastName", "Doe" }
};
await request.PostAsync("https://example.com/api/createBook", new() { DataObject = data });

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

var formData = Context.APIRequest.CreateFormData();
formData.Set("title", "Book Title");
formData.Set("body", "John Doe");
await request.PostAsync("https://example.com/api/findBook", new() { Form = formData });

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

var file = new FilePayload()
{
Name = "f.js",
MimeType = "text/javascript",
Buffer = System.Text.Encoding.UTF8.GetBytes("console.log(2022);")
};
var multipart = Context.APIRequest.CreateFormData();
multipart.Set("fileField", file);
await request.PostAsync("https://example.com/api/uploadScript", new() { Multipart = multipart });

参数

  • url string#

    目标URL。

  • options ApiRequestContextPostOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选)#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional)#

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

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


PutAsync

Added in: v1.16 apiRequestContext.PutAsync

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

用法

await ApiRequestContext.PutAsync(url, options);

参数

  • url string#

    目标URL。

  • options ApiRequestContextPutOptions? (可选)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (可选)#

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

    • FailOnStatusCode bool? (可选)#

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

    • Form 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.

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Headers IDictionary?<string, string> (可选)#

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

    • IgnoreHTTPSErrors bool? (可选)#

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

    • MaxRedirects int? (可选) 添加于: v1.26#

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

    • MaxRetries int? (可选) 添加于: v1.46#

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

    • Multipart FormData? (optional)#

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

      An instance of FormData can be created via ApiRequestContext.CreateFormData.

    • Params IDictionary?<string, [object]> (可选)#

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

    • ParamsString string? (可选) 添加于: v1.47#

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

    • Timeout [float]? (可选)#

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

返回


StorageStateAsync

Added in: v1.16 apiRequestContext.StorageStateAsync

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

用法

await ApiRequestContext.StorageStateAsync(options);

参数

  • options ApiRequestContextStorageStateOptions? (optional)
    • IndexedDB bool? (可选) 添加于: v1.51#

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

    • Path string? (可选)#

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

返回