Rayrun

How do I retrieve and display the headers of an API request using Playwright?

Answer

To log the headers of an API request using @playwright/test, you can utilize the allHeaders() method on the request object. This method returns a Promise that resolves to an object containing all the request HTTP headers, with lower-cased header names.

Here's an example in TypeScript:

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

test('log API request headers', async ({ page }) => {
  // Intercept network requests
  await page.route('https://ray.run/api/some-endpoint', async (route, request) => {
    // Get all headers
    const headers = await request.allHeaders();
    console.log(headers);

    // Continue the request
    route.continue();
  });

  // Navigate to the website
  await page.goto('https://ray.run');
});

If you need to log a specific header value, use the headerValue(name) method. It returns a Promise that resolves to the header value or null if the header is not found. The name argument is case insensitive.

Here's an example:

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

test('log specific API request header', async ({ page }) => {
  // Intercept network requests
  await page.route('https://ray.run/api/some-endpoint', async (route, request) => {
    // Get specific header value
    const headerValue = await request.headerValue('content-type');
    console.log(headerValue);

    // Continue the request
    route.continue();
  });

  // Navigate to the website
  await page.goto('https://ray.run');
});

With these methods, you can easily retrieve and log API request headers using @playwright/test.

Thank you!
Was this helpful?
Still have questions?

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

TwitterGitHubLinkedIn
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 [email protected].