Rayrun

How do I log API requests in Playwright/test?

Answer

Sure, you can log API requests in Playwright. It's a great way to see what's being sent to your API endpoint.

Intercepting Network Requests

Playwright lets you intercept and modify network traffic. You can use the page.route() method to handle network requests made by a page.

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

test('log API request', async ({ page }) => {
  await page.route('https://ray.run/api/endpoint', (route, request) => {
    console.log(request.url());
    route.continue();
  });
  await page.goto('https://ray.run');
});

Logging Request Details

Inside the callback function of page.route(), you can log the request details. For instance, you can print out the URL of each request with console.log(route.request().url()).

console.log(route.request().url());

Accessing More Request Details

If you need more details about the request, like its headers and payload data, you can use route.request().headers() and route.request().postData().

console.log(route.request().headers());
console.log(route.request().postData());

By logging these details, you'll see exactly what's being sent to your API endpoint. It's a handy tool for debugging or verifying your application is sending the correct data.

For more on API testing with Playwright, check out this blog post.

References

Thank you!
Was this helpful?
Still have questions?

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

Related Discord Threads

Related Questions

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].