In this blog we will learn about POST Request (API Testing) using Playwright Java.
Topics that we will cover:
- Create a Post Request using playwright
- Learn how to parse json
- Sample Post Request (Register successful, 200)
- Sample Post Request (Login unsuccessful, 400)
- Source code (Post a new user and parse json)
- Source code (register successful)
- Source code (login unsuccessful)
Create a Post Request using playwright
In this section, we will explore the process of making an API request using Playwright through the POST method.
Go to https://reqres.in/
Please note that for the POST request, it is necessary to provide a body as part of the request, see below


Let us explore the process of creating a new user ID using Playwright Java.
To begin with, create an object of ‘APIRequestContext’

Using Map create body of POST request.
The data that we intend to send as part of the POST request will be included in the body

After that, we will obtain the text response and assign it to a string variable.
The post() method provided below takes in two parameters: the first parameter represents the uri where we intend to post our data, while the second parameter represents the data itself, which we have previously created

At the end, we will print the response in the console

Execute.
POST request passes. New user ‘id’ is created and printed

Learn how to parse json
json parser ‘gson’ can be used to parse json https://mvnrepository.com/artifact/com.google.code.gson/gson/2.10.1

Add dependency in xml

Save pom.xml
An instance of Gson is created and the response is passed as an argument to the fromJson() method

So let us parse id, name, job

Code so far is as below

Execute the code.
id, name, job gets printed

Sample Post Request (Register successful, 200)
Next, we will explore another example of a POST request.
It can be observed in the response below that a token is received


Modify the endpoint and post the data in the following manner. We have utilized the identical email id and password as mentioned above

Execute.
The generation of a token indicates that the user registration process was successful. Also the ‘id’ gets generated, see below

Sample Post Request (Login unsuccessful, 400)
Now, let's analyze the last scenario

Change uri plus other details

Execute.
The console prints error

You can try out POST requests in a similar fashion using playwright java.
Source code (Post a new user and parse json)