
Table of Contents
Introduction
Playwright API testing lets a test suite verify a backend directly, without opening a browser at all. That distinction matters more than it sounds like. UI tests are slow by nature, since every action waits on rendering, network requests, and animations. Playwright API testing skips all of that, sending HTTP requests straight to the server and checking the response, which makes it dramatically faster and a natural fit for verifying backend behavior on its own.
This tutorial covers Playwright API testing from the first GET request through authentication, chaining requests together, combining API calls with UI tests, and validating response schemas. It closes with a genuinely different AI angle than the rest of this series: generating API tests directly from an OpenAPI or Swagger specification, rather than from a page’s HTML.
Before diving into the full article, explore these essential beginner-f articles first.
Playwright Automation Testing with AI: Complete JavaScript & TypeScript Framework From Scratch
Playwright CI/CD setup with GitHub Actions and AI Complete Automation Testing Pipeline Guide
Playwright Locators Tutorial with Examples: Use AI to Build Better Test Automation
Playwright Page Object Model Tutorial: Build a Scalable Test Framework with AI
Playwright Assertions Tutorial with Examples: Validate Your Tests with AI
Why Test APIs with Playwright
Most teams already run UI tests in Playwright. Adding Playwright API testing to the same project, rather than reaching for a separate tool, keeps everything in one framework, one test runner, and one CI pipeline.
Speed. API requests skip rendering entirely, so a full suite of Playwright API testing checks often runs in a fraction of the time an equivalent UI suite takes.
Reliability. Without a browser in the loop, API tests avoid most of the flakiness caused by animations, slow-loading assets, or timing-sensitive UI elements.
Test data setup. Playwright API testing is commonly used to create accounts, records, or other state directly through the backend before a UI test even starts, instead of clicking through a slow multi-step UI flow just to reach a starting point.
Backend confidence independent of the frontend. A broken API endpoint can be caught immediately through Playwright API testing, even if no UI change has happened yet to expose the problem visually.
Setting Up API Testing in Playwright
Playwright API testing does not need a separate library or client. It uses the built-in request fixture, available directly inside any test.
javascript
const { test, expect } = require('@playwright/test');
test('API is reachable', async ({ request }) => {
const response = await request.get('/api/health');
expect(response.ok()).toBeTruthy();
});
The request fixture behaves like a lightweight HTTP client scoped to the test. A baseURL can be set once in playwright.config.js, so every Playwright API testing call in the project can use a relative path instead of repeating the full domain in every test.
javascript
module.exports = {
use: {
baseURL: 'https://api.example.com',
},
};
What Do GET, POST, PUT, PATCH, and DELETE Mean?
Before writing any test code, it helps to be clear on what each HTTP method actually represents. These five verbs cover almost everything a REST API does, and each one maps to a specific kind of action against a resource.
| Method | What It Does | Typical Success Status |
|---|---|---|
| GET | Retrieves existing data without changing anything | 200 |
| POST | Creates a new resource | 201 |
| PUT | Replaces an entire existing resource | 200 |
| PATCH | Updates part of an existing resource | 200 |
| DELETE | Removes an existing resource | 204 |
GET is a read-only request. Calling it repeatedly should never change any data on the server, which makes it the safest method to test freely without side effects.
POST creates something new. Calling it twice with the same data usually creates two separate resources, not one, which is an important distinction when writing tests that run repeatedly.
PUT replaces a resource in full. Sending a PUT request with only one field typically overwrites every other field with empty or default values, since the request is expected to represent the complete resource, not a partial update.
PATCH updates only the fields included in the request, leaving everything else on the resource untouched. This is the method to reach for when only a small part of a resource needs to change.
DELETE removes a resource entirely. It typically returns an empty response body with a 204 status rather than the deleted object itself, since there is nothing left to return.
With that distinction clear, the examples below show exactly how each of these looks in code.
GET and POST Requests Explained
GET requests retrieve data, and are usually the simplest starting point for Playwright API testing.
javascript
test('fetch a list of users', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.status()).toBe(200);
const body = await response.json();
expect(Array.isArray(body)).toBeTruthy();
});
POST requests create new data, and are just as central to Playwright API testing since most real applications depend on writes as much as reads.
javascript
test('create a new user', async ({ request }) => {
const response = await request.post('/api/users', {
data: { name: 'Jordan Lee', email: 'jordan.lee@example.com' },
});
expect(response.status()).toBe(201);
const body = await response.json();
expect(body.name).toBe('Jordan Lee');
});
PUT, PATCH, and DELETE Requests
Full Playwright API testing coverage also means testing updates and deletions, not just reads and creates.
javascript
test('update an existing user', async ({ request }) => {
const response = await request.put('/api/users/42', {
data: { name: 'Jordan Lee Updated' },
});
expect(response.status()).toBe(200);
});
test('partially update a user', async ({ request }) => {
const response = await request.patch('/api/users/42', {
data: { email: 'new.email@example.com' },
});
expect(response.status()).toBe(200);
});
test('delete a user', async ({ request }) => {
const response = await request.delete('/api/users/42');
expect(response.status()).toBe(204);
});
PUT typically replaces a full resource, PATCH updates part of one, and DELETE removes it entirely. Covering all three in a Playwright API testing suite closes gaps that GET and POST alone tend to leave open.
Authentication and Headers
Most real APIs require authentication, and Playwright API testing handles this through custom headers passed directly with each request.
javascript
test('access a protected endpoint', async ({ request }) => {
const response = await request.get('/api/profile', {
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
});
expect(response.status()).toBe(200);
});
Storing the token in an environment variable, rather than hardcoding it in the test file, keeps credentials out of version control, which matters just as much in Playwright API testing as it does anywhere else in a codebase. For flows that log in once and reuse the resulting session, Playwright’s storageState() can capture authenticated state and share it across multiple tests without repeating the login request every time.
Validating Responses
A response check in Playwright API testing usually covers three layers: the status code, the headers, and the body.
javascript
test('validate a full response', async ({ request }) => {
const response = await request.get('/api/users/42');
expect(response.status()).toBe(200);
expect(response.headers()['content-type']).toContain('application/json');
const body = await response.json();
expect(body).toHaveProperty('id', 42);
expect(body).toHaveProperty('email');
});
Checking the status code alone is a common shortcut, but it misses a large category of real bugs, an endpoint returning 200 with the wrong data, a missing field, or an incorrect content type. Thorough Playwright API testing checks all three layers, not just one.
Chaining API Requests
Real workflows rarely involve a single isolated request. A common Playwright API testing pattern creates a resource, then immediately verifies it through a follow-up request.
javascript
test('created user appears in the user list', async ({ request }) => {
const createResponse = await request.post('/api/users', {
data: { name: 'Alex Rivera', email: 'alex.rivera@example.com' },
});
const created = await createResponse.json();
const listResponse = await request.get('/api/users');
const users = await listResponse.json();
expect(users.some(user => user.id === created.id)).toBeTruthy();
});
This chained pattern verifies real end-to-end backend behavior, not just that a single endpoint responds correctly in isolation, which is often where subtle backend bugs actually hide.
Combining API and UI Tests
One of the most practical uses of Playwright API testing is speeding up UI tests, not replacing them. Instead of clicking through a slow multi-step signup flow just to reach a page that needs testing, an API call can create that state directly.
javascript
test('logged-in user sees their dashboard', async ({ request, page }) => {
await request.post('/api/users', {
data: { name: 'Sam Patel', email: 'sam.patel@example.com', password: 'testpass123' },
});
await page.goto('/login');
await page.getByLabel('Email address').fill('sam.patel@example.com');
await page.getByLabel('Password').fill('testpass123');
await page.getByRole('button', { name: 'Login' }).click();
await expect(page).toHaveURL('/dashboard');
});
The account is created through Playwright API testing in milliseconds, and the UI test only covers what it actually needs to, the login and dashboard flow, rather than repeating a signup process that has nothing to do with what the test is checking.
Using AI to Generate Tests From an API Spec
This is where Playwright API testing pairs with AI in a genuinely different way than locators or page objects did earlier in this series. Most real APIs already have a specification, an OpenAPI or Swagger document, describing every endpoint, its parameters, and its expected responses.
Generating test cases directly from an OpenAPI spec. Pasting or referencing a project’s OpenAPI document and asking an AI assistant to draft Playwright API testing cases produces a strong first pass covering the documented endpoints, request shapes, and expected status codes, without a person manually transcribing each one from the spec by hand.
Validating responses against the spec automatically. An AI assistant can compare an actual API response against the schema defined in the spec and flag mismatches, a field that is missing, an unexpected type, or a status code the documentation never mentioned, which is tedious to check manually across dozens of endpoints.
Filling in edge cases a spec implies but does not spell out. A spec might define a field as required without listing what should happen if it is missing. AI assistants can suggest these implied edge cases, invalid input, missing fields, unexpected types, based on the schema definition itself.
As with every AI-assisted step covered elsewhere in this series, generated Playwright API testing cases still need a human review pass, confirming they test meaningful behavior and not just whatever happened to match the spec’s example values.
Testing Error and Failure Responses
Most Playwright API testing tutorials focus almost entirely on success cases, but real APIs spend a meaningful amount of their behavior handling things going wrong. A thorough suite checks those paths deliberately, rather than assuming they work.
javascript
test('rejects a request with invalid input', async ({ request }) => {
const response = await request.post('/api/users', {
data: { name: '' },
});
expect(response.status()).toBe(400);
const body = await response.json();
expect(body.error).toContain('required');
});
test('rejects an unauthenticated request', async ({ request }) => {
const response = await request.get('/api/profile');
expect(response.status()).toBe(401);
});
test('returns 404 for a nonexistent resource', async ({ request }) => {
const response = await request.get('/api/users/999999');
expect(response.status()).toBe(404);
});
Each of these confirms the API fails in a predictable, well-defined way rather than an unhandled server error. A missing field, a missing token, and a nonexistent ID are three of the most common real-world failure paths, and skipping them in a test suite means the first time they are actually exercised is in production.
Common API Testing Mistakes
Checking only the status code. A 200 response can still contain the wrong data, a missing field, or a malformed body, none of which a status check alone catches.
Hardcoding tokens and credentials directly in test files. This is a security risk and makes Playwright API testing far harder to run safely across different environments and CI providers.
Not cleaning up created data. Tests that create resources without deleting them afterward slowly pollute a shared test environment, causing unrelated failures later.
Testing only the happy path. Real APIs fail in specific, predictable ways, invalid input, missing auth, rate limits, and skipping those cases leaves significant gaps in test coverage.
Treating API and UI tests as unrelated. Missing the opportunity to use API calls for fast test data setup is one of the more common ways teams end up with UI suites that run far slower than they need to.
Playwright API Testing Best Practices Checklist
- Validate status code, headers, and body together, not status alone
- Store tokens and credentials in environment variables, never hardcoded
- Use API calls to set up test data instead of repeating slow UI flows
- Chain requests to verify real backend behavior, not isolated endpoints
- Clean up created test data after each run where possible
- Cover failure cases, not just successful responses
- Review AI-generated tests against the actual spec before merging them
Frequently Asked Questions
Does Playwright API testing require a separate library?
No. Playwright includes a built-in request fixture for sending HTTP requests, so no additional client or library is needed to test a REST API.
Can Playwright API testing and UI testing run in the same test file?
Yes. A single test can use both the request and page fixtures together, which is commonly used to set up data quickly through the API before testing the actual UI flow.
How do I handle authentication in Playwright API testing?
Authentication tokens are typically passed as headers with each request, often stored in environment variables, or captured once through storageState() and reused across multiple tests.
Is Playwright API testing faster than UI testing?
Generally yes, since API requests skip browser rendering entirely, which makes this approach a common choice for fast backend checks and test data setup.
Can AI generate accurate Playwright API testing cases from an OpenAPI spec?
AI-generated tests from a spec are usually a strong starting point covering documented endpoints and expected responses, but they still need a human review pass to confirm the assertions test meaningful, real-world behavior.
Should every project use both API and UI tests?
Most production applications benefit from both. The API layer verifies backend correctness quickly, while UI tests confirm the actual user-facing experience still works as expected.
Conclusion
Playwright API testing fills a gap that UI tests alone cannot cover efficiently, fast, reliable checks directly against a backend, without a browser slowing every request down. Covering GET, POST, PUT, PATCH, and DELETE, validating full responses rather than status codes alone, and chaining requests to verify real workflows covers the core of what a solid API testing layer needs.
The AI angle here differs from the rest of this series in a meaningful way. Instead of generating a single locator or page object from HTML, AI assistants can draft an entire suite of Playwright API testing cases directly from an existing OpenAPI or Swagger specification, and help validate real responses against that same spec automatically. Reviewed carefully, this turns documentation that already exists into working test coverage far faster than writing it by hand.
For official reference material, Playwright’s own API testing documentation covers the full APIRequestContext in depth, and the OpenAPI Specification is the standard reference for how API specs are structured, useful context for anyone generating tests from one.
For official reference material, Playwright’s own Page Object Model documentation covers the pattern in more depth directly from the source.
Explore more articles from AI blogs AI Learning Hub, AI tools pagesubscribe to AI Pathway Lab AI for Testers
- Prompt Engineering Guide – The Skill That Makes You 10x Faster
- What Are AI Agents? Complete Beginner Guide 2026
- 12 Proven Ways to Make Money With AI That Actually Work
- Claude AI to Earn Money Guide: 4 Proven Ways That Actually Work
- Free AI Courses with Certificate in 2026
- AI Test Case Generation Guide for QA Engineers Using ChatGPT and Claude
3 Proven Ways AI Accelerates Software QA Workflows
Automation with AI, Write Test Scripts 10x Faster in 2026
AI Workflows for QA Automation, How to Integrate
Explor AI Automation & Workflows