Exit course
Chapter 2 of 9 Intermediate 9 min read 2 quick checks Updated

The request Fixture and APIRequestContext

On this page
  1. Set up the project
  2. A first API test
  3. Request options you will use
  4. Three kinds of request context
  5. Reading a response

In this chapter you set up the course project, write a first API test, and learn the three ways Playwright gives you an HTTP client. Knowing which one you are holding matters more than it looks: they differ in which options they pick up, which cookies they share and, once you use a cloud grid, even on which machine the request is sent.

Set up the project#

Start from a normal Playwright project, as in chapter 1 of the Playwright course, then add the two schema libraries used in chapter 5:

mkdir playwright-api-course && cd playwright-api-course
npm init playwright@latest
npm install -D zod ajv

Put the two base URLs in one small module, lib/env.ts, so that every file reads them from the same place and you can point the suite at another environment with an environment variable:

export const API_URL = process.env.API_URL ?? 'https://api.practicesoftwaretesting.com';
export const UI_URL = process.env.UI_URL ?? 'https://practicesoftwaretesting.com';

Now replace the generated playwright.config.ts:

import { defineConfig, devices } from '@playwright/test';
import { API_URL, UI_URL } from './lib/env';

export default defineConfig({
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  reporter: [['list'], ['html', { open: 'never' }]],
  use: { trace: 'on-first-retry', testIdAttribute: 'data-test' },
  projects: [
    {
      name: 'api',
      testDir: './tests/api',
      use: {
        baseURL: API_URL,
        extraHTTPHeaders: { Accept: 'application/json' },
      },
    },
    {
      name: 'chromium',
      testDir: './tests/ui',
      use: { ...devices['Desktop Chrome'], baseURL: UI_URL },
    },
    {
      name: 'firefox',
      testDir: './tests/ui',
      use: { ...devices['Desktop Firefox'], baseURL: UI_URL },
    },
  ],
});

Three things to notice:

  • Projects split by folder. API tests live in tests/api and belong to the api project only. UI tests live in tests/ui and run once per browser. Without this split, every API test would run three times, once per browser project, for no benefit.
  • baseURL is per project. The shop's UI and API live on different hosts. baseURL is shared by page.goto() and the request fixture, so the API project gets the API host and the browser projects get the UI host.
  • extraHTTPHeaders adds headers to every request the project's request fixture sends. Here it asks for JSON. Chapter 3 uses the same option for an Authorization header.

testIdAttribute: 'data-test' is for the UI tests later: the shop marks its elements with data-test attributes, and this makes getByTestId() use them.

A first API test#

Create tests/api/first.spec.ts:

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

test('lists products', async ({ request }) => {
  const response = await request.get('/products');

  await expect(response).toBeOK();
  const body = await response.json();
  expect(body.data.length).toBeGreaterThan(0);
});

test('a fake write on JSONPlaceholder', async ({ request }) => {
  const response = await request.post('https://jsonplaceholder.typicode.com/posts', {
    data: { title: 'Hello', body: 'From Playwright', userId: 1 },
  });

  expect(response.status()).toBe(201);
  const created = await response.json();
  console.log(created);

  // JSONPlaceholder does not store anything: reading it back is a 404
  const readBack = await request.get(`https://jsonplaceholder.typicode.com/posts/${created.id}`);
  expect(readBack.status()).toBe(404);
});

Run only the API project:

npx playwright test --project=api
Running 2 tests using 2 workers

  ✓  2 [api] › tests/api/first.spec.ts:3:1 › lists products (214ms)
{ title: 'Hello', body: 'From Playwright', userId: 1, id: 101 }
  ✓  1 [api] › tests/api/first.spec.ts:11:1 › a fake write on JSONPlaceholder (734ms)

  2 passed (1.0s)

What happened:

  • { request } is a fixture, like { page }. You get a fresh APIRequestContext per test, configured from the project's use block, and it is disposed after the test.
  • request.get('/products') resolves the relative path against baseURL. A full URL, as in the second test, ignores baseURL.
  • data with a plain object is sent as JSON, and Playwright sets Content-Type: application/json for you.
  • toBeOK() passes for any 2xx status. Chapter 2 covers the other assertions.
  • The second test is the warning from the introduction in code form: JSONPlaceholder answers 201 with id: 101, but the post does not exist afterwards. A test that only checks the status of a write would pass against it whether your code is right or not.

