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();
console.log(jsonResponse);
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.
If you still have questions, please ask a question and I will try to answer it.
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].