Rayrun

How do I use Playwright to intercept and record API responses?

Answer

Intercepting API Calls with Playwright

You can definitely intercept and record API responses with Playwright. It's a powerful tool that provides various methods to handle network requests and responses.

Setting Up the Route

First, use the page.route() method to set up a route for the API endpoint you want to monitor. Here's how:

await page.route('**/api/fetch_data', route => {
  route.fulfill({ status: 200, body: testData });
});

In this code, any requests matching '**/api/fetch_data' will be intercepted.

Triggering the API Call

Next, perform actions on your web page that trigger the API call. For example:

await page.goto('https://ray.run');
await page.getByText('Update').click();

Waiting for the Response

Then, wait for the intercepted response using page.waitForResponse(). Like this:

const response = await page.waitForResponse('**/api/fetch_data');

Accessing the Response

Finally, access the response's properties. You can do something like:

console.log(response.status());
console.log(await response.json());

And that's it! You've just intercepted and recorded an API response. Remember, this is just one way to do it. Playwright offers other methods for handling network requests, so feel free to explore!

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

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 luc@ray.run.