Introduction: Why Playwright API Testing Matters in 2026
API testing is an important skill for modern QA Automation Engineers and SDETs.
A UI-only automation strategy can be slow because every test must load pages, execute JavaScript, interact with controls, and wait for the browser. API testing can validate backend behavior directly and can also create application state much faster.
This is why Playwright API testing interview questions increasingly appear in automation and SDET interviews.
Playwright provides APIRequestContext for sending HTTP requests directly from Node.js. It can be used to test APIs independently, prepare server-side state before UI tests, and validate backend state after browser actions.
An experienced interviewer may ask:
- How do you perform GET, POST, PUT, PATCH, and DELETE testing?
- How do you validate response status codes?
- How do you handle authentication?
- How do you chain API requests?
- How do you create test data through APIs?
- How do you combine API and UI testing?
- How do you isolate API data during parallel execution?
- How do you mock an external API?
- How do you debug an intermittent 500 response?
- How would you design a reusable Playwright API testing framework?
This guide covers those topics from beginner to senior SDET level.
What Is API Testing in Playwright?
1. What is API testing in Playwright?
Interview-Ready Answer: Playwright API testing allows us to send HTTP requests directly to application APIs using APIRequestContext and validate responses without relying on browser UI interactions.
Explanation: Playwright can send HTTP requests using methods such as:
GET
POST
PUT
PATCH
DELETE
HEAD
A typical flow is:
Test
↓
APIRequestContext
↓
HTTP Request
↓
Application API
↓
HTTP Response
↓
Status + Headers + JSON + Business Validation
Playwright’s API testing documentation specifically describes three common uses: testing server APIs, preparing server state before UI tests, and validating server-side postconditions after browser actions.
TypeScript Code Example:
import { test, expect } from ‘@playwright/test’;
test(‘verify users API’, async ({ request }) => {
const response = await request.get(‘/api/users’);
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});
Interview Tip: Explain that API testing is not only another test layer. It can also make UI automation faster by handling setup and cleanup through services.
Playwright API Testing vs UI Testing
2. What is the difference between API and UI testing?
Interview-Ready Answer: API testing validates backend services directly, while UI testing validates application behavior through the browser. API tests are generally faster and more focused, while UI tests validate the complete user-facing workflow.
| Area | API Testing | UI Testing |
| Browser required | No | Yes |
| Execution speed | Usually faster | Usually slower |
| UI validation | No | Yes |
| Backend validation | Yes | Indirect |
| Test-data setup | Fast | Often slower |
| Visual behavior | No | Yes |
| Authentication | Tokens/headers | Browser session |
| Best use | Service behavior | End-to-end workflows |
Architecture Example:
→ Create customer
→ Validate customer
→ Delete customer
UI Test
→ Login
→ Search customer
→ Open customer
→ Validate UI
Interview Tip: A strong SDET explains why both layers are necessary instead of replacing all UI tests with APIs.
Basic Playwright API Testing Interview Questions
3. What is APIRequestContext?
Interview-Ready Answer: APIRequestContext is Playwright’s API client abstraction for sending HTTP requests and receiving API responses.
It supports methods such as:
request.get()
request.post()
request.put()
request.patch()
request.delete()
request.fetch()
Playwright also provides an isolated request test fixture.
Example:
test(‘get product’, async ({ request }) => {
const response =
await request.get(‘/api/products/101’);
expect(response.status()).toBe(200);
});
Interview Tip: Mention the difference between an API context associated with a BrowserContext and an independently created APIRequestContext.
4. What is the Playwright request fixture?
Interview-Ready Answer: The request fixture provides an isolated APIRequestContext to a test.
test(‘API test’, async ({ request }) => {
const response =
await request.get(‘/api/products’);
expect(response.ok()).toBeTruthy();
});
Playwright documents the request fixture as an isolated APIRequestContext for each test.
Interview Tip: This is often preferable for straightforward API tests because Playwright handles fixture lifecycle for you.
GET, POST, PUT, PATCH, and DELETE Questions
5. How do you test a GET API?
Interview-Ready Answer: Send a GET request and validate the status, headers, response body, and business fields.
test(‘GET product’, async ({ request }) => {
const response =
await request.get(‘/api/products/101’);
expect(response.status()).toBe(200);
const body = await response.json();
expect(body.id).toBe(101);
expect(body.name).toBeTruthy();
});
Interview Tip: Don’t validate only 200. Validate meaningful response content too.
6. How do you test a POST API?
Interview-Ready Answer: Send the required request body, validate the creation status, and verify the returned resource.
test(‘POST customer’, async ({ request }) => {
const response =
await request.post(‘/api/customers’, {
data: {
name: ‘Automation User’,
email: ‘qa@example.com’
}
});
expect(response.status()).toBe(201);
const body = await response.json();
expect(body.name)
.toBe(‘Automation User’);
});
Playwright serializes object data as JSON for request methods such as POST and sets the appropriate content type when applicable.
Interview Tip: Mention negative cases such as duplicate users, missing mandatory fields, invalid formats, and unauthorized requests.
7. How do you test PUT and PATCH?
Interview-Ready Answer: PUT typically validates complete resource replacement, while PATCH validates partial updates according to the API contract.
test(‘update customer’, async ({ request }) => {
const response =
await request.put(‘/api/customers/101’, {
data: {
name: ‘Updated User’,
email: ‘updated@example.com’
}
});
expect(response.status()).toBe(200);
});
PATCH:
test(‘partially update customer’, async ({
request
}) => {
const response =
await request.patch(‘/api/customers/101’, {
data: {
name: ‘New Name’
}
});
expect(response.ok()).toBeTruthy();
});
Interview Tip: Explain the expected semantics from the API contract rather than assuming every API implements PUT and PATCH identically.
8. How do you test DELETE?
test(‘delete customer’, async ({ request }) => {
const response =
await request.delete(‘/api/customers/101’);
expect([200, 202, 204])
.toContain(response.status());
});
Then validate:
const verify =
await request.get(‘/api/customers/101’);
expect(verify.status()).toBe(404);
Interview Tip: Don’t assume 204 is always correct. The expected status should come from the API specification.
Headers, Query Parameters, Path Parameters, and Request Bodies
9. How do you send headers?
test(‘authorized API request’, async ({
request
}) => {
const response =
await request.get(‘/api/orders’, {
headers: {
Authorization:
`Bearer ${process.env.API_TOKEN}`,
Accept: ‘application/json’
}
});
expect(response.status()).toBe(200);
});
Headers can also be configured at API-context level when they apply to multiple requests. Playwright supports extraHTTPHeaders when creating a request context.
Interview Tip: Avoid duplicating authentication headers across hundreds of tests. Centralize common API configuration.
10. How do you pass query parameters?
const response =
await request.get(‘/api/products’, {
params: {
category: ‘laptops’,
page: 2,
limit: 20
}
});
Playwright supports query parameters through the params option.
Interview Tip: Test combinations of valid, missing, empty, invalid, and boundary-value parameters.
11. What is the difference between path and query parameters?
Interview-Ready Answer:
Path parameter:
/api/users/123
Query parameter:
/api/users?page=2&limit=10
TypeScript:
await request.get(
`/api/users/${userId}`
);
await request.get(‘/api/users’, {
params: {
page: 2,
limit: 10
}
});
Interview Tip: Be able to identify parameters directly from an API contract.
Status Codes and Response Validation
12. How do you validate status codes?
const response =
await request.post(‘/api/orders’, {
data: order
});
expect(response.status()).toBe(201);
Or:
expect(response.ok()).toBeTruthy();
Important: ok() tells you whether the response is considered successful. For business-specific tests, an exact status assertion is often better.
Interview Tip: Know common codes:
| Status | Meaning |
| 200 | Successful request |
| 201 | Resource created |
| 202 | Accepted |
| 204 | Successful request with no content |
| 400 | Bad request |
| 401 | Unauthenticated |
| 403 | Forbidden |
| 404 | Not found |
| 409 | Conflict |
| 422 | Validation failure |
| 429 | Too many requests |
| 500 | Server error |
JSON Response and Schema Validation
13. How do you validate JSON responses?
const body = await response.json();
expect(body.id).toBeTruthy();
expect(body.email).toMatch(
/^[^@\s]+@[^@\s]+\.[^@\s]+$/
);
expect(body.active).toBe(true);
For arrays:
expect(Array.isArray(body.items))
.toBe(true);
expect(body.items.length)
.toBeGreaterThan(0);
Interview Tip: Validate business-critical fields rather than asserting the entire response blindly.
14. How would you validate an API schema?
Interview-Ready Answer: I would use a schema validation library such as Zod, Ajv, or another JSON Schema-compatible solution when structural validation needs to be centralized.
Example with Zod:
import { z } from ‘zod’;
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
active: z.boolean()
});
const body = await response.json();
UserSchema.parse(body);
Interview Tip: Distinguish schema validation from business validation. A response can match the schema and still contain incorrect business data.
Authentication, Tokens, JWT, API Keys, and OAuth
15. How do you authenticate API requests?
Interview-Ready Answer: Authentication depends on the API. Common approaches include bearer tokens, API keys, basic authentication, OAuth access tokens, and cookies.
Bearer token:
const response =
await request.get(‘/api/profile’, {
headers: {
Authorization:
`Bearer ${process.env.ACCESS_TOKEN}`
}
});
API key:
const response =
await request.get(‘/api/data’, {
headers: {
‘x-api-key’: process.env.API_KEY!
}
});
Interview Tip: Never hard-code production credentials or commit secrets to Git.
16. How would you test an expired JWT?
Interview-Ready Answer: I would use a deliberately expired or invalid token and verify that the API returns the expected authentication failure, typically 401, according to the API contract.
test(‘expired token is rejected’, async ({
request
}) => {
const response =
await request.get(‘/api/profile’, {
headers: {
Authorization:
‘Bearer expired-token’
}
});
expect(response.status()).toBe(401);
});
Interview Tip: Also verify the error body and confirm that sensitive information is not exposed.
API Request Chaining and Test-Data Setup
17. How do you chain API requests?
Interview-Ready Answer: Capture data from one response and use it in the next request.
test(‘create and update user’, async ({
request
}) => {
const create =
await request.post(‘/api/users’, {
data: {
name: ‘Test User’,
email: `qa-${Date.now()}@example.com`
}
});
expect(create.status()).toBe(201);
const created = await create.json();
const update =
await request.patch(
`/api/users/${created.id}`,
{
data: {
name: ‘Updated User’
}
}
);
expect(update.status()).toBe(200);
});
Interview Tip: Always clean up created resources when the environment requires it.
18. Why use API calls to prepare UI test data?
Interview-Ready Answer: API setup is usually faster and less brittle than creating data through multiple UI steps.
Example:
API
↓
Create Customer
↓
Create Order
↓
Browser
↓
Open Order
↓
Validate UI
Playwright explicitly supports using API requests to prepare server-side state before browser tests and validate postconditions afterward.
Interview Tip: This is a strong SDET answer because it demonstrates layered testing rather than UI-only automation.
Combining API Testing With UI Automation
19. How do you validate that a UI action created the correct backend record?
test(‘UI order matches API state’, async ({
page,
request
}) => {
await page.goto(‘/checkout’);
await page.getByRole(‘button’, {
name: ‘Place Order’
}).click();
const orderId =
await page.getByTestId(‘order-id’)
.textContent();
const response =
await request.get(
`/api/orders/${orderId}`
);
expect(response.status()).toBe(200);
const order = await response.json();
expect(order.status).toBe(‘CONFIRMED’);
});
Interview-Ready Answer:
“The UI test validates the user experience, while the API assertion validates the backend postcondition.”
Interview Tip: This is a common real-world SDET pattern.
Fixtures and Reusable API Clients
20. How would you create a reusable API client?
Interview-Ready Answer: I would wrap repeated endpoints in a typed service class rather than duplicating raw request calls throughout tests.
import {
APIRequestContext,
expect
} from ‘@playwright/test’;
export class UserApi {
constructor(
private readonly request: APIRequestContext
) {}
async createUser(user: {
name: string;
email: string;
}) {
return this.request.post(‘/api/users’, {
data: user
});
}
async getUser(id: number) {
return this.request.get(
`/api/users/${id}`
);
}
async deleteUser(id: number) {
return this.request.delete(
`/api/users/${id}`
);
}
}
Interview Tip: Keep API clients responsible for API communication, not business test assertions.
21. How would you inject an API client through a fixture?
import {
test as base
} from ‘@playwright/test’;
type Fixtures = {
userApi: UserApi;
};
export const test =
base.extend<Fixtures>({
userApi: async ({ request }, use) => {
await use(new UserApi(request));
}
});
Then:
test(‘create user’, async ({
userApi
}) => {
const response =
await userApi.createUser({
name: ‘SDET’,
email: ‘sdet@example.com’
});
expect(response.ok()).toBeTruthy();
});
Interview Tip: Fixtures provide a clean dependency-injection mechanism for framework components.
API Mocking and Network Interception
22. How do you mock an API in Playwright?
Interview-Ready Answer: For browser-based tests, I can intercept network requests with page.route() and fulfill them with controlled data.
await page.route(
‘**/api/products’,
async route => {
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify({
products: [
{
id: 1,
name: ‘Mock Product’
}
]
})
});
}
);
Playwright supports mocking, modifying, and replaying network traffic, including HAR-based mocking.
Interview Tip: Explain that APIRequestContext is for making API calls, while page.route() is especially useful for controlling requests made by the browser application.
23. When would you modify rather than completely mock an API response?
Suppose the real API response is valuable, but you need to add a special condition.
await page.route(
‘**/api/products’,
async route => {
const response = await route.fetch();
const json = await response.json();
json.products.push({
id: 999,
name: ‘Special Test Product’
});
await route.fulfill({
response,
json
});
}
);
Playwright supports fetching the original response and fulfilling the route with modified data.
Interview Tip: This provides a useful middle ground between a completely fake service and an uncontrolled real dependency.
Parallel API Testing and Test-Data Isolation
24. What problems occur when API tests run in parallel?
Common problems include:
- Duplicate email addresses
- Same customer ID
- Shared order
- Concurrent updates
- Cleanup collisions
- Rate limiting
- Database locks
Use unique data:
import crypto from ‘node:crypto’;
function uniqueEmail() {
return `qa-${crypto.randomUUID()}@example.com`;
}
Then:
const response =
await request.post(‘/api/users’, {
data: {
name: ‘Parallel User’,
email: uniqueEmail()
}
});
Interview-Ready Answer:
“I design API tests to be independent before enabling aggressive parallelism.”
Interview Tip: Data isolation is often more important than worker count.
API Debugging, Logging, and Reporting
25. How do you debug an API test that fails intermittently?
Use a structured process:
Failure
↓
Status Code
↓
Response Headers
↓
Response Body
↓
Request Payload
↓
Authentication
↓
Environment
↓
Server Logs
↓
Dependency Health
Example:
const response =
await request.get(‘/api/orders’);
console.log(‘Status:’,
response.status());
console.log(‘Headers:’,
await response.allHeaders());
console.log(‘Body:’,
await response.text());
Interview Tip: Avoid logging tokens, passwords, session cookies, or other secrets.
26. Does Playwright tracing work with API requests?
APIRequestContext exposes tracing capabilities, and Playwright also integrates API activity into broader test debugging workflows. The API request context API exposes a tracing property.
For browser/API integration tests, configure failure artifacts:
use: {
trace: ‘retain-on-failure’,
screenshot: ‘only-on-failure’,
video: ‘retain-on-failure’
}
Interview Tip: Explain which diagnostic artifact you would use for which problem instead of collecting everything permanently.
CI/CD, Docker, and GitHub Actions Questions
27. How would you run Playwright API tests in CI?
name: API Tests
on:
pull_request:
push:
branches:
– main
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v6
– uses: actions/setup-node@v6
with:
node-version: lts/*
– run: npm ci
– run: npx playwright test tests/api
– uses: actions/upload-artifact@v5
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
Interview-Ready Answer:
“I keep API tests fast enough to run on pull requests while reserving larger API regression suites for nightly or release pipelines.”
Interview Tip: Discuss secrets, environment variables, artifacts, retries, and parallel jobs.
28. Why run API tests in Docker?
Interview-Ready Answer: Docker provides a consistent Node.js and dependency environment across developers and CI agents.
FROM node:lts
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD [“npx”, “playwright”, “test”, “tests/api”]
For suites containing both API and browser testing, Playwright’s official container images can provide the browser dependencies as well.
Scenario-Based Playwright API Testing Interview Questions
29. API returns 401 unexpectedly. What do you check?
Problem: Authentication failure.
Possible Causes:
- Missing token
- Expired token
- Wrong token
- Wrong environment
- Incorrect header
- Wrong authentication scheme
Debugging:
console.log(response.status());
console.log(await response.text());
Solution: Verify token generation and environment configuration.
Interview-Ready Answer:
“I would first verify whether the token was generated for the correct environment and whether the Authorization header is correctly constructed. I would then inspect the response body without exposing the credential itself.”
30. API returns 500 intermittently. What would you do?
Problem: Flaky server response.
Root Causes:
- Backend defect
- Dependency outage
- Data race
- Resource exhaustion
- Environment instability
Interview-Ready Answer:
“I would collect request and response metadata, correlate failures with test data and timing, and check service logs. I would not simply add retries because that could hide a production defect.”
31. Tests fail only when run in parallel.
Problem: Tests pass individually.
Root Cause: Shared data.
Solution:
const email =
`qa-${crypto.randomUUID()}@example.com`;
Use unique resources and cleanup.
Interview-Ready Answer:
“I would isolate server-side resources first. Disabling parallel execution should be the last resort.”
32. API response structure changes unexpectedly. What should the test do?
Problem:
Expected:
{
“id”: 100,
“name”: “John”
}
Received:
{
“userId”: 100,
“name”: “John”
}
Solution: Fail clearly and identify the contract mismatch.
A schema validator can make this explicit.
Interview Tip: Distinguish an intentional API version change from an accidental breaking change.
33. API is slow in CI but fast locally.
Possible causes:
- Network latency
- CI resource constraints
- Environment load
- DNS
- Authentication service
- Backend dependency
- Rate limiting
Interview-Ready Answer:
“I would measure response time and compare environments before changing the timeout. A slow service may indicate an infrastructure or backend problem rather than a test problem.”
Advanced Playwright API Testing Framework Architecture
A scalable API framework might use:
playwright-api-framework/
├── tests/
│ ├── smoke/
│ ├── regression/
│ ├── contract/
│ └── integration/
├── api/
│ ├── clients/
│ ├── models/
│ └── schemas/
├── fixtures/
├── auth/
├── test-data/
├── utils/
├── config/
├── reports/
└── playwright.config.ts
Architecture:
Test
↓
Fixture
↓
API Client
↓
API Request Context
↓
Service
↓
Response
↓
Schema + Business Assertions
The test should not know implementation details such as authentication-header construction or URL formatting.
Playwright API Testing Coding Questions
34. Create a reusable authenticated API context.
import {
request,
APIRequestContext
} from ‘@playwright/test’;
async function createApiContext():
Promise<APIRequestContext> {
return request.newContext({
baseURL: process.env.API_URL,
extraHTTPHeaders: {
Authorization:
`Bearer ${process.env.API_TOKEN}`,
Accept: ‘application/json’
}
});
}
Playwright supports creating standalone request contexts through request.newContext().
35. Create and delete test data.
test(‘customer lifecycle’, async ({
request
}) => {
const email =
`qa-${Date.now()}@example.com`;
const create =
await request.post(‘/api/customers’, {
data: {
name: ‘Test Customer’,
}
});
expect(create.status()).toBe(201);
const customer =
await create.json();
const deleteResponse =
await request.delete(
`/api/customers/${customer.id}`
);
expect(deleteResponse.status())
.toBe(204);
});
Interview Tip: Discuss cleanup even if the example is short.
API Testing Interview Questions by Experience
Freshers
Prepare:
- What is API testing?
- HTTP methods
- Status codes
- JSON
- Headers
- Query parameters
- GET/POST basics
- Playwright request
- Basic assertions
2–3 Years
Prepare:
- APIRequestContext
- Authentication
- API chaining
- Test-data setup
- Fixtures
- API/UI integration
- Network mocking
- CI execution
4–5 Years
Prepare:
- API client architecture
- Schema validation
- Parallel execution
- Test-data isolation
- Environment configuration
- Authentication strategies
- API mocking
- CI scalability
Senior SDET
Prepare:
- Enterprise API framework design
- Contract testing strategy
- Service virtualization
- Multi-tenant data
- API versioning
- Observability
- Test ownership
- CI optimization
- Failure classification
Common Playwright API Interview Mistakes
1. Validating only status codes
200 does not prove that the business operation is correct.
2. Hard-coding authentication
Use secure environment configuration.
3. Reusing the same test data
Parallel execution will expose conflicts.
4. Retrying every failed API
A 500 response may indicate a real defect.
5. Logging secrets
Never print tokens or passwords.
6. Creating every UI precondition through the browser
Use APIs where appropriate.
7. Ignoring negative testing
Cover:
400
401
403
404
409
422
429
500
as applicable to the API contract.
8. Treating mocking as real integration testing
Mocked tests and real-service tests serve different purposes.
Playwright API Interview Preparation Roadmap
Level 1 — HTTP Fundamentals
Learn:
- REST
- HTTP methods
- Headers
- Status codes
- JSON
- Authentication
Level 2 — Playwright API
Master:
- request
- APIRequestContext
- GET
- POST
- PUT
- PATCH
- DELETE
- Response validation
Level 3 — Automation Engineering
Add:
- Fixtures
- API clients
- Test-data factories
- Authentication
- API/UI integration
- Mocking
Level 4 — CI/CD
Learn:
- GitHub Actions
- Docker
- Environment variables
- Reports
- Artifacts
- Parallel execution
Level 5 — Senior SDET
Master:
- API framework architecture
- Schema validation
- Contract strategy
- Multi-tenant testing
- Test-data isolation
- Observability
- Large-suite optimization
Playwright API Testing Interview Checklist
Before your interview, make sure you can explain:
- APIRequestContext
- Request fixture
- GET
- POST
- PUT
- PATCH
- DELETE
- Headers
- Query parameters
- Path parameters
- JSON bodies
- Status codes
- Response validation
- Schema validation
- API keys
- JWT
- OAuth
- API chaining
- Test-data setup
- Fixtures
- API/UI integration
- Network mocking
- Parallel API testing
- CI/CD
- Docker
- Reporting
- Debugging
- Framework architecture
FAQs About Playwright API Testing Interview Questions
What are the most important Playwright API testing interview questions?
Focus on APIRequestContext, HTTP methods, authentication, headers, parameters, status codes, JSON validation, request chaining, fixtures, test-data management, API/UI integration, mocking, parallel execution, CI/CD, and debugging.
Can Playwright be used only for UI automation?
No. Playwright can directly test REST APIs using APIRequestContext, and those requests can also be used to prepare and validate server-side state for browser tests.
What is the difference between request and page.request?
The request fixture provides an isolated API request context. page.request is associated with the browser context and shares its cookie storage. Playwright documents both standalone and browser-context-associated API request contexts.
How do you authenticate Playwright API tests?
Use the authentication mechanism required by the API, such as bearer tokens, API keys, basic authentication, OAuth tokens, or cookies. Store credentials securely in environment variables or CI secrets.
Can Playwright API testing be combined with UI testing?
Yes. API calls can establish preconditions before a UI test and validate backend postconditions after UI actions.
How do you mock API responses in Playwright?
For browser traffic, use page.route() and route.fulfill(). Playwright also supports modifying real responses and replaying traffic from HAR files.
How do you make API tests reliable in parallel?
Generate unique data, avoid shared mutable state, isolate authentication where necessary, and make cleanup independent. Parallelism should come after test isolation.
Should API tests validate every JSON field?
Not necessarily. Validate contract-critical fields and business rules. Schema validation can provide structural coverage, while targeted assertions verify business behavior.
