Can Playwright be used for API testing?
Yes. Playwright includes an HTTP client, APIRequestContext, and the test runner exposes it as the request fixture. It sends GET, POST, PUT, PATCH and DELETE calls directly, without opening a browser, and you assert on the responses with the same expect you use for UI tests. It will not replace a dedicated API tool for every job, but for most web projects it removes the need for a second test framework.
A first API test
Say your app has an enquiry endpoint: POST /api/enquiries creates an enquiry and GET /api/enquiries/:id returns it. The paths are examples; the code was run against a small local server shaped like this.
// tests/enquiries.api.spec.ts
import { test, expect } from '@playwright/test';
test('create and read an enquiry', async ({ request }) => {
const created = await request.post('/api/enquiries', {
data: { name: 'Riya', course: 'Software Testing' }, // sent as JSON
});
expect(created.status()).toBe(201);
const enquiry = await created.json();
const fetched = await request.get(`/api/enquiries/${enquiry.id}`);
await expect(fetched).toBeOK(); // any 2xx status
expect(await fetched.json()).toMatchObject({ name: 'Riya', course: 'Software Testing' });
});
test('rejects a bad token', async ({ request }) => {
const res = await request.post('/api/enquiries', {
data: {},
headers: { Authorization: 'Bearer wrong-token' }, // overrides the config header
});
expect(res.status()).toBe(401);
});
When the server returned 201 for the first call, created.json() gave back the new record with its id. In the second test, the per-request header replaced the default one and the server answered 401. If an assertion like toBeOK() fails, the error message includes the response details, which makes API failures quick to read.
Config: base URL and default headers
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://staging-api.example.com',
extraHTTPHeaders: {
Accept: 'application/json',
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
},
});
Keep the token in an environment variable or your CI's secret store, never in the repository. To run only the API tests, give them their own project with a testMatch pattern such as /.*\.api\.spec\.ts/; see the Playwright config file.
Where Playwright API testing really helps: mixing it with UI
- Fast setup. Create a user, a course or an order through the API, then test only the screen you care about. That keeps UI tests short and stable.
- Verify the UI's side effects. Submit a form in the browser, then call the API to confirm the record was saved correctly.
- Shared login.
page.request(orcontext.request) uses the same cookies as the browser, so API calls made with it are authenticated as the logged-in user.
test('enquiry form saves the record', async ({ page }) => {
await page.goto('/contact');
await page.getByLabel('Name').fill('Arjun');
await page.getByRole('button', { name: 'Submit' }).click();
const res = await page.request.get('/api/enquiries?name=Arjun'); // browser's cookies
await expect(res).toBeOK();
});
Limits to know
- There is no built-in JSON schema validation. Add a library such as Ajv or Zod if you need contract checks.
- It is not a load-testing tool. Use k6, JMeter or Gatling for volume.
- Exploratory API work (saving collections, sharing requests with developers) is easier in a GUI tool. A balanced comparison is in Playwright vs Postman for beginners.
- Outside a test, create a client with
request.newContext()from@playwright/testand calldispose()when you are done.
Related: fixtures in Playwright (the request fixture is one of them) and HAR files in Playwright.
Want to master Playwright hands-on?
Join Uncodemy's Playwright Automation Testing Course in Noida — Dedicated Placement Support.
Explore the Course →