Playwright API Authentication

A library clerk checks a membership card before handing over a book. Servers behave the same way. Most APIs refuse requests that arrive without proof of identity. Playwright attaches that proof, usually a token or a username and password, to every request so API tests can reach protected data.

The Authentication Flow

Test                          Server
 |                              |
 |  POST /login (credentials)   |
 |----------------------------->|
 |                              |
 |  200 OK + token              |
 |<-----------------------------|
 |                              |
 |  GET /orders                 |
 |  Authorization: Bearer abc   |
 |----------------------------->|
 |                              |
 |  200 OK + order list         |
 |<-----------------------------|

Getting a Token

The built-in request fixture sends API calls without opening a browser. A login call returns a token that later calls reuse.

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

test('read orders with a token', async ({ request }) => {
  const login = await request.post('/api/login', {
    data: { email: 'asha@example.com', password: process.env.API_PASSWORD },
  });
  const { token } = await login.json();

  const orders = await request.get('/api/orders', {
    headers: { Authorization: `Bearer ${token}` },
  });
  expect(orders.ok()).toBeTruthy();
});

Setting Headers for Every Request

Repeating the header in each call adds noise. The config file attaches it to all requests.

export default defineConfig({
  use: {
    baseURL: 'https://api.example.com',
    extraHTTPHeaders: {
      Authorization: `Bearer ${process.env.API_TOKEN}`,
      Accept: 'application/json',
    },
  },
});

Basic Authentication

Some services accept a username and password directly. The httpCredentials option handles that style.

test.use({
  httpCredentials: { username: 'tester', password: process.env.API_PASSWORD! },
});

Creating a Separate API Client

A custom request context carries its own address and headers. A test can create one client per role.

import { request } from '@playwright/test';

const adminApi = await request.newContext({
  baseURL: 'https://api.example.com',
  extraHTTPHeaders: { Authorization: `Bearer ${process.env.ADMIN_TOKEN}` },
});

const response = await adminApi.get('/users');
await adminApi.dispose();

Testing the Locked Door

A good suite checks failures as well as successes. A request without a token must receive status 401, and a request from a regular user to an admin route must receive 403.

const response = await request.get('/api/admin/users');
expect(response.status()).toBe(401);

Status Codes to Remember

  • 200 means the request succeeded.
  • 401 means the server does not know the caller.
  • 403 means the server knows the caller and refuses access.

A Real-World Scenario

An online pharmacy exposes an orders API. The test team checks three cases: a valid token returns the order list, a missing token returns 401, and a token that belongs to another customer returns 403. These three tests protect customer privacy and take under two seconds.

Keeping Secrets Safe

Never type real tokens into test files. Read them from environment variables or from the secret store of the CI system. Rotate tokens on a schedule, and use accounts created only for testing.

Quick Practice Task

Choose a public practice API that offers a login route. Write a test that logs in, extracts the token, and calls a protected route. Add a second test that omits the token and expects status 401.

Common Questions

Where does the token expire?

Servers define the lifetime. Short tokens last minutes, and long ones last days. Request a fresh token at the start of each run for reliable results.

Can one test use two roles?

Yes. Create one request context per role and call the same route with each. Compare the two responses to confirm the permission rules.

Why does a header go missing?

A request context created by hand ignores the config headers. Pass extraHTTPHeaders into request.newContext directly.

Key Takeaways

  • The request fixture sends API calls without a browser.
  • Tokens travel in the Authorization header.
  • Config-level headers keep tests short.
  • Negative tests prove that locked doors stay locked.