Tutorial 15 – Parse and Assert API Response Json Data using Playwright
What you will Learn in this blog:
Parse API Response json data
Assert json data
Code snippet
Parse API Response json Data
Let us now see ‘how to parse api response json data so that we can use assertions on them’.
The json data comes as part of api response.
Launch https://reqres.in/ and click GET API against SINGLE USER. We will get the json response data
Let us see how to get this json data using PW.
In line#6, we are getting the text response and converting (parsing) it to JSON and storing it in a variable
In line#7, we are printing the json response.
Save and execute.
Notice that we get the same json response data in the console and our test passes
Assert json data
Look at some of the notations below viz name of the json, json fields and the corresponding values
Next, let us say we want to assert the value of ‘id’ field.
This ‘id’ field belongs to ‘data’ json object, so we are calling this ‘data’ json object in line#8
If the json object name would have been ‘user’ (instead of ‘data’), than we would have written: respBody.user.id and so on…
We use ‘toBe()’ function (as shown above) to validate the expected value.
Save and run the test.
The test passes. This means, that the value of ‘id’ field is indeed 2
Let us change the expected value to be 7 (see line#8), save and run.
The test fails
Similarly, let us assert firstname and lastname (lines#9, 10)
To validate ‘email field, we can use ‘toBetruthy’ method. If this method returns true, that would mean that there is some value in the email field
Notice below that the test passes
If we use the ‘toBeFalsy()’ method, the test would fail
Code snippet (log json data)
import {test,expect} from '@playwright/test'
test("api get response", async ({ request }) => {
const response = await request.get('https://reqres.in/api/users/2')
const respBody = JSON.parse(await response.text())
console.log(respBody)
})
Code snippet (assert json)
import {test,expect} from '@playwright/test'
test("api get response", async ({ request }) => {
const response = await request.get('https://reqres.in/api/users/2')
const respBody = JSON.parse(await response.text())
expect(respBody.data.id).toBe(2)
expect(respBody.data.first_name).toBe('Janet')
expect(respBody.data.last_name).toBe('Weaver')
//console.log(respBody)
})
Code snippet (assert email)
import {test,expect} from '@playwright/test'
test("api get response", async ({ request }) => {
const response = await request.get('https://reqres.in/api/users/2')
const respBody = JSON.parse(await response.text())
expect(respBody.data.id).toBe(2)
expect(respBody.data.first_name).toBe('Janet')
expect(respBody.data.last_name).toBe('Weaver')
expect(respBody.data.email).toBeFalsy()
//console.log(respBody)
})
Thank you for reading!