日本語

Testing APIs Directly with Playwright’s request Fixture

​​Playwright​API Testing,E2E Testing,TypeScript

The request fixture (an object for calling APIs) that you can receive in Playwright tests lets you send HTTP requests directly to a REST API without opening a browser. You can write tests for an API with no screen (checking the responses and status codes for create, read, and delete) with the same npx playwright test command used for E2E tests. You can also use it to prepare data through the API before running UI tests.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, @playwright/test 1.63.0, and TypeScript 5.9.3. As the test target, I wrote a small Todo API in Node.js that only holds data in memory, and started it with webServer. The UI tests ran in Chromium (headless). I did not try a real external API, HTTPS, sending files with multipart, or running on a CI service.

Writing the API URL and auth header in the config file

request uses the baseURL and extraHTTPHeaders you write under use in the config file (the official API testing docs). For the test, I prepared an API that requires Authorization: Bearer test-token to create a Todo, and used the following config.

ts
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  reporter: 'list',
  workers: 1,
  use: {
    baseURL: 'http://localhost:3000',
    extraHTTPHeaders: {
      Authorization: 'Bearer test-token',
    },
  },
  webServer: {
    command: 'node server.mjs',
    url: 'http://localhost:3000/api/todos',
    stdout: 'pipe',
  },
});

Because of baseURL, you can write just the path, such as /api/todos, inside the tests. The headers in extraHTTPHeaders are attached to every request.

Testing create, read, and delete

Receive { request } in the test function, then call request.post() or request.get().

ts
// tests/todos.spec.ts
import { test, expect } from '@playwright/test';

test('Todo を作ると 201 が返り、取得できる', async ({ request }) => {
  const created = await request.post('/api/todos', {
    data: { title: '牛乳を買う' },
  });
  expect(created.status()).toBe(201);
  expect(created.headers()['content-type']).toContain('application/json');
  const todo = await created.json();
  expect(todo).toMatchObject({ title: '牛乳を買う', done: false });

  const fetched = await request.get(`/api/todos/${todo.id}`);
  await expect(fetched).toBeOK();
  expect(await fetched.json()).toEqual(todo);
});

test('title がないと 422 が返る', async ({ request }) => {
  const res = await request.post('/api/todos', { data: {} });
  expect(res.status()).toBe(422);
  expect(await res.json()).toEqual({ error: 'title is required' });
});

test('削除すると 204 が返り、そのあとは 404 になる', async ({ request }) => {
  const todo = await (await request.post('/api/todos', { data: { title: '消すもの' } })).json();
  const deleted = await request.delete(`/api/todos/${todo.id}`);
  expect(deleted.status()).toBe(204);
  const after = await request.get(`/api/todos/${todo.id}`);
  expect(after.status()).toBe(404);
});

When you pass an object to data, it is sent as a JSON string, and content-type becomes application/json. The response body can be read as an object with json(). toBeOK() is an assertion that checks the status code is in the range 200 to 299 (APIResponseAssertions docs).

Here is the result of the run. The [WebServer] lines show requests received by the test server. auth=あり means the Authorization header was present.

text
$ npx playwright test tests/todos.spec.ts
[WebServer] listening on port 3000
[WebServer] GET /api/todos content-type=- auth=なし

Running 3 tests using 1 worker

[WebServer] POST /api/todos content-type=application/json auth=あり
[WebServer] GET /api/todos/1 content-type=- auth=あり
  ✓  1 tests/todos.spec.ts:3:5 › Todo を作ると 201 が返り、取得できる (66ms)
[WebServer] POST /api/todos content-type=application/json auth=あり
  ✓  2 tests/todos.spec.ts:17:5 › title がないと 422 が返る (15ms)
[WebServer] POST /api/todos content-type=application/json auth=あり
[WebServer] DELETE /api/todos/2 content-type=- auth=あり
[WebServer] GET /api/todos/2 content-type=- auth=あり
  ✓  3 tests/todos.spec.ts:23:5 › 削除すると 204 が返り、そのあとは 404 になる (21ms)

  3 passed (1.0s)

The first GET /api/todos (auth=なし) is a check sent by webServer to the config's url to wait for the server to start (official webServer docs). Every request sent from the tests carried the token. I ran it three times in a row: total times were 1.0 s, 826 ms, and 973 ms, and each test took 12 to 66 ms.

Tests that use only request do not launch a browser. I set the environment variable PLAYWRIGHT_BROWSERS_PATH to a folder that does not exist, so no browser could be found, and these three tests still passed. Running a test that uses page under the same condition failed with browserType.launch: Executable doesn't exist at ….

Even when a 4xx is returned, the test does not fail automatically

request.get() and similar methods do not throw when they receive a 404 or 500. They simply return the response (the failOnStatusCode option in the APIRequestContext docs). This is why the 422 and 404 tests above can be written, but when you expect success, you need to check the status code yourself.

The way you check changes what information you see on failure. I fetched a non-existent /api/todos/999 and made it fail in three ways.

With expect(res.status()).toBe(200), you only see the difference in the number.

text
    Error: expect(received).toBe(expected) // Object.is equality

    Expected: 200
    Received: 404
    …(以下略)

With await expect(res).toBeOK(), the request headers that were sent and the returned body were both shown.

