Skip to contentPlayForge

How do I make an API request in a Playwright test?

Written by Jatin Thacker, Automation Architect · Updated

Ask for the built-in request fixture in your test and call request.get(), request.post() and the rest, with paths resolved against the baseURL in your config. Check the response with await expect(response).toBeOK() and read the body with await response.json().

This answer is one piece of Chapter 23: API Testing.

  • Introduction to APIRequestContext
  • Request & Response Handling
  • Combining API + UI Tests
  • Asserting on a Response
  • Practice and interview questions: API Testing with Playwright

Playwright's API testing page says the request fixture "respects configuration options like baseURL", so request.get('/api/orders') goes to your app's host without you repeating it. No browser opens: the request is sent from the test process.

toBeOK() checks the status is in the 200 to 299 range. After that, response.json() parses the body so you can assert on the fields that matter.

In the example, the practice app's /api/orders returns its seeded dataset of 47 orders, and the test checks the total and the first id, ORD-4100. On the practice app, the request fixture is answered from static snapshot files, so reads like this work but writes are rejected.

One trap on this app: inside the browser, the default mode answers API calls from a service worker that Playwright cannot see. Any test that watches the page's own requests, with page.route() or page.request, must pin ?mock=static.

request.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('the orders API returns the seeded dataset', async ({ request }) => { const response = await request.get('/api/orders'); await expect(response).toBeOK(); const body = await response.json(); expect(body.total).toBe(47); expect(body.items[0].id).toBe('ORD-4100'); });
Output
1 passed (1.1s)
Test yourself
What does await expect(response).toBeOK() check?

Practised in the full course: the drill API payload formatting.

See the chapter

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.