GET Request API testing in Playwright Python

Tutorial 16​​ ​​ GET Request API testing​​ in Playwright​​ Python​​ 

What you will Learn​​ in this​​ blog:

  • Automate API GET Request​​ (status code 200)

  • Automate API GET Request (status code 404)

  • Code snippets

Automate API GET Request​​ (status code 200)

Launch​​ https://reqres.in/​​ 

Click GET request shown against SINGLE USER.​​ 

Notice that the response is 200 (viz the GET request was successfully processed by the server)

Also notice the ‘Request’ uri that is shown above​​ viz​​ /api/users/2.

Let us see how to validate the response​​ status​​ in Playwright.

But before we look into that, open pycharm and go to File > Settings.

The below window comes up. Select ‘Python Interpreter’ as shown below

On the right hand side, you should see ‘requests’ package (as seen above). This is required for API testing.​​ 

If you don’t see ‘requests’ package, click + icon (see above snapshot). The below window would come up.

Search for ‘requests’ package and install it​​ 


After installing, you should see the ‘requests’ package in the earlier window that we had seen.

We have to import the ‘requests’ package

Now, when you type​​ requests.get​​ you would see one of the parameters as​​ url

Also, when you mouse hover​​ .get, you would see the entire documentation

Our url is composed of ‘base url’ plus ‘uri’

Also, if you again mouse hover ‘get’ method, we see that it returns us the ‘Response’ object

So​​ let us capture the o/p in a ‘resp’ variable

We can now invoke the ‘status_code’ method​​ 

Thus we have

Our entire code snippet looks like below

Save and execute

Notice​​ above that​​ the console shows​​ the​​ status code 200

Automate API GET Request (status code 404)

Let us now test below api having response code of 404

Below would be our script

Save and execute.

Notice the console showing status code 404. The code 200 is shown for the previous get request

This is how we test​​ Get​​ APIs.

Refer​​ https://playwright.dev/python/docs/api-testing​​ 

Code snippet​​ 

import​​ requests

from​​ playwright.sync_api​​ import​​ Playwright,​​ sync_playwright,​​ expect

def​​ run(playwright: Playwright) ->​​ None:

 ​​ ​​ ​​​​ 
#status code 200
 ​​ ​​ ​​​​ 
resp = requests.get("https://reqres.in/api/users/2")
 ​​ ​​ ​​​​ 
print(resp.status_code)

 ​​ ​​ ​​​​ 
# status code 404
 ​​ ​​ ​​​​ 
resp = requests.get("https://reqres.in/api/users/23")
 ​​ ​​ ​​​​ 
print(resp.status_code)

with​​ sync_playwright()​​ as​​ playwright:
 ​​ ​​ ​​​​ run(playwright)

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 10000 RS/149 USD
Attend All Live courses in just 10000 rs / $149 - offer ends 31st May 2024