Rayrun
← Back to Discord Forum

Intercepting API responses

junior_grossiposted in #help-playwright
Open in Discord
junior_grossi
junior_grossi

Hi, I'm basically testing APIs using the APIRequestContext. On every response I'd like to log the test name (available on testInfo) and a correlation ID I receive as a response header. I was thinking on overriding the request using fixtures and then listen to the response event, but there's no way to listen to when a response is received in API (like we have for Page -> page.on('response'). Any ideas?

This thread is trying to answer question "How can I intercept API responses using APIRequestContext and log test names and correlation IDs?"

7 replies

Use the same approach - fixtures and define page.on there.

However, it's just a listener and does not stop any execution so I would recomment try-catching the response.

junior_grossi
junior_grossi

thanks @skorp32 for your reply. I think the challenge is how to define page.on in there there? the implementation of those event listeners is not very straightforward it seems. maybe PW has an easier way to achieve that result?

Are you using apiRequest.newContext() or page.request / browserContext.request ? You won't have any events without a browser/page to have the events. Ad-hoc requests would need to be handled manually

someFixture: [
    async ({ page }, use) => {
      page.on('response', async response => {
        // do stuff with response
      })

      await use()
    },
    { auto: true },
  ],

that's an automatic one, but you can do same thing with simpel fixture as well

and as I mentioned, try-catch response body because on navigation (and perhaps other stuff) response bodies are dumped so you might get an error

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