API AUTOMATIONBEGINNER

Part 2: Playwright API Testing Tutorial: Setting Up Project & Sending Your First API Request

Set up a Playwright API testing project from scratch. Learn how to configure APIRequestContext, baseURL, send your first GET request, validate API responses, and avoid common beginner mistakes.

iff Solution Academy July 17, 2026 16 min read Updated July 17, 2026
Playwright API Testing REST API APIRequestContext TypeScript Beginner GET Request JSONPlaceholder

Introduction

In the previous tutorial, we learned why Playwright has become one of the best frameworks for API automation and how enterprise teams use it to build scalable automation solutions.

Now it's time to start building our project.

By the end of this chapter, you'll have a fully functional Playwright API automation project capable of sending HTTP requests and validating API responses.

Prerequisites

Before getting started, make sure you have the following installed on your machine:

  • Node.js (v18 or later recommended)
  • Visual Studio Code
  • Basic knowledge of JavaScript or TypeScript
  • Basic understanding of REST APIs and HTTP methods

You can verify your installation by running:

bash
node -v
npm -v

If both commands return version numbers, you're ready to proceed.

Creating a New Playwright Project

Create a new Playwright project using the official setup command:

bash
npm init playwright@latest

During installation, Playwright will ask several questions. Choose the following options:

text
TypeScript
tests folder
GitHub Actions (Optional)
Install Playwright Browsers

Once the installation completes, your project structure will look similar to this:

text
playwright-api-framework/
│
├── node_modules/
├── tests/
├── playwright.config.ts
├── package.json
├── tsconfig.json
└── package-lock.json

This project is capable of running both UI and API tests. No additional HTTP libraries are required.

Understanding APIRequestContext

The heart of Playwright API testing is APIRequestContext. Think of it as an HTTP client built directly into Playwright.

Instead of opening Chrome and clicking buttons, APIRequestContext communicates directly with your application's backend.

It supports every common HTTP method, including:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • HEAD
  • OPTIONS

It also supports:

  • Authentication
  • Custom Headers
  • Cookies
  • JSON Payloads
  • Form Data
  • File Uploads
  • Query Parameters
  • Response Validation

This eliminates the need for third-party libraries such as Axios or Request.

Configuring Playwright for API Testing

Open playwright.config.ts and configure a common base URL.

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({

  testDir: './tests',

  timeout: 30000,

  retries: process.env.CI ? 2 : 0,

  reporter: [
    ['html'],
    ['list']
  ],

  use: {

    baseURL: 'https://jsonplaceholder.typicode.com',

    extraHTTPHeaders: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    }

  }

});

Why Use a Base URL?

Without a Base URL:

ts
await request.get("https://jsonplaceholder.typicode.com/posts/1");

With Base URL:

ts
await request.get("/posts/1");

Using a Base URL provides several benefits:

  • Cleaner test code
  • Easier environment switching
  • Less duplication
  • Better maintainability

If your application moves from Development to QA or Production, you'll only need to change the Base URL in one place.

Creating Your First API Test

Create a new file:

text
tests/get-post.spec.ts

Add the following code:

tests/get-post.spec.ts
import { test, expect } from '@playwright/test';

test("Get a single post", async ({ request }) => {

    const response = await request.get("/posts/1");

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

    const body = await response.json();

    expect(body.id).toBe(1);

    expect(body.userId).toBe(1);

});

This is your very first API automation test. Although the code is simple, it demonstrates the complete lifecycle of an API request.

Understanding the Code

Let's break down what's happening.

Step 1

Playwright automatically provides a request fixture.

ts
async ({ request })

This fixture creates an APIRequestContext for your test.

Step 2

Send a GET request.

ts
const response = await request.get("/posts/1");

Playwright automatically combines this endpoint with the configured Base URL. The actual request becomes:

text
https://jsonplaceholder.typicode.com/posts/1

Step 3

Validate the Status Code.

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

This confirms the request completed successfully.

Step 4

Convert the response into JSON.

ts
const body = await response.json();

Now the API response becomes a JavaScript object that can easily be validated.

Step 5

Verify the response data.

ts
expect(body.id).toBe(1);

expect(body.userId).toBe(1);

Instead of checking only the status code, always validate the actual business data returned by the API.

Running Your Test

Execute the following command:

bash
npx playwright test

To run a specific file:

bash
npx playwright test tests/get-post.spec.ts

To view the HTML report:

bash
npx playwright show-report

The report displays request details, test duration, pass/fail status, error messages, and stack traces. This makes debugging much easier compared to reading console logs.

Understanding APIResponse

Every request returns an APIResponse object. The most commonly used methods include:

ts
response.status()

response.ok()

response.headers()

response.json()

response.text()

response.body()

Example:

ts
expect(response.ok()).toBeTruthy();

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

const json = await response.json();

These methods cover nearly every validation you'll perform in API automation.

Best Practices

As your framework grows, following a few best practices will make it easier to maintain:

Keep Tests Independent

Each test should create and validate its own data instead of relying on another test to run first.

Validate More Than Status Codes

A 200 OK response does not guarantee the API returned correct data. Always validate important fields in the response body.

Use Meaningful Test Names

Instead of test("Test 1"), prefer test("GET /posts/{id} returns the correct post details"). Descriptive names make reports easier to understand.

Avoid Hardcoding URLs

Configure a common Base URL in playwright.config.ts so you can switch environments without editing every test.

