Rayrun

What is the difference between APIRequestContext associated with a BrowserContext and an isolated APIRequestContext in terms of handling cookies?

Answer

The main difference between an APIRequestContext associated with a BrowserContext and an isolated APIRequestContext lies in how they handle cookies. When you create an APIRequestContext associated with a BrowserContext using apiRequest.newContext(), it populates the request's Cookie header from the browser context and automatically updates browser cookies if the APIResponse has a Set-Cookie header. This is useful when you want to maintain the same session or authentication state across multiple requests.

On the other hand, if you don't want the APIRequestContext to use and update cookies from the browser context, you can manually create a new instance of APIRequestContext. This isolated instance will have its own separate cookies and won't affect the browser context's cookies.

Keep in mind that there might be differences in how the server treats requests made with an rq.post call and an APIRequest attached to a browser context page. These differences could be due to authentication, authorization mechanisms, or handling of redirects and errors. To ensure consistent behavior across different contexts, review the options available for customizing network requests in @playwright/test, such as setting HTTP headers or ignoring HTTPS errors.

Here's an example of creating an APIRequestContext associated with a BrowserContext:

import { test, expect } from '@playwright/test';

test('API request with browser context', async ({ browser }) => {
  const context = await browser.newContext();
  const apiRequest = await context.apiRequest();
  const response = await apiRequest.post('https://ray.run/api/endpoint', {
    headers: { 'Content-Type': 'application/json' },
    data: { key: 'value' },
  });

  expect(response.status()).toBe(200);
});

And here's an example of creating an isolated APIRequestContext:

import { test, expect, APIRequestContext } from '@playwright/test';

test('API request with isolated context', async () => {
  const apiRequest = new APIRequestContext();
  const response = await apiRequest.post('https://ray.run/api/endpoint', {
    headers: { 'Content-Type': 'application/json' },
    data: { key: 'value' },
  });

  expect(response.status()).toBe(200);
});
Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].