Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS MATH

Playwright API Testing


Share

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 response
  • expect(response).toBeOK() checks that the status is in the 200 to 299 range
  • response.json() reads the body as JSON
  • toEqual() compares the whole object, field by field
  • params adds a query string, so this request goes to api/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();
});
  • request is imported from @playwright/test here, not taken from the fixture
  • extraHTTPHeaders is sent with every request, a common place for an API token
  • api.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.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.