Common Beginner Mistakes

Many beginners make the same mistakes when starting API automation:

  • Forgetting to use await with API requests.
  • Validating only the status code.
  • Hardcoding URLs throughout the project.
  • Combining multiple scenarios into a single test.
  • Writing tests that depend on execution order.

Avoiding these mistakes from the beginning will help you build a stable and scalable automation framework.

Interview Tip

A common interview question is: "Why should we use Playwright instead of Axios for API testing?"

Playwright provides a built-in HTTP client that integrates seamlessly with the Playwright Test Runner. This allows UI and API tests to share the same configuration, fixtures, authentication, reporting, and CI/CD pipeline. It reduces framework complexity and enables hybrid testing where API calls and browser interactions work together in a single automation framework.

What's Next?

Now that you've successfully sent your first API request, the next step is to explore different HTTP methods.

In Part 3, we'll build a complete CRUD API test suite using GET, POST, PUT, PATCH, and DELETE. You'll also learn how to validate response payloads, organize reusable request methods, and follow enterprise-level coding practices used by professional automation engineers.

Choosing the Right Request Context

Playwright gives you three ways to make an HTTP call and they are not interchangeable. The built-in request fixture is isolated per test and is what you want for the vast majority of API specs. A context created with request.newContext() lets you set headers, a base URL, or a proxy for a group of calls and is the right tool inside a worker-scoped fixture. Finally page.request shares cookies and storage state with the live browser page — use it only when you deliberately want the API call to see the same session the UI is using, for example when you set up data mid-journey.

Getting this wrong produces the classic symptom of an API test that passes alone and fails in a suite: the call inherited a cookie jar from a previous browser interaction, or two tests shared one context and one of them logged out. When in doubt, pick the most isolated option that still lets the test do its job.

The second decision is where to put headers. Content-Type and Accept belong on the context because they never change. Authorization belongs on a fixture because it changes per role. Idempotency keys and correlation IDs belong on the individual call because they change per request. Layering them in that order keeps every test readable — a spec should show only the header that is actually interesting to that test.

Common Mistakes

  • Calling response.json() without checking response.ok() first — a 500 returning HTML throws an unhelpful parse error and hides the real status.
  • Forgetting to dispose contexts created with request.newContext(), which leaks sockets in long runs.
  • Sending an object with data: when the API expects form encoding, or using form: when it expects JSON. Playwright will happily send either.
  • Relying on default timeouts for slow report endpoints instead of passing an explicit timeout on that single call.

Frequently Asked Questions

How do I send a raw string or binary body?

Pass data as a string or Buffer and set the Content-Type header yourself. Playwright only serialises to JSON automatically when you hand it a plain object.

Why does my POST return 415?

The server rejected the media type. Either you sent form data to a JSON endpoint or your context is overriding Content-Type with a value the API does not accept.

Can I inspect API calls in the trace viewer?

Yes. API requests made through the request fixture appear in the trace timeline with full request and response detail, which makes debugging a CI-only failure far quicker than adding console logs.

Playwright Framework Series

View all →
  1. 1Getting Started with Playwright: Installation, Setup, and Your First Test
  2. 2Playwright Locators: The Complete Guide with Real-World Examples
  3. 3Playwright Actions: Complete Guide to Click, Fill, Hover, Keyboard, Mouse & File Upload
  4. 4Playwright Assertions Complete Guide: Web-First Assertions, Auto-Retry & Custom Matchers
  5. 5Playwright Auto Waiting: The Complete Guide with Real-World Examples
  6. 6Playwright Fixtures: The Complete Guide with Real-World Examples
  7. 7Playwright Browser Context & Multiple Tabs: The Complete Guide with Real-World Examples
  8. 8Playwright Authentication & Session Management: Complete Guide with Enterprise Examples
  9. 9Playwright Network Interception & API Mocking: Complete Guide with Real-World Examples
  10. 10Playwright Page Object Model (POM): The Complete Guide with Enterprise Examples
  11. 11Page Object Model with Playwright: A Practical Guide
  12. 12How to Build a Robust Professional Playwright Framework from Scratch (Step-by-Step)
  13. 13Building an Enterprise Playwright Framework from Scratch

API Testing Series

View all →
  1. 1Part 1 : Playwright API Testing Tutorial: Build Enterprise-Level API Automation Framework
  2. 2Part 2: Playwright API Testing Tutorial: Setting Up Project & Sending Your First API Request
  3. 3Part 3: Mastering CRUD Operations in Playwright API Testing
  4. 4Part 4: Authentication in Playwright API Testing (Bearer Token, JWT, API Key & Reusable Fixtures)
  5. 5Part 5: Building an Enterprise-Level Playwright API Automation Framework
  6. 6Part 6: API Models, Schema Validation & Test Data Management in Playwright
  7. 7Part 7: Custom Fixtures, Hooks, Logging & Parallel Execution in Playwright API Testing
  8. 8Part 8: Building a Production-Ready Playwright API Framework (Environment Management, CI/CD, Reporting & Best Practices)
  9. 9Part 9: Advanced Playwright API Testing Techniques for Enterprise Automation
  10. 10Part 10: Building a Complete Enterprise Playwright API Automation Framework (Final Part)
  11. 11Playwright Backend Testing Tutorial – REST API, GraphQL, WebSocket, Kafka, Database & Microservices

Recommended Next Articles