Can Playwright Do API Testing? Complete Beginner’s Guide with TypeScript Examples

Introduction

One of the most common questions beginners ask when learning Playwright is “Can Playwright do API testing?” Traditionally, QA engineers used tools like Postman for manual API testing and REST Assured for API automation. However, modern automation frameworks are evolving, and Microsoft Playwright now offers powerful built-in support for REST API testing.

This means you can automate API testing and UI testing using the same framework, programming language, and test runner. For automation engineers, this reduces maintenance, simplifies framework design, and improves end-to-end test coverage.

Whether you’re a QA Automation Engineer, SDET, Selenium engineer transitioning to Playwright, or a beginner learning automation testing, understanding Playwright API testing is an important skill.

In this guide, you’ll learn how Playwright performs API testing, how to use APIRequestContext, write your first API tests with TypeScript, and combine API and UI automation in a single framework.


What Is Playwright?

Microsoft Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of modern web applications.

Playwright supports:

  • Chromium
  • Firefox
  • WebKit

Modern features include:

Unlike many traditional automation tools, Playwright includes browser automation and API testing in one framework.


Can Playwright Do API Testing? (Direct Answer)

The short answer is:

Yes. Playwright has built-in support for REST API testing through the APIRequestContext class.

You can use Playwright to:

Because API testing is built directly into Playwright, there is no need to install a separate API automation framework for many common scenarios.


How Playwright API Testing Works

Playwright provides an APIRequestContext object that sends HTTP requests directly to your application’s APIs.

The architecture looks like this:

Playwright Test

        │

        ▼

APIRequestContext

        │

        ▼

REST API

        │

        ▼

Application Server

        │

        ▼

Database

Unlike browser automation, API tests communicate directly with the backend server without opening a browser. This makes API tests faster and useful for validating backend functionality independently of the user interface.


Benefits of Playwright API Testing

Using Playwright for API testing offers several advantages.

1. One Framework for UI and API Testing

You can automate frontend and backend testing using a single framework.

Benefits include:

  • Less code duplication
  • Easier maintenance
  • Shared test data
  • Shared authentication
  • Unified reporting

2. Fast Execution

Since API tests do not launch a browser, they execute much faster than UI tests.

This makes them ideal for:


3. Built-in TypeScript Support

Playwright works seamlessly with TypeScript.

Advantages include:

  • Type safety
  • Better IntelliSense
  • Easier debugging
  • Improved maintainability

4. Easy Response Validation

Playwright allows you to validate:

  • Status codes
  • Response body
  • JSON values
  • Headers
  • Response time

All using built-in APIs.


5. Authentication Support

Playwright supports various authentication mechanisms, including:

  • Bearer Tokens
  • Basic Authentication
  • Custom Headers
  • Cookies

This makes it suitable for testing secure REST APIs.


Setting Up Playwright for API Testing

Step 1: Create a Playwright Project

npm init playwright@latest

This command creates a new Playwright project with the recommended folder structure.


Step 2: Create an API Test File

Example:

tests/

    api.spec.ts


Step 3: Import Playwright Test

import { test, expect } from ‘@playwright/test’;

The test function defines your API test, and expect is used to validate responses.


Real-World Playwright API Testing Example (GET Request)

The following example sends a GET request to a public REST API.

import { test, expect } from ‘@playwright/test’;

test(‘Get User Details’, async ({ request }) => {

    const response = await request.get(

        ‘https://jsonplaceholder.typicode.com/users/1’

    );

    expect(response.status()).toBe(200);

    const body = await response.json();

    expect(body.name).toBe(‘Leanne Graham’);

});

Step-by-Step Explanation

Import Playwright Test

import { test, expect } from ‘@playwright/test’;

Imports Playwright’s testing framework and assertion library.


Create the Test

