Playwright + TS · Lesson 29 of 36

0/36 done

Module 29: API Testing with Playwright

29. Direct HTTP API Automation & Hybrid API-to-UI Testing

20 minlesson

Try it yourself

Implement isSuccessfulHttpStatus:

  1. Accept status of type number.
  2. Return true if status is between 200 and 299 inclusive.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Pure API Testing with request Fixture

Playwright exposes request: APIRequestContext directly into tests:

typescript
import { test, expect } from "@playwright/test";

test("create user and verify response", async ({ request }) => {
  const response = await request.post("https://api.targetqa.com/users", {
    data: {
      name: "Alex QA",
      email: "alex@targetqa.com",
      role: "SDET",
    },
    headers: {
      Authorization: "Bearer test-api-key",
      "Content-Type": "application/json",
    },
  });

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

  const body = await response.json();
  expect(body.name).toBe("Alex QA");
  expect(body.id).toBeDefined();
});

The Power of Hybrid Testing (API Preconditions -> UI Verification)

Instead of clicking through 15 forms to create a project before testing a comment box:

  1. API: Create the project via request.post() in 100ms.
  2. UI: Navigate directly to /projects/${id} in the browser!
  3. Speedup: Tests run 10x faster and never fail due to setup flakiness.
typescript
test("hybrid workflow", async ({ request, page }) => {
  // 1. Create order via API
  const res = await request.post("/api/orders", { data: { item: "Book", qty: 1 } });
  const { orderId } = await res.json();

  // 2. Verify in UI
  await page.goto(`/orders/${orderId}`);
  await expect(page.getByRole("heading", { name: `Order #${orderId}` })).toBeVisible();
});

Key Takeaways & Walkthrough Summary

Playwright is not just for browsers; it also includes a blazing-fast HTTP API client. In this lesson, we will use the request fixture to validate REST APIs directly, and combine API calls with browser tests to seed test data in milliseconds before launching the UI. Let's master hybrid API and UI testing!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Does the request fixture inherit cookies from the browser context?

Yes! If you use 'page.request', it shares the exact same cookie store as the page. If you use the standalone 'request' fixture, it has its own isolated HTTP context.

Can Playwright replace Postman and Supertest?

Absolutely. Playwright's API testing features provide TypeScript typings, automatic cookie handling, and seamless integration with browser tests in the same test runner.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip