How do I extract the response body from an API request using Playwright?


To extract the body from an API response in @playwright/test, use the body() method from the APIResponse class. This method returns a Promise that resolves to a Buffer containing the response body. You can await this Promise to get the actual content. Here's an example:

const responseBody = await apiResponse.body();

Remember that calling body() consumes the response body, so call it only once per response object.

If you need to parse JSON responses, use the json() method on the APIResponse instance:

const jsonResponse = await apiResponse.json();

Keep in mind that calling json() on non-JSON or invalid JSON data will throw an error. Handle these errors accordingly.

Alternatively, you can use Playwright's request interception feature with Node.js' built-in HTTP/HTTPS modules or third-party libraries like Axios or Request to access the response contents directly within your test code.

Thank you!
Was this helpful?
Still have questions?

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

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.