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:
node -v
npm -vIf 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:
npm init playwright@latestDuring installation, Playwright will ask several questions. Choose the following options:
TypeScript
tests folder
GitHub Actions (Optional)
Install Playwright BrowsersOnce the installation completes, your project structure will look similar to this:
playwright-api-framework/
│
├── node_modules/
├── tests/
├── playwright.config.ts
├── package.json
├── tsconfig.json
└── package-lock.jsonThis 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.
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:
await request.get("https://jsonplaceholder.typicode.com/posts/1");With Base URL:
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:
tests/get-post.spec.tsAdd the following code:
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.
async ({ request })This fixture creates an APIRequestContext for your test.
Step 2
Send a GET request.
const response = await request.get("/posts/1");Playwright automatically combines this endpoint with the configured Base URL. The actual request becomes:
https://jsonplaceholder.typicode.com/posts/1Step 3
Validate the Status Code.
expect(response.status()).toBe(200);This confirms the request completed successfully.
Step 4
Convert the response into JSON.
const body = await response.json();Now the API response becomes a JavaScript object that can easily be validated.
Step 5
Verify the response data.
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:
npx playwright testTo run a specific file:
npx playwright test tests/get-post.spec.tsTo view the HTML report:
npx playwright show-reportThe 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:
response.status()
response.ok()
response.headers()
response.json()
response.text()
response.body()Example:
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?"
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.
Get Playwright tutorials in your inbox
Weekly tips, real-world examples, and framework patterns – no spam, unsubscribe anytime.
Playwright Framework Series
View all →- 1Getting Started with Playwright: Installation, Setup, and Your First Test
- 2Playwright Locators: The Complete Guide with Real-World Examples
- 3Playwright Actions: Complete Guide to Click, Fill, Hover, Keyboard, Mouse & File Upload
- 4Playwright Assertions: The Complete Guide with Real-World Examples
- 5Playwright Auto Waiting: The Complete Guide with Real-World Examples
- 6Playwright Fixtures: The Complete Guide with Real-World Examples
- 7Playwright Browser Context & Multiple Tabs: The Complete Guide with Real-World Examples
- 8Playwright Authentication & Session Management: Complete Guide with Enterprise Examples
- 9Playwright Network Interception & API Mocking: Complete Guide with Real-World Examples
- 10Playwright Page Object Model (POM): The Complete Guide with Enterprise Examples
- 11Page Object Model with Playwright: A Practical Guide
- 12How to Build a Robust Professional Playwright Framework from Scratch (Step-by-Step)
- 13Building an Enterprise Playwright Framework from Scratch
API Testing Series
View all →- 1Playwright API Testing: The Complete Guide with Real-World Examples
- 2Part 1 : Playwright API Testing Tutorial: Build Enterprise-Level API Automation Framework
- 3Part 2: Playwright API Testing Tutorial: Setting Up Project & Sending Your First API Request
- 4Part 3: Mastering CRUD Operations in Playwright API Testing
- 5Part 4: Authentication in Playwright API Testing (Bearer Token, JWT, API Key & Reusable Fixtures)
- 6Part 5: Building an Enterprise-Level Playwright API Automation Framework
- 7Part 6: API Models, Schema Validation & Test Data Management in Playwright
- 8Part 7: Custom Fixtures, Hooks, Logging & Parallel Execution in Playwright API Testing
- 9Part 8: Building a Production-Ready Playwright API Framework (Environment Management, CI/CD, Reporting & Best Practices)
- 10Part 9: Advanced Playwright API Testing Techniques for Enterprise Automation
- 11Part 10: Building a Complete Enterprise Playwright API Automation Framework (Final Part)
- 12API Testing with Playwright: Request Context, Auth, and Assertions