Playwright API Testing
Playwright API Testing
API testing means sending HTTP requests straight to a server, and checking the responses, without opening a page.
Playwright can do this with the same test runner, the same expect and the same reports as your browser tests.
This chapter tests the practice API: api/products.php.
It returns a list of 5 products, one product by id, and accepts new products with POST.
The request Fixture
Ask for the request fixture to get an API client: an object that sends HTTP requests for you.
It uses the baseURL from your config, so relative URLs work:
Example
tests/products.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('get all products', async ({ request }) => {
const response = await request.get('api/products.php');
await expect(response).toBeOK();
const data = await response.json();
expect(data.products).toHaveLength(5);
expect(data.products[0]).toEqual({ id: 1, name: 'Laptop Stand', price: 29.99 });
});
test('get one product', async ({ request }) => {
const response = await request.get('api/products.php', { params: { id: 2 } });
await expect(response).toBeOK();
expect(await response.json()).toEqual({ id: 2, name: 'USB-C Cable', price: 9.5 });
});
Example Explained
request.get()sends a GET request and returns the responseexpect(response).toBeOK()checks that the status is in the 200 to 299 rangeresponse.json()reads the body as JSONtoEqual()compares the whole object, field by fieldparamsadds a query string, so this request goes toapi/products.php?id=2
No browser is started for these tests, so they are very fast.
Send Data with POST
Use request.post() with a data option.
When data is an object, Playwright sends it as JSON and sets the Content-Type header for you.
Add this test to tests/products.spec.js:
Example
test('create a product', async ({ request }) => {
const response = await request.post('api/products.php', {
data: { name: 'Headphones', price: 59 },
});
expect(response.status()).toBe(201);
expect(await response.json()).toEqual({ id: 6, name: 'Headphones', price: 59 });
});
The API answers with status 201 (Created) and the new product, with id 6.
There are also request.put(), request.patch(), request.delete() and request.head().
Run the file:
Example
npx playwright test tests/products.spec.js
Output:
Running 3 tests using 3 workers
[1/3] [chromium] › tests/products.spec.js:4:1 › get all products
[2/3] [chromium] › tests/products.spec.js:19:1 › create a product
[3/3] [chromium] › tests/products.spec.js:13:1 › get one product
3 passed (749ms)
Test Error Cases
A good API test also checks what happens when something is wrong.
Error responses have a status code from 400 to 599 (for example 404 Not Found).
Playwright does not throw an error for them, so you can check them like any other response:
Example
tests/errors.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('missing product returns 404', async ({ request }) => {
const response = await request.get('api/products.php?id=99');
expect(response.status()).toBe(404);
expect(await response.json()).toEqual({ error: 'Product not found' });
});
test('bad body returns 400', async ({ request }) => {
const response = await request.post('api/products.php', {
data: { name: 'No price' },
});
expect(response.status()).toBe(400);
await expect(response).not.toBeOK();
});
When toBeOK() fails, the error shows the request, the status and the response body.
Here is a test that expects product 99 to exist:
Example
tests/fail.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('product 99 exists', async ({ request }) => {
const response = await request.get('api/products.php?id=99');
await expect(response).toBeOK();
});
The output (some header lines are cut):
Output:
Running 1 test using 1 worker
[1/1] [chromium] › tests/fail.spec.js:4:1 › product 99 exists
1) [chromium] › tests/fail.spec.js:4:1 › product 99 exists ───────────────────────────────────────
Error: expect(response).toBeOK() failed
Call log:
→ GET https://www.w3schools.com/playwright/practice/api/products.php?id=99
accept: */*
← 404 Not Found
content-type: application/json; charset=utf-8
Response text:
{"error":"Product not found"}
4 | test('product 99 exists', async ({ request }) => {
5 | const response = await request.get('api/products.php?id=99');
> 6 | await expect(response).toBeOK();
| ^
7 | });
1 failed
[chromium] › tests/fail.spec.js:4:1 › product 99 exists ────────────────────────────────────────
Your Own Request Context
The request fixture is enough for most tests.
A request context is an API client with its own settings.
If you need different settings, for example another server or extra headers, create your own context with request.newContext():
Example
tests/context.spec.js
// @ts-check
import { test, expect, request } from '@playwright/test';
test('own request context', async () => {
const api = await request.newContext({
baseURL: 'https://www.w3schools.com/playwright/practice/',
extraHTTPHeaders: {
'Accept': 'application/json',
},
});
const response = await api.get('api/products.php?id=3');
await expect(response).toBeOK();
expect((await response.json()).name).toBe('Wireless Mouse');
await api.dispose();
});
requestis imported from@playwright/testhere, not taken from the fixtureextraHTTPHeadersis sent with every request, a common place for an API tokenapi.dispose()closes the context and frees its memory when you are done
You can also set extraHTTPHeaders in the use section of the config, and the request fixture will send them.
Combine API and UI Tests
API calls are fast, so they are a good way to get data or to prepare a test.
This test asks the API which products exist, and then checks that the shop page shows every one of them:
Example
tests/combined.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('shop shows every product from the API', async ({ page, request }) => {
const response = await request.get('api/products.php');
const { products } = await response.json();
await page.goto('shop.html');
await expect(page.getByTestId('product')).toHaveCount(products.length);
for (const product of products) {
await expect(page.getByRole('heading', { name: product.name })).toBeVisible();
}
});
In a real app you often do it in the other order: create data with a POST request, then open the page and check that the new data appears.
That is much faster than clicking through a form in every test.
Note: page.request is an API client that shares cookies with the page.
If the page is logged in, requests sent with page.request are logged in too.
Cookies that the API sets are also used by the page.