Contact Us

API Testing with Playwright: Requests, Assertions and Auth (TypeScript)

Mike Krasnovskyi Head of Automation
  • Last updated:
  • 12 min read

Playwright includes an API request context, the request fixture, that sends HTTP requests without opening a browser. Use it to test REST endpoints on their own, to prepare test data for UI tests, and to share authentication between API and UI tests in one suite.

Every example below was run against a live REST API on Playwright 1.65.1. Seventeen tests, all green, before any of it went into this article.

When to Test APIs with Playwright (and When Not To)

Playwright isn’t always the right tool. Here’s where it fits:

NeedPlaywrightPostman / NewmanREST AssuredPact
API tests beside existing UI tests
Best fit
Separate suite
Separate suite
No
Shared auth between API and UI
Built in
Manual
No
No
Exploratory API work by hand
Poor
Best fit
No
No
A Java or Kotlin codebase
Poor fit
Workable
Best fit
Workable
Consumer-driven contracts
No
No
No
Best fit
Seeding data for UI tests
Built in
Awkward
No
No

The pattern worth noticing: Playwright wins when your API tests live next to UI tests. One framework, one runner, one report, one CI job, and one set of skills on the team rather than two.

Where it loses is worth being honest about. There’s no request builder to click around in, no shared collection your product manager can run, and no consumer-driven contract verification. If you need a human to explore an API by hand, Postman is the better tool and this article won’t change that.

If you’re new to the subject itself rather than the tool, start with our introduction to API testing. This guide assumes you know what a 201 means and want the code.

Setup: baseURL and Headers in playwright.config.ts

Two settings do most of the work. baseURL keeps environment details out of your tests, and extraHTTPHeaders applies to every request:

Setup_baseURL_and_Headers_in_playwright_config_ts_1

That api project has no browser settings at all, so tests matching *.api.spec.ts never launch one. Our sixteen API tests finish in about a second. The browser tests in the same repo take twice as long on their own.

Naming your API specs differently from your UI specs is what makes that split possible. You can run npx playwright test –project=api on every commit and keep the slower browser tests for the merge. If Playwright itself is new to you, our Playwright tutorial for beginners covers the basics this builds on.

Your First API Test

Your_First_API_Test_1

Line by line:

  • async ({ request }) — the request fixture is Playwright’s API client. No page, so no browser starts.
  • request.get(‘/api/orders/A-1001’) — relative to baseURL.
  • response.ok() is true for any 2xx. response.status() gives you the exact code when it matters, and it usually does — a 201 and a 200 mean different things. Our API testing cheatsheet has the status codes worth knowing.
  • await response.json() parses the body. It’s async, and forgetting the await here gives you a Promise that passes every assertion you throw at it.

There’s a shorter assertion when you only care that the call succeeded:

Your_First_API_Test_2

It passes for any 2xx and prints the status and body when it fails, which beats a bare toBeTruthy() on a bad day.

Sending Request Bodies

Write bodies with data. Playwright serialises objects to JSON and sets the content type:

Sending_Request_Bodies_1

toMatchObject checks the fields you name and ignores the rest. That matters: asserting the whole body means your test breaks every time someone adds a field, which is a change that broke nothing.

The server-generated id gets a regex rather than a fixed value, because you can’t know it in advance and shouldn’t pretend to.

Test the unhappy path in the same breath:

Sending_Request_Bodies_2

Updates and removals work the same way. Building the path once keeps the test readable, and note that a 204 has no body to parse:

Sending_Request_Bodies_3

The last two lines are the part people skip. Deleting and then confirming it’s gone is the difference between testing that the endpoint returned 204 and testing that it deleted something.

Query Strings, Headers, and Timeouts

3 request options cover most of what’s left.

Query parameters. Build them with params rather than string concatenation, and Playwright encodes them for you:

Query_Strings_Headers_and_Timeouts_1

Response headers. headers() returns them lowercased, which saves an argument about casing:

Query_Strings_Headers_and_Timeouts_2

Failing fast. By default a 404 is a response you inspect, not an error. That’s usually what you want, since testing error codes is half the job. When a call is setup rather than the thing under test, failOnStatusCode turns a bad status into a thrown error so the test stops at the real cause:

Query_Strings_Headers_and_Timeouts_3

Use it on the arrange steps, never on the assert step. A seeding call that silently 500s and lets the test continue produces a confusing failure three lines later.

Validating the Response Schema

Field-by-field assertions miss the thing you care about: did the shape of the response change? A schema catches that in one line. Here it is with zod:

Validating_the_Response_Schema_1

2 things happen here that are easy to miss.

z.infer derives the TypeScript type from the schema, so the contract is defined once instead of twice. And parse throws on a mismatch with a message that names the field — we broke one deliberately and got Invalid input: expected string, received number at total. That’s a better failure than expected 49.9 to be “49.9”.

If your API publishes an OpenAPI definition, that’s your source of truth for the schema. Our Swagger walk-through covers reading one.

Authentication

Logging in inside every test is slow and repetitive. Playwright’s recommended approach is a setup project that authenticates once and saves the state. Keep the credentials in environment variables and import them, so no real values sit in the repo.

Authentication_1

Wire it up as a dependency:

Authentication_2

Both projects depend on setup and read the same file, which is what makes the next section work.

Now tests carry the session without mentioning it:

Authentication_3

3 things worth knowing.

That state file holds real credentials. Put playwright/.auth in .gitignore before the first run, not after.

Sessions expire. Playwright’s docs say so plainly, and a suite that fails every Monday morning is usually a storage state older than the token’s lifetime.

