← Back to Discord Forum

Write API response to JSON File

I’m trying to intercept a network call and then write the response to aJSON file to compare for later

This thread is trying to answer question "How to intercept a network call and write the response to a JSON file, and how to handle multiple calls with the same name from a graphql url?"

5 replies

If you want to listen for a single response: https://playwright.dev/docs/api/class-page#page-wait-for-response

Something like this

const responsePromise = page.waitForResponse('https://example.com/api/backend/call/endpoint');
await // your action to trigger the network call
const response = await responsePromise;
const content = await response.text();
fs.writeFileSync('networkResponse.txt', content);

Thanks so much @hubspace , works great. Any idea on how to handle when the graphql url has multiple calls with the same name? For instance if I wanted the second matching one?

@Reuvy you will have to intercept all grapgql calls and check if the request includes the operation that you are looking for. Atleast that is how I am doing it

Besides .waitForResponse there's also a .on('response'), which will keep handling response events for the life time of the context/page, from the moment you set it up.

It will make the execution non-linear though. It's less suitable for 'waiting for some specific response'. That's what waitForResponse is for. But if you want to record all the responses and at the end of the test you want to know all the responses received, then .on('response') could be used.


Related Discord Threads

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.