API tests in Playwright let the test runner call an HTTP endpoint directly instead of opening a browser page. They fit health checks, setup checks, and server postcondition checks where the result to verify is a response status plus a small body contract.
The built-in request fixture provides an APIRequestContext for each test and can use baseURL from playwright.config.ts. Keeping the host in config or an environment variable keeps each spec focused on the endpoint path, expected status range, and JSON fields that define success.
A low-side-effect endpoint is the safest first target because failures point to request setup, response parsing, or an API contract change instead of a browser interaction. Assert both the HTTP success range and at least one application-level field so a generic success page or wrong route cannot pass the test.
$ cd ~/projects/playwright-demo
Install Playwright first when the project does not already have @playwright/test.
Related: How to install Playwright with npm
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: process.env.API_BASE_URL ?? 'http://127.0.0.1:4173',
},
});
If the project already has a use block, add only the baseURL line instead of replacing existing browser, trace, or timeout options.
Related: How to set base URL in Playwright tests
import { test, expect } from '@playwright/test';
test('health endpoint returns ready state', async ({ request }) => {
const response = await request.get('/api/health');
await expect(response).toBeOK();
const body = await response.json();
expect(body).toMatchObject({
status: 'ok',
message: 'Playwright fixture ready',
});
});
toBeOK() checks that the response status is in the HTTP 200 to 299 range. Parse JSON only after the status assertion passes so failures point to status handling, body parsing, or field matching.
$ API_BASE_URL=http://127.0.0.1:4173 npx playwright test tests/api/health.spec.ts Running 1 test using 1 worker ✓ 1 tests/api/health.spec.ts:3:5 › health endpoint returns ready state (50ms) 1 passed (1.3s)
Use the API base URL for the environment under test. Keep tokens, cookies, and API keys in environment variables or config loaded from secrets, not in committed spec files.
Related: How to run specific Playwright tests