Introduction
Playwright API Testing with TypeScript is one of the fastest and most reliable ways to automate REST APIs. While Playwright is widely known for browser automation, it also includes powerful built-in support for API testing. This allows QA engineers to validate backend services without using additional HTTP libraries.
If you are a QA Automation Engineer, API tester, Selenium engineer transitioning to Playwright, or a software testing student, learning Playwright API Testing with TypeScript will help you build scalable API automation frameworks. In this tutorial, you’ll learn how to perform API testing with Playwright TypeScript, work with HTTP methods, authenticate APIs, validate responses, and organize enterprise-level API automation projects.
What is Playwright API Testing?
Playwright API Testing is the process of sending HTTP requests and validating API responses using Playwright’s built-in APIRequestContext.
Instead of interacting with a browser, Playwright communicates directly with backend services, making API tests faster and more reliable.
With Playwright REST API Testing, you can:
- Test REST APIs
- Validate JSON responses
- Perform CRUD operations
- Test authentication
- Verify status codes
- Chain API requests
- Create test data for UI automation
This makes Playwright API Automation suitable for both standalone API testing and combined UI + API testing.
Why Use TypeScript for Playwright API Testing?
TypeScript provides additional safety and better development experience compared to JavaScript.
Benefits
- Static type checking
- Better IntelliSense support
- Early error detection
- Cleaner code
- Easier maintenance
- Strong IDE support
- Enterprise-ready development
These advantages make Playwright TypeScript API Testing an excellent choice for large automation projects.
Setting Up Playwright for API Testing with TypeScript
Step 1: Create a New Project
mkdir PlaywrightAPIProject
cd PlaywrightAPIProject
Step 2: Install Playwright
npm init playwright@latest
Choose:
- TypeScript
- Playwright Test
- Install browsers
Step 3: Verify Installation
npx playwright test
Your project is now ready for API automation.
HTTP Methods (GET, POST, PUT, PATCH, DELETE)
GET Request Example
import { test, expect } from ‘@playwright/test’;
test(‘Get User’, async ({ request }) => {
const response = await request.get(
‘https://reqres.in/api/users/2’
);
expect(response.status()).toBe(200);
});
Explanation
- request.get() sends a GET request.
- The response object stores the server response.
- The assertion validates the status code.
POST Request Example
test(‘Create User’, async ({ request }) => {
const response = await request.post(
‘https://reqres.in/api/users’,
{
data: {
name: ‘John’,
job: ‘QA Engineer’
}
}
);
expect(response.status()).toBe(201);
});
Explanation
- The data property contains the JSON payload.
- Playwright automatically serializes the object.
- Status code 201 confirms successful resource creation.
PUT Request Example
test(‘Update User’, async ({ request }) => {
const response = await request.put(
‘https://reqres.in/api/users/2’,
{
data: {
name: ‘Peter’,
job: ‘Automation Tester’
}
}
);
expect(response.ok()).toBeTruthy();
});
PATCH Request Example
test(‘Patch User’, async ({ request }) => {
const response = await request.patch(
‘https://reqres.in/api/users/2’,
{
data: {
job: ‘Senior QA’
}
}
);
expect(response.status()).toBe(200);
});
DELETE Request Example
test(‘Delete User’, async ({ request }) => {
const response = await request.delete(
‘https://reqres.in/api/users/2’
);
expect(response.status()).toBe(204);
});
A 204 No Content response indicates that the resource was deleted successfully.
Request Headers, Query Parameters, Authentication, and Payloads
Request Headers
const response = await request.get(
‘https://api.example.com/users’,
{
headers: {
Accept: ‘application/json’,
Authorization: ‘Bearer your_token’
}
}
);
Headers are commonly used for authentication and content negotiation.
Query Parameters
const response = await request.get(
‘https://reqres.in/api/users’,
{
params: {
page: 2,
per_page: 5
}
}
);
Query parameters help filter or paginate API results.
Bearer Token Authentication
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
Store tokens in environment variables instead of hardcoding them.
API Key Authentication
headers: {
“x-api-key”: process.env.API_KEY
}
Many public APIs require API keys.
Basic Authentication
headers: {
Authorization:
“Basic ” +
Buffer.from(“admin:password”).toString(“base64”)
}
Basic Authentication encodes the username and password using Base64.
OAuth 2.0 Overview
OAuth 2.0 typically requires obtaining an access token first and then using it as a Bearer token for subsequent API requests.
API Response Validation and Assertions
Validating only the status code is not enough.
const body = await response.json();
expect(response.status()).toBe(200);
expect(body.data.id).toBe(2);
expect(body.data.first_name).toBe(“Janet”);
Validate
- Status code
- Response body
- Response headers
- Response time
- Business data
- Error messages
Comprehensive validation improves API test reliability.
Enterprise Playwright API Framework Folder Structure
PlaywrightAPIFramework
│
├── api
│ UserAPI.ts
│ AuthAPI.ts
│
├── tests
│ users.spec.ts
│
├── fixtures
│ apiFixture.ts
│
├── utils
│ APIHelper.ts
│
├── config
│ environment.ts
│
├── test-data
│ users.json
│
├── .env
│
└── playwright.config.ts
Folder Explanation
| Folder | Purpose |
| api | Reusable API service classes |
| tests | Test scripts |
| fixtures | Shared setup |
| utils | Helper methods |
| config | Environment settings |
| test-data | JSON payloads |
| .env | Tokens and secrets |
Request Flow
Test Script
│
▼
API Helper
│
▼
REST API
│
▼
Response Validation
│
▼
Assertions
This modular architecture is commonly used in enterprise Playwright API Framework using TypeScript implementations.
Best Practices
Follow these best practices for Playwright API Testing with TypeScript:
- Create reusable API service classes.
- Store secrets in environment variables.
- Validate response bodies and status codes.
- Keep payloads in JSON files.
- Separate API logic from test logic.
- Use descriptive assertions.
- Test positive and negative scenarios.
- Reuse authentication tokens.
- Log requests and responses.
- Generate HTML reports.
- Organize tests by feature.
- Integrate with CI/CD pipelines.
- Use TypeScript interfaces for request and response models.
- Keep API methods independent.
- Review failed requests using logs and reports.
Common Mistakes
Avoid these common issues:
- Hardcoding authentication tokens.
- Validating only status codes.
- Mixing test logic with API helper methods.
- Ignoring response body validation.
- Duplicating request code.
- Not testing error scenarios.
- Storing secrets in source code.
- Ignoring environment-specific configurations.
Real-Time API Testing Scenarios
Scenario 1: Login API
Login
│
▼
Generate Token
│
▼
Access Profile
Scenario 2: E-Commerce Application
Login
│
▼
Search Product
│
▼
Add to Cart
│
▼
Checkout
Scenario 3: Banking Application
- Authenticate user
- Retrieve account details
- Transfer funds
- Verify transaction history
- Validate account balance
These scenarios demonstrate how API automation supports real-world enterprise applications.
Playwright API Testing with TypeScript Interview Questions
1. What is Playwright API Testing?
Testing REST APIs using Playwright’s built-in API request functionality.
2. What is APIRequestContext?
It is the Playwright object used to send HTTP requests.
3. Which HTTP methods are supported?
GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
4. Why use TypeScript for API automation?
It provides type safety, better tooling, and easier maintenance.
5. What is Bearer Token Authentication?
A method of authenticating requests using an access token in the Authorization header.
6. What is API Key Authentication?
Authentication using a unique application key.
7. What is Basic Authentication?
Authentication using a Base64-encoded username and password.
8. How do you validate API responses?
By checking status codes, headers, response body, and business rules.
9. Why store tokens in environment variables?
To improve security and support multiple environments.
10. Can Playwright combine API and UI testing?
Yes. API calls can prepare test data before running UI tests.
FAQs
Is Playwright suitable for API testing?
Yes. It provides built-in support for REST API automation.
Can Playwright test authenticated APIs?
Yes. It supports Bearer Tokens, API Keys, Basic Authentication, OAuth, and custom headers.
Does Playwright support TypeScript?
Yes. TypeScript is fully supported and recommended.
Can Playwright replace Postman?
Playwright is ideal for automated API testing, while Postman is commonly used for manual API exploration.
Is API automation faster than UI automation?
Yes. API tests communicate directly with backend services, making them significantly faster.
Can Playwright integrate with CI/CD?
Yes. It works with GitHub Actions, Jenkins, Azure DevOps, GitLab CI, and other CI/CD platforms.
Should request payloads be stored separately?
Yes. Using JSON files improves readability and maintainability.
Can beginners learn Playwright API testing?
Yes. Playwright’s API is simple, well-documented, and beginner-friendly.
