πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 67 of 100
API
Intermediate

How can you test APIs without a UI in Playwright?

The Answer

Playwright's `request` fixture provides a full `APIRequestContext` for sending HTTP requests directly without a browser. Use it in tests via `{ request }` fixture parameter.

Deep Dive Explanation

The `request` fixture in `@playwright/test` shares cookies with the browser context by default, making it perfect for authenticated API calls after a UI login. You can also create standalone `APIRequestContext` instances via `playwright.request.newContext()` for pure API tests.

example.spec.ts
import { test, expect } from '@playwright/test';

test('CRUD API tests', async ({ request }) => {
  // POST - Create
  const createRes = await request.post('/api/users', {
    data: { name: 'Alice', role: 'tester' },
  });
  expect(createRes.status()).toBe(201);
  const user = await createRes.json();

  // GET - Read
  const getRes = await request.get(`/api/users/${user.id}`);
  expect(getRes.ok()).toBeTruthy();
  expect((await getRes.json()).name).toBe('Alice');

  // PUT - Update
  await request.put(`/api/users/${user.id}`, {
    data: { name: 'Alice Updated' },
  });

  // DELETE
  const deleteRes = await request.delete(`/api/users/${user.id}`);
  expect(deleteRes.status()).toBe(204);
});