How do I use Playwright to test API requests without opening a browser page?


To test API requests without opening a browser page using @playwright/test, you can utilize the APIRequestContext methods. These methods enable you to send HTTP(S) requests directly from Node.js, which is helpful for testing server APIs, setting up server-side state, or validating post-conditions.

First, configure authorization if required by setting up a token and baseURL using test.use():

import { test } from '@playwright/test';

  baseURL: 'https://ray.run/api',
  extraHTTPHeaders: {
    Authorization: 'Bearer YOUR_API_TOKEN',

Next, write tests using APIRequestContext to send requests to your API:

test('create a new project', async ({ api }) => {
  const response = await api.post('/projects', {
    json: { name: 'New Project' },

Establish preconditions, such as creating repositories or setting up specific data on your server:

test.beforeEach(async ({ api }) => {
  await api.post('/projects', { json: { name: 'Test Project' } });

If needed, send requests from UI tests:

test('create a project from the UI', async ({ page, api }) => {
  await page.goto('/projects/new');
  await page.fill('#project-name', 'New Project');
  await page.click('#create-project');
  const response = await api.get('/projects');
  expect(response.json()).toContainEqual({ name: 'New Project' });

Finally, validate post-conditions on your server after running actions in the browser or sending requests via APIRequestContext.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.