Notice the timing too: about a second for both tests. No browser was started. You can prove that by pointing Playwright at a browser folder that does not exist:

PLAYWRIGHT_BROWSERS_PATH=/nonexistent npx playwright test --project=api

The API tests still pass, because nothing in them asks for page, context or browser. Fixtures are created lazily, and request does not need a browser. That fact shapes the CI setup in chapter 7.

A test POSTs a new order to a demo API, asserts 201, and passes. A colleague says it proves nothing. When are they right?

A status code is the server's claim, not proof. JSONPlaceholder, for example, answers 201 and stores nothing. Reading the record back with a GET is what proves the write happened.

Request options you will use#

Every method (get, post, put, patch, delete, head, and the generic fetch) takes the same options object. The ones that come up constantly:

Option What it does
params Query string, as an object: { q: 'pliers', page: 2 } becomes ?q=pliers&page=2, encoded for you
data Request body. An object is sent as JSON; a string or Buffer is sent as is
form Sends application/x-www-form-urlencoded fields
multipart Sends multipart/form-data, including file uploads
headers Headers for this request only, on top of extraHTTPHeaders
failOnStatusCode Throw on any status that is not 2xx or 3xx (off by default)
timeout Per-request timeout in milliseconds (30 seconds by default)

Prefer params over building query strings by hand; it handles encoding of spaces, & and non-ASCII characters, which hand-built URLs regularly get wrong.

Three kinds of request context#

Playwright has one class for HTTP, APIRequestContext, but three ways to get one. They behave differently.

1. The request fixture. One per test, configured from the project's use options (baseURL, extraHTTPHeaders, httpCredentials, storageState and so on), disposed after the test. It has its own cookie jar, separate from any browser. This is what API tests use.

2. page.request (or context.request). The request context that belongs to a browser context. It shares cookies with the browser: a cookie set by a page.request call is visible to the page, and the page's cookies are sent with page.request calls. That makes it the right tool when you need an API call "as the logged-in browser user" in a cookie-based app. You can see the difference directly:

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

test('page.request shares cookies with the page, request does not', async ({ page, request }) => {
  await page.request.get('https://the-internet.herokuapp.com/login');
  await request.get('https://jsonplaceholder.typicode.com/posts/1');
  console.log('context cookies:', (await page.context().cookies()).map((c) => `${c.domain} ${c.name}`));
  console.log('request cookies:', (await request.storageState()).cookies.map((c) => `${c.domain} ${c.name}`));
});
context cookies: [ 'the-internet.herokuapp.com rack.session' ]
request cookies: []

The session cookie that the login page set through page.request landed in the browser context. The standalone request fixture has nothing to do with it.

3. playwright.request.newContext(). A context you create yourself, with its own options. Use it when one test needs to talk to two hosts with different settings, for example an API client with an auth header next to a browser on another domain. Two rules: you must call dispose() on it when you are done, and inside a test it inherits the project's use options for anything you do not pass. Called with no arguments in the api project, newContext() still resolves /products against the API baseURL. In a browser project, it would resolve against the UI host instead, which is why the fixtures in chapter 3 always pass baseURL explicitly. This inheritance comes from the Playwright Test runner, which fills in every option you did not pass (including baseURL and extraHTTPHeaders) from the project's use block; a quick test with test.use({ baseURL, extraHTTPHeaders }) shows both arriving on a bare newContext(). Outside the runner, in a plain Node script that imports playwright, there is no project config, so nothing is inherited and relative URLs need an explicit baseURL.

Your app uses a session cookie. A UI test logs in through the browser and then needs to call /api/cart as that same user. Which client do you use?

page.request sends the browser context's cookies, so the call is made as the logged-in user. The request fixture and a new context each have their own empty cookie jar.

Reading a response#

An APIResponse gives you everything about the reply:

  • status(), statusText() and ok() (true for 2xx),
  • headers() as an object with lower-case names, and headersArray() when a header repeats (several set-cookie lines, for example),
  • json(), text() and body() (a Buffer),
  • url(), the final URL after redirects.

The body is kept in memory until the request context is disposed. For the fixtures that happens automatically at the end of the test; for contexts you create in a long-running loop, call response.dispose() or dispose the context to free memory.

You now have a project, a way to run only the API tests, and a clear picture of which client to reach for. The next chapter is about making the assertions on those responses say something useful.