PRACTICAL GUIDE / playwright API testing interview scenarios
18 Playwright API and UI Hybrid Testing Interview Scenarios
Master 18 senior Playwright API and UI scenarios covering request contexts, cookie sharing, setup, browser verification, cleanup, and boundary tradeoffs.
In this guide9 sections
- Define the Business Workflow Boundary
- API Preconditions and UI Outcomes
- 1. Why would you create an order through the API before testing the order-details page?
- 2. How would you prevent an API setup failure from appearing as a missing UI row?
- 3. When would API setup invalidate the purpose of a UI test?
- Request Context and Cookie Semantics
- 4. What is the difference between request and context.request in a test?
- 5. Why can an API call through page.request sign the browser in?
- 6. When should you create an isolated APIRequestContext?
- 7. How would you prove that an API login and browser context share the intended session?
- Authentication, CSRF, and Role Boundaries
- 8. How would you handle CSRF protection in an API-assisted browser workflow?
- 9. How would you use the API as one role and the browser as another?
- 10. Why is inserting a bearer token into localStorage a weak default?
- Data Isolation and Cleanup
- 11. How would you keep API-created records unique under parallel execution?
- 12. Where should cleanup live for a resource created by API setup?
- 13. How would you test browser deletion and still keep teardown idempotent?
- Cross-Layer Assertions and Consistency
- 14. When should a test verify a UI action through an API postcondition?
- 15. How would you handle eventual consistency after a browser action?
- 16. How would you test a GraphQL-backed UI without turning the scenario into endpoint testing?
- Debugging and Suite Architecture
- 17. How would you diagnose an API call that succeeds while the browser still shows stale data?
- 18. How would you review a suite that uses API shortcuts for every UI step?
- Hybrid Test Checklist
- Conclusion: Optimize Preconditions, Not Truth
What you will learn
- Define the Business Workflow Boundary
- API Preconditions and UI Outcomes
- Request Context and Cookie Semantics
- Authentication, CSRF, and Role Boundaries
Hybrid API and UI tests are valuable when they keep the browser focused on behavior only a browser can prove. They become dangerous when setup bypasses the very workflow under test, API failures are ignored, or a request client unexpectedly shares authentication cookies with the page.
These scenarios ask a senior candidate to draw the boundary. State why the API is used, validate the precondition close to its source, verify the user outcome in the browser, and clean up through the owner that created the resource. The best answer is faster than an all-UI test without becoming less honest.
Define the Business Workflow Boundary
Playwright's API testing guide supports preparing server state, validating postconditions, and reusing authenticated state. A senior answer first identifies which step is prerequisite plumbing and which step is product behavior. It then chooses an associated or isolated request context intentionally.
Animated field map
API and UI Hybrid Interview Flow
A defensible hybrid test establishes a narrow API precondition, verifies the browser outcome, and cleans state at the same ownership boundary.
01 / business workflow
Business workflow
Separate prerequisite state from behavior the user must perform.
02 / api setup
API setup choice
Choose shared or isolated request context and validate it.
03 / browser verification
Browser verification
Assert rendering, interaction, and customer-visible outcome.
04 / state cleanup
State cleanup
Delete resources idempotently without hiding failures.
05 / boundary explanation
Candidate boundary explanation
Defend realism, speed, authentication, and coverage gaps.
Do not praise API setup simply because it is fast. If the requirement is that a customer can create a support ticket through the form, creating it over HTTP and only viewing it does not cover that requirement.
API Preconditions and UI Outcomes
1. Why would you create an order through the API before testing the order-details page?
The creation form is not the behavior under test, so an API call can create an exact order state quickly and deterministically. I would validate the response, capture the order ID, navigate to its detail page, and assert the user-visible representation. A separate UI test covers order creation. This division narrows failure diagnosis: setup failure is API infrastructure, while rendering and action failures belong to the detail workflow.
2. How would you prevent an API setup failure from appearing as a missing UI row?
Assert the setup response immediately, including success status and the minimum fields the test consumes. If creation fails, stop before navigation and include a safe correlation ID. Do not return undefined from a helper and let a locator time out later. The report should show that the precondition was never established, which directs investigation to service health, credentials, or test data rather than the browser.
test('shows a seeded order', async ({ request, page }) => {
const response = await request.post('/api/test/orders', {
data: { sku: 'TRAIL-1', quantity: 2 },
})
expect(response.ok()).toBeTruthy()
const order: { id: string; status: string } = await response.json()
expect(order.id).toBeTruthy()
await page.goto(`/orders/${order.id}`)
await expect(page.getByRole('heading', { name: `Order ${order.id}` })).toBeVisible()
await expect(page.getByTestId('order-status')).toHaveText(order.status)
})3. When would API setup invalidate the purpose of a UI test?
It invalidates the test when it bypasses the behavior named by the requirement: form validation, browser-generated payload, accessibility interaction, client-side transformation, or navigation. I would write the scenario statement before choosing setup. API setup can still create surrounding data, but the critical user action stays in the browser. A candidate should be able to name exactly what confidence was traded away.
Request Context and Cookie Semantics
4. What is the difference between request and context.request in a test?
The built-in request fixture is an API request context configured for the test, while context.request and page.request are associated with that browser context. The associated client shares its cookie jar with the browser. I would choose based on whether API calls should authenticate as and update the current browser user. The variable name alone is not enough; the answer must explain cookie ownership.
5. Why can an API call through page.request sign the browser in?
The associated APIRequestContext uses the browser context's cookies and applies Set-Cookie response headers back to that same jar. A successful login response can therefore authenticate subsequent page navigation. I would verify the application's full auth model because local storage or client bootstrap may still be required. I would also keep the login API response and credentials out of logs and attachments.
6. When should you create an isolated APIRequestContext?
Create one when API traffic must not read or mutate browser cookies, such as probing an unauthenticated endpoint while the page is signed in, acting as a second service identity, or validating logout independently. Dispose it when finished. The APIRequestContext reference makes this cookie distinction explicit; accidental sharing can make a denial test pass as the wrong user.
7. How would you prove that an API login and browser context share the intended session?
Use the context-associated request client to log in, assert the response without exposing the token, then navigate to a protected page and assert the expected identity. I would also test a fresh isolated context to prove the protected page is not publicly accessible. This positive and negative pair confirms that shared state, rather than residual global data, enabled the browser session.
Authentication, CSRF, and Role Boundaries
8. How would you handle CSRF protection in an API-assisted browser workflow?
I would follow the application's real protocol: obtain the CSRF cookie or bootstrap token and send the corresponding header or form value. Using a context-associated client can preserve cookies, but it does not invent the application token. I would not disable CSRF in an end-to-end environment unless the test purpose explicitly excludes that control. A separate security test should verify missing and mismatched token rejection.
9. How would you use the API as one role and the browser as another?
Use separate authentication owners. Create an isolated request context with the service or admin credential, and create the browser context from the user role's state. Name both clients by role and assert resource ownership explicitly. Sharing page.request would silently perform the API action as the browser user. The test must make the cross-role setup visible and protect both identities from logs.
10. Why is inserting a bearer token into localStorage a weak default?
It assumes storage keys, token format, and application bootstrap behavior, bypassing cookies, redirects, refresh handling, and other initialization. I would prefer the supported login API followed by saved state or a context-linked request. Direct injection may be acceptable for a narrow component-level contract when the app team owns that hook, but the answer should state which real authentication behavior is no longer covered.
Data Isolation and Cleanup
11. How would you keep API-created records unique under parallel execution?
Generate a run and test-specific business key, let the service return the authoritative ID, and use that ID for browser navigation and cleanup. Avoid timestamps alone because distributed workers can collide or produce hard-to-trace data. The test should not search for the latest record. Stable ownership makes retries, shards, and delayed indexing diagnosable without relying on suite order.
12. Where should cleanup live for a resource created by API setup?
Prefer a fixture that owns creation and deletion, or a try/finally block for a tightly local scenario. Cleanup uses the returned ID, tolerates already-deleted records, and runs after browser assertions. It should record a real deletion failure without replacing the original test error. A global after hook that guesses what each test created is less reliable and obscures resource ownership.
13. How would you test browser deletion and still keep teardown idempotent?
The browser performs the deletion because that is the scenario. Teardown then attempts deletion through the API and treats a verified not-found response as success. Other failures remain visible. This allows cleanup to recover if the UI action failed before completion while accepting that a successful test already removed the resource. Idempotent cleanup is essential when the product action and infrastructure share ownership of final state.
Cross-Layer Assertions and Consistency
14. When should a test verify a UI action through an API postcondition?
Use an API postcondition when the durable server result matters and the UI alone could display optimistic or stale state. After the browser action, query the specific resource and assert the required field. Keep the UI assertion too, because the user experience and persisted state are different contracts. The API check should poll only when the architecture is genuinely asynchronous and should have a bounded diagnostic timeout.
15. How would you handle eventual consistency after a browser action?
I would identify the asynchronous boundary and poll the authoritative read endpoint for the exact state, using meaningful intervals and a bounded total duration. A fixed sleep is both wasteful and unreliable. The failure should report the last observed state and resource ID. I would not poll the UI and API indefinitely together, because that obscures whether rendering or backend propagation failed.
16. How would you test a GraphQL-backed UI without turning the scenario into endpoint testing?
Use the API to seed only required entities or inspect one durable postcondition. In the browser, assert the rendered business state and interaction. Avoid exhaustive schema assertions in the hybrid test; a contract or API suite owns that depth. If routing GraphQL traffic, match operation name and variables rather than one shared URL alone, or the mock may answer the wrong operation.
Debugging and Suite Architecture
17. How would you diagnose an API call that succeeds while the browser still shows stale data?
I would verify the browser and request client target the same environment and identity, inspect cache and service-worker behavior, check eventual consistency, and examine the page's actual data request. The setup response may be successful but point to a different tenant or region. I would compare resource IDs and safe correlation headers before adding reloads. A forced refresh can hide an application invalidation defect.
18. How would you review a suite that uses API shortcuts for every UI step?
I would map each requirement to the layer that proves it. Keep API setup for expensive unrelated preconditions, restore browser actions for customer-visible behavior, and move detailed endpoint assertions into API suites. I would standardize request clients by authentication boundary, centralize response validation, and add fixture-owned cleanup. The goal is not maximum API use; it is the fewest slow steps consistent with honest end-to-end evidence.
Hybrid Test Checklist
- Write the browser behavior under test before choosing API setup.
- Select associated or isolated request contexts from cookie ownership.
- Validate every setup response before using returned data.
- Keep role identities visible and separate.
- Use authoritative IDs for navigation, assertions, and cleanup.
- Assert both the customer-visible outcome and durable server state when both matter.
- Preserve dedicated UI and API coverage for boundaries a shortcut bypasses.
Conclusion: Optimize Preconditions, Not Truth
The strongest hybrid test removes irrelevant UI setup while preserving the behavior the requirement actually names. Choose request context by cookie semantics, fail immediately when preconditions are absent, and let the creator own cleanup. Pair browser evidence with an API postcondition only when it proves a different contract. A senior SDET uses the API to sharpen the UI scenario, never to make an incomplete workflow look complete.
// LIVE COURSE / THE TESTING ACADEMY
Playwright Automation Mastery
Go beyond Selenium. Master Playwright with JS/TS in 90 days.
From the instructor behind this guide.
Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.
PRIMARY REFERENCES
Verify the details at the source
QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.
- 01Playwright documentation
Microsoft
Canonical API, locator, fixture, browser, and test-runner behavior.
- 02Playwright best practices
Microsoft
Official guidance for resilient tests, isolation, and user-facing locators.
- 03
- 04
FAQ / QUICK ANSWERS
Questions testers ask
Why combine API setup with Playwright UI verification?
API setup can create precise preconditions quickly while the browser verifies the customer-facing behavior. This keeps the UI scenario focused, provided separate tests cover creation through the interface.
Does page.request share cookies with the page?
Yes. page.request is the browser context's associated APIRequestContext, so requests use and update the same cookie jar. Create an isolated request context when cookie sharing is not desired.
Should hybrid tests assert API responses before using their data?
Yes. Check status and the minimum required schema before navigating. Otherwise failed setup can surface later as a confusing missing UI element rather than a precise API precondition failure.
Where should hybrid test cleanup happen?
Place cleanup in a fixture or finally block owned by the resource creator. Make it idempotent, use stable identifiers, and preserve the original UI failure if cleanup also encounters a problem.
How do hybrid tests avoid duplicating API test coverage?
Assert only the setup and postcondition details needed by the UI scenario. Keep exhaustive endpoint validation in API-focused suites and use the browser to verify behavior that only the rendered workflow can prove.
RELATED GUIDES
Continue the learning route
GUIDE 01
Playwright API Testing: Validate APIs Inside Your E2E Suite
Playwright API testing guide covering request contexts, setup flows, assertions, authentication, fixtures, UI strategy, and CI-ready checks.
GUIDE 02
How to Write API Test Cases
How to write API test cases with practical templates, CRUD examples, auth checks, negative paths, and a review checklist for reliable service coverage.
GUIDE 03
API Automation Framework: Build a Maintainable Test Suite
API automation framework guide covering architecture, tools, test data, assertions, CI, reporting, mocks, contracts, and mistakes to avoid.
GUIDE 04
Test Cases for API Endpoint: REST QA Checklist
Test cases for API endpoint QA covering methods, payloads, auth, status codes, schema, pagination, errors, idempotency, logs, and safe failures.