test(‘Get User Details’, async ({ request }) => {

The request fixture provides access to APIRequestContext, allowing you to send HTTP requests without opening a browser.


Send the GET Request

const response = await request.get(

    ‘https://jsonplaceholder.typicode.com/users/1’

);

This sends an HTTP GET request to retrieve user details.


Validate the Status Code

expect(response.status()).toBe(200);

Verifies that the server responded successfully.


Read the JSON Response

const body = await response.json();

Converts the response into a JavaScript object.


Validate Response Data

expect(body.name).toBe(‘Leanne Graham’);

Checks that the expected user name is returned.


Playwright API Testing Example (POST Request)

Creating resources through POST requests is another common API testing scenario.

import { test, expect } from ‘@playwright/test’;

test(‘Create New User’, async ({ request }) => {

    const response = await request.post(

        ‘https://jsonplaceholder.typicode.com/users’,

        {

            data: {

                name: ‘John’,

                email: ‘john@example.com’

            }

        }

    );

    expect(response.status()).toBe(201);

    const body = await response.json();

    expect(body.name).toBe(‘John’);

});

This example demonstrates how to:

  • Send JSON data
  • Validate the HTTP status code
  • Verify values returned in the response body

Combining API Testing with UI Testing

One of Playwright’s biggest advantages is that it allows you to combine API testing and UI testing within the same automation framework. Instead of using separate tools like Postman for APIs and another framework for browser automation, you can validate backend services and the user interface in a single test.

Example Workflow

API Login

      │

      ▼

Receive Authentication Token

      │

      ▼

Launch Browser

      │

      ▼

Open Dashboard

      │

      ▼

Verify User Information

Real-World Example

Imagine you’re testing an e-commerce application.

Instead of creating a user through the UI every time, you can:

  1. Create a test user using an API.
  2. Launch the browser.
  3. Log in using that user.
  4. Verify the dashboard.
  5. Delete the user through another API after the test.

This approach makes tests faster, more reliable, and easier to maintain.


Playwright API Testing vs Postman vs REST Assured

FeaturePlaywrightPostmanREST Assured
API Testing✅ Yes✅ Yes✅ Yes
UI Testing✅ Yes❌ No❌ No
TypeScript Support✅ ExcellentScripts Only❌ Java Only
Parallel Execution✅ Built-inLimitedDepends on Test Runner
CI/CD Integration✅ ExcellentGoodExcellent
Browser Automation✅ Yes❌ No❌ No
Built-in Test Runner✅ Yes❌ NoDepends on JUnit/TestNG
End-to-End Testing✅ Yes❌ No❌ No

Which Tool Should You Choose?


Best Practices for Playwright API Testing

Following best practices helps you build scalable and maintainable API automation.

1. Use a Base URL

Instead of repeating the server URL in every request, configure it once.

use: {

    baseURL: ‘https://api.example.com’

}


2. Validate More Than Status Codes

Don’t stop at checking HTTP 200.

Also verify:

  • Response body
  • JSON fields
  • Response headers
  • Business rules
  • Response time (when appropriate)

3. Store Test Data Separately

Keep request payloads in JSON files instead of hardcoding them.

Example:

test-data/

users.json

orders.json


4. Reuse Authentication

Avoid generating authentication tokens before every test.

Reuse tokens or authenticated request contexts where appropriate to improve execution speed.


5. Keep API Tests Independent

Every API test should execute independently without relying on another test.

This improves:

  • Parallel execution
  • Reliability
  • Debugging
  • CI/CD execution

6. Organize API Tests

Example enterprise structure:

PlaywrightFramework

tests/

   api/

   ui/

pages/

fixtures/

utils/

test-data/

Keeping API and UI tests organized makes large projects easier to maintain.


Enterprise Use Cases

Playwright API Testing is commonly used in enterprise applications.

Banking

  • Account creation
  • Fund transfer APIs
  • Transaction history
  • Authentication

E-commerce

  • Product APIs
  • Shopping cart
  • Order management
  • Payment validation

Healthcare

  • Patient registration
  • Appointment scheduling
  • Medical record APIs

SaaS Applications

  • User management
  • Subscription APIs
  • Authentication
  • Dashboard data validation

Playwright API Testing Interview Questions

1. Can Playwright do API testing?

Yes. Playwright provides built-in API testing through APIRequestContext, allowing you to test REST APIs without additional libraries.


2. What is APIRequestContext?

It is Playwright’s API client used to send HTTP requests such as GET, POST, PUT, PATCH, and DELETE.


3. Can Playwright replace Postman?

Playwright is excellent for automated API testing and combining API with UI tests. Postman remains valuable for manual API exploration, collaboration, and documentation.


4. Can Playwright test REST APIs?

Yes. It supports all common HTTP methods and response validation.


5. How do you validate API responses?

By checking:

  • Status code
  • JSON values
  • Headers
  • Response body
  • Expected business logic

6. Can API and UI testing be combined?

Yes. This is one of Playwright’s strongest features. You can create data through APIs and verify it through the UI in the same test suite.


7. Is Playwright suitable for enterprise API automation?

Yes. It supports retries, fixtures, parallel execution, reporting, and CI/CD integration, making it suitable for enterprise projects.


8. Does Playwright support authentication?

Yes. You can test APIs secured with Bearer tokens, Basic Authentication, cookies, and custom headers.


9. Which language is recommended?

TypeScript is commonly recommended because it integrates seamlessly with Playwright and provides excellent tooling.


10. Can Playwright API tests run in CI/CD?

Yes. They integrate well with GitHub Actions, Azure DevOps, Jenkins, GitLab CI, and other CI/CD platforms.


Frequently Asked Questions

Can Playwright do API testing?

Yes. Playwright includes built-in support for REST API testing through APIRequestContext.


Does Playwright support GET and POST requests?

Yes. It supports GET, POST, PUT, PATCH, DELETE, and other HTTP methods.


Is Playwright good for API automation?

Yes. It is well suited for API automation, especially when API and UI testing need to work together in the same framework.


Can Playwright replace REST Assured?

For teams using TypeScript or JavaScript, Playwright can often cover both UI and API automation. REST Assured remains a strong choice for Java-centric API testing.


Does Playwright support response validation?

Yes. You can validate status codes, headers, JSON data, cookies, and other response details.


Can Playwright perform end-to-end testing?

Yes. A typical workflow is:

  • Create data through APIs.
  • Validate it in the UI.
  • Clean up through APIs.

Is Playwright suitable for beginners?

Yes. Its simple API, integrated test runner, and consistent syntax make it approachable for newcomers.


Can Playwright be used in CI/CD?

Yes. It integrates well with popular CI/CD platforms and supports parallel execution and reporting.


Should I learn Postman before Playwright?

Learning basic HTTP concepts with Postman is helpful, but you can also begin directly with Playwright if your goal is automated API and UI testing.


What should I learn after Playwright API Testing?

Recommended next topics include:

These skills will help you build enterprise-ready automation frameworks.

Leave a Comment

Your email address will not be published. Required fields are marked *