Skip to main content

APIRequestContext

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.

Each Playwright browser context has associated with it APIRequestContext instance which shares cookie storage with the browser context and can be accessed via BrowserContext.APIRequest or Page.APIRequest. It is also possible to create a new APIRequestContext instance manually by calling ApiRequest.NewContextAsync().

Cookie management

APIRequestContext returned by BrowserContext.APIRequest and Page.APIRequest shares cookie storage with the corresponding BrowserContext. Each API request will have Cookie header populated with the values from the browser context. If the API response contains Set-Cookie header it will automatically update BrowserContext cookies and requests made from the page will pick them up. This means that if you log in using this API, your e2e test will be logged in and vice versa.

If you want API requests to not interfere with the browser cookies you should create a new APIRequestContext by calling ApiRequest.NewContextAsync(). Such APIRequestContext object will have its own isolated cookie storage.


Methods

CreateFormData

Added in: v1.23 apiRequestContext.CreateFormData

Creates a new FormData instance which is used for providing form and multipart data when making HTTP requests.

Usage

ApiRequestContext.CreateFormData

Returns


DeleteAsync

Added in: v1.16 apiRequestContext.DeleteAsync

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.

Usage

await ApiRequestContext.DeleteAsync(url, options);

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextDeleteOptions? (optional)

    • Data|DataByte|DataObject string?|byte[]?|[object]? (optional) Added in: v1.17#

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


DisposeAsync

Added in: v1.16 apiRequestContext.DisposeAsync

All responses returned by ApiRequestContext.GetAsync() and similar methods are stored in the memory, so that you can later call ApiResponse.BodyAsync().This method discards all its resources, calling any method on disposed APIRequestContext will throw an exception.

Usage

await ApiRequestContext.DisposeAsync();

Returns


FetchAsync

Added in: v1.16 apiRequestContext.FetchAsync

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 objects can be passed directly to the request.

Usage

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 });

The common way to send file(s) in the body of a request is to encode it as form fields with multipart/form-data encoding. You can achieve that with Playwright API like this:

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 });

Arguments

  • urlOrRequest string|Request#

    Target URL or Request to get all parameters from.

  • options ApiRequestContextFetchOptions? (optional)

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

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • Method string? (optional)#

      If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


GetAsync

Added in: v1.16 apiRequestContext.GetAsync

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.

Usage

Request parameters can be configured with params option, they will be serialized into the URL search parameters:

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

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextGetOptions? (optional)

    • Data|DataByte|DataObject string?|byte[]?|[object]? (optional) Added in: v1.26#

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


HeadAsync

Added in: v1.16 apiRequestContext.HeadAsync

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.

Usage

await ApiRequestContext.HeadAsync(url, options);

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextHeadOptions? (optional)

    • Data|DataByte|DataObject string?|byte[]?|[object]? (optional) Added in: v1.26#

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


PatchAsync

Added in: v1.16 apiRequestContext.PatchAsync

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.

Usage

await ApiRequestContext.PatchAsync(url, options);

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextPatchOptions? (optional)

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

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


PostAsync

Added in: v1.16 apiRequestContext.PostAsync

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.

Usage

JSON objects can be passed directly to the request:

var data = new Dictionary<string, object>() {
{ "firstNam", "John" },
{ "lastName", "Doe" }
};
await request.PostAsync("https://example.com/api/createBook", new() { DataObject = 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):

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 });

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. You can achieve that with Playwright API like this:

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 });

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextPostOptions? (optional)

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

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


PutAsync

Added in: v1.16 apiRequestContext.PutAsync

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.

Usage

await ApiRequestContext.PutAsync(url, options);

Arguments

  • url string#

    Target URL.

  • options ApiRequestContextPutOptions? (optional)

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

      Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

    • FailOnStatusCode bool? (optional)#

      Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

    • 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> (optional)#

      Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

    • IgnoreHTTPSErrors bool? (optional)#

      Whether to ignore HTTPS errors when sending network requests. Defaults to false.

    • MaxRedirects int? (optional) Added in: v1.26#

      Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

    • 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 either as fs.ReadStream or 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]> (optional)#

      Query parameters to be sent with the URL.

    • Timeout [float]? (optional)#

      Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

Returns


StorageStateAsync

Added in: v1.16 apiRequestContext.StorageStateAsync

Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.

Usage

await ApiRequestContext.StorageStateAsync(options);

Arguments

  • options ApiRequestContextStorageStateOptions? (optional)
    • Path string? (optional)#

      The file path to save the storage state to. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.

Returns