These Playwright API testing interview questions are real situations an interviewer gives you, not definitions to memorise. Each answer shows how to investigate and fix the problem step by step, with TypeScript code that was run against the free SQA Tools practice REST API. They follow Module 9 of the Playwright TypeScript tutorial.
📖 How to use this page: read the scenario, answer it out loud in 60 to 90 seconds, then compare with the steps. The follow-up and red-flag lines show where interviewers push and where candidates lose marks.
🧪 API Test Design and Assertions
Q1. Scenario: You are asked to automate a create-update-delete flow for an /objects endpoint. The manual testers only check that each call returns 2xx.
What the interviewer is checking: whether you test the whole resource lifecycle and the data, not just status codes.
Answer:
- Create the object with a unique name so parallel runs never collide.
- Assert
201and theLocationheader that points to the new resource. - Update one field and assert the response contains the new value.
- Delete it and accept the documented success code (200 or 204).
- Prove the delete worked: a GET on the same id must now return
404.
📄 tests/api/objects.spec.ts
import { test, expect } from '@playwright/test';
const API = 'https://sqatools.in/wp-json/sqa-api/v1';
test('object CRUD lifecycle', async ({ request }) => {
const created = await request.post(`${API}/objects`, {
data: { name: `pw-crud-${Date.now()}`, data: { price: 10 } },
});
expect(created.status()).toBe(201);
const obj = await created.json();
expect(created.headers()['location']).toContain(`/objects/${obj.id}`);
const patched = await request.patch(`${API}/objects/${obj.id}`, { data: { data: { price: 12 } } });
expect(patched.ok()).toBeTruthy();
expect((await patched.json()).data.price).toBe(12);
const deleted = await request.delete(`${API}/objects/${obj.id}`);
expect([200, 204]).toContain(deleted.status());
const gone = await request.get(`${API}/objects/${obj.id}`);
expect(gone.status()).toBe(404);
});
Follow-up they may ask: Why not reuse one fixed object id for all tests? Shared data couples tests: one failure or a parallel worker changes the state for every other test. Each test should create and own its data.
Red flag answer: “I check that every call returns 200.” That misses wrong bodies, wrong codes like 200 instead of 201, and deletes that silently do nothing.
Q2. Scenario: A backend change renamed email to emailAddress. All your API tests still passed, and the UI broke in production.
What the interviewer is checking: contract thinking: asserting the shape and types of the response, not just one or two values.
Answer:
- Explain why the tests passed: they checked the status and maybe
id, never the full shape. - Assert the fields consumers depend on with
toMatchObjectand asymmetric matchers such asexpect.any(String). - For wide coverage, validate against a JSON Schema (the practice API publishes them at
/schema/{name}) with a library like Ajv. - Agree with the backend team on contract tests in their pipeline so renames are caught before deploy.
📄 tests/api/users.spec.ts
test('user has the expected shape', async ({ request }) => {
const res = await request.get(`${API}/users/1`);
expect(res.status()).toBe(200);
const { data } = await res.json();
expect(data).toMatchObject({
id: 1,
username: 'asha',
email: expect.stringContaining('@'),
role: expect.any(String),
active: expect.any(Boolean),
});
});
Follow-up they may ask: Why toMatchObject and not toEqual? toEqual fails when the API adds a new optional field, which is not a breaking change. toMatchObject checks only the fields you list.
Red flag answer: “We compare the whole response to a saved JSON file.” That breaks on every timestamp or new field and trains the team to ignore failures.
Q3. Scenario: The product owner says error responses are “random”. Mobile developers cannot show proper messages to users.
What the interviewer is checking: that you treat error responses as part of the contract and test them as carefully as success paths.
Answer:
- List the documented errors: 400 invalid input, 401 no credentials, 403 not allowed, 404 not found, 422 validation, 429 rate limit.
- Write one test per error that checks the status, the machine-readable
codeand the message. - For validation, send several bad fields at once and check that every field is reported, not just the first.
📄 tests/api/errors.spec.ts
test('unknown user returns a clear 404', async ({ request }) => {
const res = await request.get(`${API}/users/999`);
expect(res.status()).toBe(404);
expect(await res.json()).toEqual({
error: { status: 404, code: 'not_found', message: 'User 999 does not exist. Valid ids are 1 to 12.' },
});
});
test('invalid user payload lists every field error', async ({ request }) => {
const res = await request.post(`${API}/validate/user`, { data: { name: '', email: 'not-an-email', age: -1 } });
expect(res.status()).toBe(422);
const body = await res.json();
console.log(JSON.stringify(body));
expect(body.error.code).toBe('validation_failed');
});
🖥️ Output
{"error":{"status":422,"code":"validation_failed","message":"3 field(s) failed validation.","details":[{"field":"name","message":"name is required: text of 2 to 50 characters."},{"field":"email","message":"email is required and must be a valid email address."},{"field":"age","message":"age is required: a whole number from 18 to 100 (not a string)."}]}}
Follow-up they may ask: Would you assert the exact error message text? Assert the stable code always; assert the message only when it is shown to users or documented, because wording changes are common.
Red flag answer: “Negative testing is just checking for 500 errors.” A 500 is a bug; the interesting cases are the correct 4xx responses.
Q4. Scenario: A product listing supports category, sort and order parameters. A bug made order=asc return items in database order.
What the interviewer is checking: whether you assert the behaviour a parameter promises (filtering, ordering), not just that the call succeeds.
Answer:
- Pass parameters with the
paramsoption, so Playwright encodes them correctly. - Check the filter: every item must have the requested category.
- Check the order: compare the returned list with a sorted copy.
- Add one invalid value to prove the API rejects it with
400and names the field.
📄 tests/api/products.spec.ts
test('electronics sorted by price, cheapest first', async ({ request }) => {
const res = await request.get(`${API}/products`, {
params: { category: 'electronics', sort: 'price', order: 'asc' },
});
expect(res.status()).toBe(200);
const { data } = await res.json();
const prices = data.map((p: { price: number }) => p.price);
expect(data.every((p: { category: string }) => p.category === 'electronics')).toBe(true);
expect(prices).toEqual([...prices].sort((a, b) => a - b));
});
test('an invalid filter value returns 400 with details', async ({ request }) => {
const res = await request.get(`${API}/products`, { params: { category: 'audio' } });
expect(res.status()).toBe(400);
const body = await res.json();
expect(body.error.code).toBe('invalid_parameter');
expect(body.error.details[0].field).toBe('category');
});
Follow-up they may ask: How would you test pagination? Request page 1 and page 2 with the same page size and assert there is no overlap and no gap in ids, plus the total-count header if the API provides one.
Red flag answer: “I check the first item only.” The bug is usually in the middle or the last page.
🔐 Authentication and Authorisation
Q5. Scenario: Every API test logs in first, so the suite takes 6 minutes and sometimes hits the login rate limit.
What the interviewer is checking: fixture design: logging in once and reusing a ready, authenticated request context.
Answer:
- Move login into a fixture that returns an
APIRequestContextwith theAuthorizationheader already set. - Create one fixture per role (admin, viewer) so tests ask for the role they need by name.
- If tokens are long-lived, make the fixture worker-scoped so each worker logs in once.
- Dispose contexts in the fixture teardown to avoid leaking connections.
📄 tests/api/auth.spec.ts
import { test as base, expect, request as pwRequest, APIRequestContext } from '@playwright/test';
const API = 'https://sqatools.in/wp-json/sqa-api/v1';
type ApiFixtures = { adminApi: APIRequestContext; viewerApi: APIRequestContext; tempObject: { id: string } };
async function loginAs(username: string, password: string) {
const anon = await pwRequest.newContext();
const res = await anon.post(`${API}/auth/login`, { data: { username, password } });
expect(res.ok()).toBeTruthy();
const { access_token } = await res.json();
await anon.dispose();
return pwRequest.newContext({ extraHTTPHeaders: { Authorization: `Bearer ${access_token}` } });
}
const test = base.extend<ApiFixtures, { adminToken: string }>({
adminApi: async ({}, use) => {
const ctx = await loginAs('admin', 'admin@123');
await use(ctx);
await ctx.dispose();
},
viewerApi: async ({}, use) => {
const ctx = await loginAs('viewer', 'viewer@123');
await use(ctx);
await ctx.dispose();
},
tempObject: async ({ adminApi }, use, testInfo) => {
const res = await adminApi.post(`${API}/token/objects`, {
data: { name: `pw-${testInfo.workerIndex}-${Date.now()}` },
});
const obj = await res.json();
await use(obj);
await adminApi.delete(`${API}/token/objects/${obj.id}`); // cleanup even if the test failed
},
});
test('viewer can read but not delete', async ({ viewerApi, tempObject }) => {
expect((await viewerApi.get(`${API}/token/objects/${tempObject.id}`)).status()).toBe(200);
const del = await viewerApi.delete(`${API}/token/objects/${tempObject.id}`);
expect(del.status()).toBe(403);
});
test('token identifies the user', async ({ adminApi }) => {
const me = await (await adminApi.get(`${API}/auth/me`)).json();
console.log(JSON.stringify(me));
expect(JSON.stringify(me)).toContain('admin');
});
🖥️ Output
{"data":{"username":"admin","name":"Admin User","role":"admin","issued_at":"2026-11-24T05:20:16Z","expires_at":"2026-11-24T05:35:16Z","can_write":true}}
Follow-up they may ask: The token expires after 15 minutes. What happens in a 40-minute run? Keep the fixture test-scoped (a fresh token per test, as above), or refresh it when a request returns 401. The practice API has /auth/refresh for exactly this.
Red flag answer: “I hard-code a token copied from Postman.” It expires, leaks in Git, and hides login bugs.
Q6. Scenario: A security review finds that read-only users can delete records through the API, although the UI hides the Delete button.
What the interviewer is checking: that you test authorisation on the server, per role, and not only through the UI.
Answer:
- Explain that hiding a button is not security; the API must refuse the call.
- Create test data as an admin in a fixture, then call the write endpoint as the viewer.
- Assert
403(authenticated but not allowed), not401(not authenticated). - Turn this into a role-by-endpoint matrix and run it on every build.
📄 tests/api/auth.spec.ts (uses the fixtures above)
test('viewer can read but not delete', async ({ viewerApi, tempObject }) => {
expect((await viewerApi.get(`${API}/token/objects/${tempObject.id}`)).status()).toBe(200);
const del = await viewerApi.delete(`${API}/token/objects/${tempObject.id}`);
expect(del.status()).toBe(403);
});
Follow-up they may ask: What is the difference between 401 and 403? 401 means “who are you?”: missing or invalid credentials. 403 means “I know who you are, and you may not do this.”
Red flag answer: “The UI does not allow it, so it is covered by UI tests.”
Q7. Scenario: Your service supports HTTP Basic auth for partners and an API key for internal tools. You need tests for both, plus a test that a missing key is rejected.
What the interviewer is checking: knowledge of request.newContext() options for different auth types.
Answer:
- Use
httpCredentialsfor Basic auth; Playwright builds the header for you. - Use
extraHTTPHeadersfor an API key or any custom header. - Always include the negative case: no credentials must return
401. - Keep credentials in environment variables in real projects; these are public practice values.
📄 tests/api/auth-types.spec.ts
import { test, expect, request as pwRequest } from '@playwright/test';
const API = 'https://sqatools.in/wp-json/sqa-api/v1';
test('basic auth and API key', async () => {
const basic = await pwRequest.newContext({ httpCredentials: { username: 'sqa_user', password: 'sqa@123' } });
expect((await basic.get(`${API}/basic/profile`)).status()).toBe(200);
const keyed = await pwRequest.newContext({ extraHTTPHeaders: { 'X-API-Key': 'sqa-key-12345' } });
expect((await keyed.get(`${API}/apikey/profile`)).status()).toBe(200);
const noKey = await pwRequest.newContext();
expect((await noKey.get(`${API}/apikey/profile`)).status()).toBe(401);
await Promise.all([basic.dispose(), keyed.dispose(), noKey.dispose()]);
});
Follow-up they may ask: How do you share an API login with UI tests? After logging in with request, call request.storageState({ path }) and load that file in the browser context with storageState, if the app uses cookies.
Red flag answer: “I put the password in the test file.” Secrets belong in CI secrets and .env files that are not committed.
⏱️ Timeouts, Caching and Reliability
Q8. Scenario: One slow endpoint sometimes takes 40 seconds. When it does, the whole test times out and the report says nothing useful.
What the interviewer is checking: whether you set request-level timeouts and make the failure message point at the real cause.
Answer:
- Set a per-request
timeoutthat matches the service level agreement, for example 2 seconds. - Assert the timeout explicitly in a test for the slow path, so the report names the slow call.
- Log the response time header (
X-Response-Timehere) for trend tracking. - Raise it with the backend team as a performance bug; do not just raise the test timeout.
📄 tests/api/timeouts.spec.ts
test('a slow endpoint fails fast with a per-request timeout', async ({ request }) => {
await expect(request.get(`${API}/delay/5`, { timeout: 2000 })).rejects.toThrow(/Timeout 2000ms exceeded/);
});
Follow-up they may ask: Where else can you set API timeouts? In request.newContext({ timeout }) for a whole context, or use.actionTimeout in the config. The per-call option wins.
Red flag answer: “I increase the test timeout to 2 minutes.” The suite gets slower and the slow endpoint is never fixed.
Q9. Scenario: The API team added ETags to cut bandwidth. You are asked to prove caching works.
What the interviewer is checking: HTTP knowledge beyond status 200: conditional requests and 304.
Answer:
- Make a first GET and read the
ETagheader. - Repeat the GET with
If-None-Matchset to that value. - Assert
304 Not Modifiedwith no body. - Update the resource, then prove the old ETag now returns
200with a new ETag.
📄 tests/api/etag.spec.ts
test('ETag returns 304 when nothing changed', async ({ request }) => {
const first = await request.get(`${API}/products/101`);
const etag = first.headers()['etag'];
expect(etag).toBeTruthy();
const second = await request.get(`${API}/products/101`, { headers: { 'If-None-Match': etag } });
expect(second.status()).toBe(304);
});
Follow-up they may ask: Why might the ETag header be missing in your test but present in Postman? A proxy or CDN may strip or rewrite it, or you hit a different URL (for example an id that does not exist returns 404 without an ETag). Print response.headers() and the status first.
Red flag answer: “304 is an error code.”
Q10. Scenario: Your API tests pass on your laptop, but every request returns 403 with an HTML page in CI.
What the interviewer is checking: debugging from evidence: reading the body and headers, and knowing about firewalls and CDNs in front of APIs.
Answer:
- Print the status, headers and the first part of the body. An HTML 403 page means something in front of the API answered, not the API itself (which returns JSON).
- Check the headers for the proxy, WAF or CDN name (for example
serveror a request-id header). - Compare what differs in CI: IP range, missing VPN, user agent, or a query pattern the firewall blocks.
- Fix it at the source: allow-list the CI runners or the endpoint pattern with the platform team. Do not fake a browser user agent to sneak past security.
Follow-up they may ask: How do you make this failure obvious next time? Assert the content-type is JSON before calling response.json(), so the error says “got text/html” instead of “Unexpected token <“.
Red flag answer: “I add retries.” A firewall block will fail on every retry.
⚠️ Watch out: Calling response.json() on an HTML error page throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. When you see that error, the request reached the wrong thing: read await response.text() to see what answered.
🏗️ Framework Design for API Tests
Q11. Scenario: Tests running in parallel delete each other’s data, and the shared test environment fills up with thousands of leftover records.
What the interviewer is checking: test data ownership and cleanup that runs even when a test fails.
Answer:
- Each test creates its own data with a unique name (worker index plus timestamp).
- Create the data in a fixture, and delete it after
use(): fixture teardown runs even if the test fails. - Never depend on data created by another test or on test order.
- Add a nightly job that removes anything older than a day with your test prefix, as a safety net.
📄 tempObject fixture (from tests/api/auth.spec.ts above)
tempObject: async ({ adminApi }, use, testInfo) => {
const res = await adminApi.post(`${API}/token/objects`, {
data: { name: `pw-${testInfo.workerIndex}-${Date.now()}` },
});
const obj = await res.json();
await use(obj);
await adminApi.delete(`${API}/token/objects/${obj.id}`); // cleanup even if the test failed
},
Follow-up they may ask: Why not clean up in afterEach? It works, but a fixture keeps setup and cleanup together, runs only for tests that use it, and can be shared across files.
Red flag answer: “We reset the database before the run.” That does not stop parallel workers clashing during the run.
Q12. Scenario: Your manager asks why you use Playwright for API tests instead of a separate tool like Postman or REST Assured.
What the interviewer is checking: a balanced view of tool choice, not tool loyalty.
Answer:
- One language, one runner and one report for UI and API tests, so the team maintains one framework.
- API calls can prepare data for UI tests (create a user, then log in through the UI) in the same test.
- Built-in retries, parallel workers, traces and CI integration already exist.
- Be honest about limits: Postman is better for exploratory checks and sharing collections; dedicated tools are better for load testing.
Follow-up they may ask: What is APIRequestContext? Playwright’s HTTP client. The built-in request fixture gives you one per test that uses the config’s baseURL and extraHTTPHeaders; request.newContext() creates extra ones with their own settings.
Red flag answer: “Playwright is a UI tool, so API tests are a workaround.”
Q13. Scenario: A UI test for “order history” is slow and flaky because it first places three orders through the checkout UI.
What the interviewer is checking: hybrid tests: using the API for setup and the UI only for what you are testing.
Answer:
- Create the three orders through the API in a fixture: seconds instead of minutes.
- Log in with saved storage state, then open only the order history page in the UI.
- Assert in the UI what the user sees, and optionally cross-check totals against the API response.
- Keep one separate end-to-end checkout test so the full UI flow is still covered once.
Follow-up they may ask: When would you mock the API instead of calling it? With page.route() when you need states that are hard to create (empty list, server error, slow response) or when the backend is not ready. Never mock in the one test that proves the integration works.
Red flag answer: “Every test should go through the UI because that is what users do.”
❓ Frequently Asked Questions
🤔 Can Playwright be used only for API testing?
Yes. Tests that use only the request fixture never start a browser, so a pure API suite runs fast and needs no browser download in CI beyond the Playwright package.
🤔 How do I send query parameters with Playwright request?
Use the params option, for example request.get(url, { params: { category: 'electronics' } }). Playwright encodes the values for you.
🤔 How do I validate a JSON schema in Playwright?
Playwright has no built-in schema validator. Fetch or store the schema, compile it with a library such as Ajv, and assert that validate(body) is true, printing validate.errors on failure.
🤔 Where can I practise Playwright API testing for free?
Use the SQA Tools practice REST API: users, products, orders, temporary objects you can create and delete, and Basic, API key and Bearer token auth.
🔗 More Playwright Interview Preparation
- Playwright Interview Questions and Answers (scenario-based, all topics)
- Playwright Interview Questions for Experienced Engineers (2, 3 and 5+ years)
- 200 Playwright + TypeScript Interview Questions
- Playwright Test Data, Configuration and Cross-Browser Interview Questions
- Playwright Cheat Sheet
- Playwright mock interviews: 13 timed tests, one per module
🎬 Watch the full Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in