Project-level auth makes the 401 path untestable — the request context is already authenticated. For that one test, open a clean context:

Authentication_4

A context made with playwright.request.newContext() has its own cookie jar. We found this the way everyone does: the 401 test started returning 200 the moment we added storageState to the project.

When your API uses a bearer token

storageState saves cookies and local storage. If your API authenticates with an Authorization header instead, it has nothing to save, and plenty of guides skip over that.

The pattern that works is a setup project that captures the token, plus a fixture that attaches it:

Authentication_5
Authentication_6

Import test from your fixtures file instead of @playwright/test, and every test gets an authenticated api client:

Authentication_7

The same .gitignore rule applies, and more urgently — a token file is a credential sitting on disk.

Optimize Your Testing Today

Ready to level up your quality? From test automation services to full-scale software testing outsourcing, we help you build a product that is extraordinary.

Combining API and UI Tests

This is the argument for doing both in one framework, and it rests on one line from Playwright’s docs: “Storage state is interchangeable between BrowserContext and APIRequestContext.”

Log in once, and the same session authenticates your API calls and your browser.

Combining_API_and_UI_Tests_1

Compare that with the all-UI version: click through a creation form, wait for redirects, assert, then click through a deletion flow. Slower, and it fails when the form changes even though you were testing the orders page.

Set up through the API, assert on the UI, clean up through the API. The browser only does the part that needs a browser.

One practical note: baseURL is shared, so this is simplest when your UI and API sit behind the same host. When they don’t, give the UI project its own baseURL and point API calls at the other one with an absolute URL or a dedicated request context.

Mocking the API in UI Tests vs Testing the Real API

Both are right, for different jobs.

Mock with page.route when you’re testing the UI. You get determinism and you can produce states the real API won’t give you on demand:

Mocking_the_API_in_UI_Tests_vs_Testing_the_Real_API_1

That’s how you test an empty state, an error banner, or a slow response without asking a backend team to break something for you.

Hit the real API when you’re testing the integration. A mock proves your UI renders what you told it to. It proves nothing about whether the real endpoint still returns that shape — which is exactly the bug that reaches production.

The split that works: real API in your API specs and a small number of end-to-end flows, mocks in the UI specs covering edge states. If every UI test is mocked and no test hits the real thing, a renamed field ships.

A useful habit is to build mocks from the same schema you validate the real API against. Then a contract change breaks the schema test, and you know the mocks need updating — instead of finding out when a user does. The schema is the single definition; the mock and the assertion both read from it.

Running API Tests in CI

API tests are fast and need no browser, so run them on every push and gate the browser tests behind them:

Running_API_Tests_in_CI_1

Point baseURL at the environment with an env var rather than editing the config.

Common Mistakes

Shared state between tests. A test that creates A-1001 and a test that deletes it will fight the moment they run in parallel. Create what you need inside the test and delete it at the end.

Hardcoded tokens. A token pasted into a spec expires, leaks into git, and breaks the suite for everyone. Use a setup project.

No cleanup. Every run leaves orders behind until the list endpoint returns thousands of rows and a test that asserts on a count starts failing. Delete what you create.

Asserting the whole body. toEqual on an entire response means a new optional field breaks your test. Use toMatchObject for the fields you care about, or a schema for the shape.

Only testing 200s. The interesting behaviour is at 400, 401, 404 and 422. An API that returns 200 with an error message in the body is a bug your tests should be catching.

Running API tests serially out of habit. They’re network calls, not browsers, so they parallelise well. If yours can’t run in parallel, that’s usually the shared-state problem above rather than a limit of the tool.

Testing the mock instead of the API. Easy to do by accident: a page.route handler left in a shared fixture means your “integration” test never leaves the browser. If a test is meant to hit the real service, assert on something only the real service produces — a generated id, a server timestamp.

Put API Tests Where Your UI Tests Already Live

A separate API testing tool means a separate suite, a separate report, and a separate thing to maintain. Running both in Playwright means one framework, one CI job, and auth that’s set up once.

We do API testing and UI automation as one engagement, not two. Our test automation services cover both, built by ISTQB-certified QA engineers in your stack rather than handed over as a demo — the same software testing services team on either side of the browser.

Contact us, and we’ll look at what your API coverage is missing.

FAQs

No. The api project never launches one, so a CI job that only runs API tests can skip the browser download step altogether. We pointed Playwright at an empty browsers directory and all sixteen API tests still passed. That saves a few minutes and a few hundred megabytes on every run.

Yes. Traces work the same way they do for browser tests: set trace: ‘on-first-retry’ and open the result with npx playwright show-trace. The trace records each request and response, so you can read the body the server actually returned instead of guessing from an assertion message.

No. Playwright measures correctness, not throughput. There’s no concurrency model for sustained load, no ramp-up profiles and no percentile reporting. Use k6, Gatling or JMeter for that, and keep Playwright for whether the endpoint returns the right thing.

No. Playwright ships bindings for Python, Java and .NET, and each one exposes the same APIRequestContext with matching method names. TypeScript is the better default when your UI tests already live in the same repo, which is most of the reason to pick Playwright for API testing in the first place.

Yes, and it needs nothing special. Every GraphQL call is a POST to a single endpoint, with the operation carried in the request body — so you send it with the same post method you’d use for any other request, and the body goes in the data option. One thing to watch. GraphQL usually answers with 200 even when the operation fails, and reports the problem in an errors field rather than in the status code. A status check on its own will wave a broken call through, so assert on the response body.

Ready to Speed Up the Testing Process?

We'll get back to you within 24 hours
Which services are you interested in? (Select multiple if needed or leave blank)