Playwright TypeScript API Testing Framework Setup
In this article
This guide walks you through building a maintainable API testing framework using Playwright and TypeScript. You'll end up with a structured project that separates test logic, API clients, and configuration, making it easy to add new tests, handle authentication, and run tests in CI. The framework uses Playwright's built-in request context, which means you don't need extra HTTP libraries, and TypeScript gives you type safety across your test suite.
What You'll Need
- Node.js 16 or later installed on your machine
- A code editor (VS Code recommended)
- Basic familiarity with TypeScript and REST APIs
- An API endpoint to test (you can use a public test API like JSONPlaceholder)
Step-by-Step
- Initialize the project
Create a new directory and run
npm init -yto generate a package.json file. - Install dependencies
Run
npm install -D @playwright/test typescript @types/node. This installs Playwright's test runner, TypeScript, and Node.js type definitions. - Set up TypeScript configuration
Create a
tsconfig.jsonfile with the following settings:{ "compilerOptions": { "target": "ES2022", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["tests", "src", "playwright.config.ts"] } - Create the Playwright configuration
Create
playwright.config.tsat the root. This file tells Playwright where tests are, sets the base URL for your API, and configures reporters. Here's a minimal config:import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests', timeout: 30000, use: { baseURL: 'https://jsonplaceholder.typicode.com', extraHTTPHeaders: { 'Content-Type': 'application/json', }, }, reporter: [['list'], ['html', { open: 'never' }]], }); - Create a folder structure
Create the following directories:
testsfor test files,src/apifor API client classes,src/modelsfor TypeScript interfaces, andsrc/utilsfor helpers. - Define data models
In
src/models, create a fileuser.tswith an interface that represents the data you'll work with. For example:export interface User { id: number; name: string; email: string; } - Build an API client
Create
src/api/BaseClient.tsthat wraps Playwright'srequestfixture. This class will handle common methods like GET, POST, PUT, DELETE, and also handle authentication if needed. Here's a basic version:import { APIRequestContext } from '@playwright/test'; export class BaseClient { constructor(protected request: APIRequestContext) {} async get(path: string) { const response = await this.request.get(path); return response; } async post(path: string, data?: object) { const response = await this.request.post(path, { data }); return response; } // Similar for put, patch, delete } - Create specific API endpoints
For each resource, create a class that extends BaseClient. For example,
src/api/UsersClient.ts:import { BaseClient } from './BaseClient'; import { User } from '../models/user'; export class UsersClient extends BaseClient { async getAll(): Promise{ const response = await this.get('/users'); return response.json(); } async getById(id: number): Promise { const response = await this.get(`/users/${id}`); return response.json(); } } - Write your first test
Create
tests/users.spec.ts. Use Playwright'stestandexpect. Therequestfixture is available in each test, so you can instantiate your client:import { test, expect } from '@playwright/test'; import { UsersClient } from '../src/api/UsersClient'; test.describe('Users API', () => { test('GET /users returns a list of users', async ({ request }) => { const usersClient = new UsersClient(request); const users = await usersClient.getAll(); expect(Array.isArray(users)).toBeTruthy(); expect(users.length).toBeGreaterThan(0); }); test('GET /users/1 returns a single user', async ({ request }) => { const usersClient = new UsersClient(request); const user = await usersClient.getById(1); expect(user.id).toBe(1); expect(user.name).toBeDefined(); }); }); - Run the tests
Add a script to package.json:
"test": "playwright test". Then runnpm test. You should see the tests pass. - Add authentication support
If your API requires a token, modify the BaseClient to accept a token and set it in the headers. You can also use Playwright's
globalSetupto fetch a token once and store it in a file or environment variable. - Create a fixture for the client
To avoid repeating instantiation in every test, create a custom fixture in
src/fixtures.ts:import { test as base } from '@playwright/test'; import { UsersClient } from './api/UsersClient'; export const test = base.extend<{ usersClient: UsersClient }>({ usersClient: async ({ request }, use) => { const client = new UsersClient(request); await use(client); }, });Then importtestfrom this file in your tests instead of from @playwright/test. - Add environment configuration
Use
dotenvto manage environment-specific variables like base URL and API keys. Installdotenv, create a.envfile, and load it in the Playwright config. - Organize tests with groups
Use
test.describeblocks to group related tests. Use tags like@smokeor@regressionto selectively run tests with--grep. - Add reporting and CI integration
Playwright's HTML reporter is great for local debugging. For CI, you can use the JSON or JUnit reporter to integrate with your CI tool. Add a
ciscript that runs tests with the appropriate reporter.
Common Mistakes
- Not separating API clients from tests – This leads to duplication and makes maintenance harder.
- Hardcoding URLs and credentials – Use environment variables and the baseURL config.
- Ignoring status codes – Always assert on the HTTP status code, not just the body content.
- Not handling authentication properly – Don't log in for every test; use a shared token or a setup step.
- Overusing test data – Avoid creating the same data in every test; use fixtures or setup scripts.
Tips
- Use TypeScript interfaces for all API responses to catch errors at compile time.
- Create helper functions for common assertions (e.g.,
expectSuccess). - Use Playwright's
requestfixture directly for one-off requests, but use client classes for repeated patterns. - Keep your test files small and focused on one resource or workflow.
- Use
test.beforeAllto set up data that is shared across tests in a describe block. - Run tests in parallel by default; ensure your tests are independent.
Troubleshooting
- Tests fail with 404 errors – Check your baseURL and the path in your client. Make sure the API is reachable.
- TypeScript compilation errors – Run
npx tsc --noEmitto see errors. Ensure your tsconfig includes the right files. - Tests hang or timeout – Increase the timeout in the config, or check if your API is slow. Also make sure you're not accidentally using a browser context instead of request context.
- Authentication fails – Verify that your token is being sent correctly. Use or set it in extraHTTPHeaders .
- Tests pass locally but fail in CI – Ensure environment variables are set in CI. Use a
.env.examplefile to document needed variables.
Frequently Asked Questions
Do I need a browser for API testing?
No. Playwright's request fixture uses Node.js's HTTP client, so no browser is launched. This makes tests fast and lightweight.
How do I handle dynamic data like timestamps?
Use a library like faker to generate random data, or compute values inside the test. Avoid hardcoding values that change.
Can I reuse the same token across tests?
Yes. Use a globalSetup file to fetch a token once and store it in a file or environment variable that tests read.
How do I run only a subset of tests?
Use --grep to filter by test name, or use tags. For example: npx playwright test --grep "@smoke".
What's the best way to structure test data?
Create a separate data folder with JSON or TypeScript objects. Use factories to generate unique data per test run.
How do I integrate this with CI/CD?
Install Playwright browsers in your CI image, run npm ci and npm test. Use the JUnit reporter to get results in a format your CI tool understands.