text
    Error: expect(response).toBeOK() failed


    Call log:
    → GET http://localhost:3000/api/todos/999
      user-agent: Playwright/1.63.0 (x64; ubuntu 24.04) node/22.23
      accept: */*
      accept-encoding: gzip,deflate,br
      Authorization: Bearer test-token
    ← 404 Not Found
      content-type: application/json; charset=utf-8
      …(中略)

    Response text:
    {"error":"not found"}
    …(以下略)

When you add failOnStatusCode, as in request.get('/api/todos/999', { failOnStatusCode: true }), anything outside 2xx and 3xx throws immediately. The output was Error: apiRequestContext.get: 404 Not Found, followed by the body and headers in the same way. If the API returns the reason for an error in the body, using toBeOK() or failOnStatusCode lets you read the cause right away.

Warning

The failure output of toBeOK() includes request headers such as Authorization as they are. If you publish CI logs or test reports externally, your real token will be exposed there too.

Login cookies carry over within the same request

For APIs that take form input, use form instead of data. The content-type becomes application/x-www-form-urlencoded.

ts
test('form で送ると urlencoded になり、Cookie は同じ context に残る', async ({ request }) => {
  const login = await request.post('/login', {
    form: { user: 'alice', password: 'secret' },
  });
  await expect(login).toBeOK();

  const me = await request.get('/api/me');
  await expect(me).toBeOK();
  expect(await me.json()).toEqual({ user: 'alice' });
});

In the code in the article, I left out the console.log line that prints the cookie contents. The Set-Cookie in the login response (sid=…; Path=/; HttpOnly) was stored in request and sent with the following /api/me, and the test passed. When I checked the contents with request.storageState(), sid was stored with httpOnly=true. On the other hand, when I called /api/me from the request received in a different test, I got 401. As listed in the built-in fixtures list, request is a separate context for each test, so login state does not carry over between tests.

Be careful when you pass a string to data. When I sent data: 'title=牛乳', content-type became application/octet-stream, and the test API that expected JSON returned 400. The APIRequestContext docs specify for data that an object is sent as JSON and a string is sent as raw bytes as it is.

request.newContext() also inherited the use settings from the config

To check that a request without a token gets 401, I wrote a test that creates a new context with request.newContext() from @playwright/test, passing only baseURL.

ts
import { test, expect, request as playwrightRequest } from '@playwright/test';

// This test failed (201 was returned instead of 401)
test('トークンなしの context では 401 になる', async () => {
  const anonymous = await playwrightRequest.newContext({
    baseURL: 'http://localhost:3000',
  });
  const res = await anonymous.post('/api/todos', { data: { title: 'x' } });
  expect(res.status()).toBe(401);
  await anonymous.dispose();
});

It failed with Expected: 401 / Received: 201. The server log showed auth=あり, meaning the Authorization from the config file was attached. Even when I created the context without passing anything to newContext(), both baseURL and Authorization came from the config file, and the request to /api/todos returned 201. In this test environment (1.63.0), a context created inside a test inherits the use settings from the config file. I did not find any mention of this inheritance in the official API testing docs.

To remove the token, set an empty header explicitly. Both of the following were sent with auth=なし and returned 401.

ts
// Override with empty headers in newContext()
const ctx = await playwrightRequest.newContext({ extraHTTPHeaders: {} });

// Empty the headers of the request fixture only inside a describe block
test.describe('トークンなし', () => {
  test.use({ extraHTTPHeaders: {} });
  test('request フィクスチャ', async ({ request }) => {
    const res = await request.post('/api/todos', { data: { title: 'x' } });
    expect(res.status()).toBe(401);
  });
});

Clean up a context created with newContext() by calling dispose() when you are done with it, because responses stay in memory (the dispose entry in the APIRequestContext docs).

Combining with UI tests

request and page can be received together in the same test. This test creates a Todo through the API, checks that it appears on the screen, then deletes it through the API.

ts
// tests/ui.spec.ts
import { test, expect } from '@playwright/test';

test('API で作った Todo が画面に出る', async ({ request, page }) => {
  const res = await request.post('/api/todos', { data: { title: '画面で確かめる' } });
  await expect(res).toBeOK();
  const todo = await res.json();

  await page.goto('/');
  await expect(page.getByRole('listitem').filter({ hasText: '画面で確かめる' })).toBeVisible();

  await request.delete(`/api/todos/${todo.id}`);
});

This test, which prepared its data through the API, passed in 163 ms.

If you want to log in through the API and then open a screen, the result depends on which request you use. page.request uses the same cookies as the browser context. The request fixture is a separate context with its own cookies (APIRequestContext docs).

ts
test('page.request でログインすると、ページにも Cookie が入る', async ({ page }) => {
  const login = await page.request.post('/login', { form: { user: 'alice', password: 'secret' } });
  await expect(login).toBeOK();
  await page.goto('/api/me');
  await expect(page.locator('body')).toHaveText('{"user":"alice"}');
});

test('request フィクスチャでログインしても、ページには Cookie が入らない', async ({ request, page }) => {
  await request.post('/login', { form: { user: 'alice', password: 'secret' } });
  await page.goto('/api/me');
  await expect(page.locator('body')).toHaveText('{"error":"not logged in"}');
});

I left this out of the code in the article, but when I printed the browser cookies with page.context().cookies() after logging in, the result was [ 'sid' ] with page.request and [] with the request fixture. Both tests passed.

When logging in with page.request, page.request and the screen share the same cookie (sid present), and /api/me opened on the screen returns the user. When logging in with the request fixture, only the request side has sid, the browser context has no cookies, and /api/me opened on the screen returns not logged in. (The labels in this image are in Japanese.)
The difference in the request used for login, and the browser cookies

If you log in before a UI test, use page.request. When you test only the API, the request fixture is better, because its state is reset for each test and earlier tests cannot affect it.

​Posted by 86