How to Test a PUT API by Rest Assured

 

To test a PUT API using Rest Assured in Java, you'll follow these steps:

















What is PUT Request?

PUT request is used to update a resource on the server. For example, modifying a user's details.

The endpoint we'll use:
https://reqres.in/api/users/2 — This updates user with ID 2.


Steps to test PUT API using Rest Assured

  • Add dependencies (Maven or Gradle)
  • Set the Base URI
  • Create the JSON request body using JSONObject
  • Send PUT request using given()
  • Validate the response



Maven Dependency


<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230227</version>
    </dependency>
</dependencies>





Java Code using Rest Assured & JSONObject


import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.json.JSONObject;

import static io.restassured.RestAssured.given;

public class PutApiTest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Create JSON body using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "Software Engineer");

        // Step 3: Send PUT request and get the response
        Response response = given()
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .when()
                .put("/users/2")
                .then()
                .statusCode(200)  // Verifying status code
                .extract()
                .response();

        // Step 4: Print response
        System.out.println("Response Body:");
        System.out.println(response.getBody().asPrettyString());
    }
}




Code Explanation:


LinePurpose
RestAssured.baseURISets the base server endpoint
JSONObjectBuilds the request payload
given().header().body()Prepares the request with header & body
.put("/users/2")Sends PUT request to /users/2
.statusCode(200)Asserts response code is 200 OK
.response()Extracts full response
.asPrettyString()Converts raw response to formatted JSON string




Response:


{
    "name": "Himanshu",
    "job": "Software Engineer",
    "updatedAt": "2025-07-28T13:48:32.054Z"
}

How to Test a POST API by Rest Assured

 


To test a POST API using Rest Assured with a JSONObject in Java, follow these steps:




















Step-by-Step Implementation


1. Add Rest Assured Dependency

<dependencies>
    <!-- Rest Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Library -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
    </dependency>
</dependencies>




API to be tested: 

POST https://reqres.in/api/users





Sample request body:


{
  "name": "Himanshu",
  "job": "QA Engineer"
}




Expected response (201 Created):


{
  "name": "Himanshu",
  "job": "QA Engineer",
  "id": "123",
  "createdAt": "2025-07-28T..."
}





3. Java Code to Test POST API using JSONObject


import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.http.ContentType;
import org.json.JSONObject;

public class PostAPITest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Create Request Payload using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "QA Engineer");

        // Step 3: Make POST Request
        Response response = RestAssured
            .given()
                .contentType(ContentType.JSON)
                .body(requestBody.toString())
                .log().all()
            .when()
                .post("/users")
            .then()
                .log().all()
                .statusCode(201)
                .extract().response();

        // Step 4: Print Response Fields
        System.out.println("ID: " + response.jsonPath().getString("id"));
        System.out.println("Created At: " + response.jsonPath().getString("createdAt"));
    }
}




Code Explanation:


LinePurpose
RestAssured.baseURISets the base URL.
JSONObjectBuilds the JSON body using key-value pairs.
given().contentType().body()Prepares the request with headers and body.
post("/users")Sends POST request to the endpoint.
statusCode(201)Verifies the response status.
response.jsonPath()Extracts values from JSON response.




Sample Output:


Request method:	POST
Request URI:	https://reqres.in/api/users
Request body:
{
    "name": "Himanshu",
    "job": "QA Engineer"
}
Response Status Code: 201
Response body:
{
    "name": "Himanshu",
    "job": "QA Engineer",
    "id": "867",
    "createdAt": "2025-07-28T14:30:55.098Z"
}

Execute Playwright Script on Chrome Browser


When you execute a Playwright script on the Chrome browser, you are telling Playwright to launch tests on the real Chrome browser rather than the bundled Chromium. By default, Playwright uses Chromium, which is an open-source browser engine used by Chrome and Edge. However, if you specifically want to run on Google Chrome, Playwright allows you to configure it.


(1) Chromium vs Chrome

  • Chromium is the base project that Chrome is built on. Playwright ships with its own bundled version of Chromium.
  • Chrome is the actual browser installed on your system (with additional features, branding, and sometimes slight differences).

(2) How Playwright Handles Browsers

  • Playwright has built-in support for Chromium, Firefox, and WebKit.
  • For Chromium-based browsers, you can point Playwright to use either the bundled Chromium or your installed Chrome browser.
  • This is done by specifying the executable path of Chrome.

(3) Why Run Tests on Chrome?

  • Some projects or organizations require running automation scripts on the same browser version that end users use (i.e., Chrome instead of Playwright’s default Chromium).
  • This ensures compatibility testing with the actual Chrome build.
  • Running on Chrome may also be needed when browser policies, extensions, or enterprise configurations are involved.

(4) Process of Running on Chrome

  • Playwright launches Chrome using its Playwright API, but instead of the bundled Chromium, it points to the Chrome executable available on your machine.
  • Once launched, the script runs in the same way—navigating pages, finding locators, clicking elements, etc.—but all actions are now happening in the Google Chrome browser.

(5) Key Points

  • Execution on Chrome is nearly identical to execution on Chromium in terms of Playwright commands.
  • The main difference lies in specifying which browser binary to use.
  • After that, all locators, assertions, and interactions remain the same.


To execute a Playwright script in the Chrome browser using Java, you need to launch the browser in "Chrome" mode instead of the default "Chromium" (Playwright uses Chromium by default).

















Steps to Run Playwright in Chrome (Java):

  • Install Chrome on your system (Playwright will launch the installed Chrome browser).
  • Set the executable path of Chrome.
  • Use launchPersistentContext with Chrome executable path to launch Chrome.
  • Write and run your Playwright Java test.


Maven Dependency

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- or latest -->
</dependency>




Java Code Example: Launch in Chrome

import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class PlaywrightChromeExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {

      // Path to the installed Chrome browser executable
      String chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"; // Adjust this path

      BrowserType.LaunchOptions options = new BrowserType.LaunchOptions()
        .setExecutablePath(Paths.get(chromePath))
        .setHeadless(false); // Show the browser window

      Browser browser = playwright.chromium().launch(options);
      Page page = browser.newPage();
      page.navigate("https://example.com");

      System.out.println("Page title: " + page.title());

      browser.close();
    }
  }
}



Code explanation:

(a) Create Playwright object
(b) Create Browser object
(c) Then, create Page object
(d) Navigate to webpage by page.navigate()
(e) Print page title on console

Locators in Playwright

 

In Playwright, locators are used to identify and interact with elements on a web page. They are a powerful and reliable way to automate user actions like clicking buttons, entering text, and verifying elements.



















What Are Locators in Playwright?

Locators in Playwright abstract away selectors and provide a robust, high-level API to interact with page elements. Rather than manually writing CSS or XPath selectors, locators let you query elements in an expressive and stable way.


Playwright introduces a locator() API that makes element queries lazy and retries actions automatically, reducing flakiness.

Locator button = page.locator("text=Submit");
button.click();  // Retries until the button becomes actionable


Types of Locators in Playwright

Playwright supports several locator strategies:


1. Text Locator

Locates elements that contain specific visible text.

page.locator("text=Login");

2. CSS Selector

Uses standard CSS syntax to locate elements.

page.locator("button.submit");
page.locator("input[type='text']");

3. XPath Selector

Uses XPath expressions for complex DOM querying.

page.locator("xpath=//div[@id='container']");

4. ID Selector

Uses # to select elements by ID (CSS-based).

page.locator("#username");


5. Class Selector

Selects elements by class name.

page.locator(".btn-primary");


6. Attribute Selector

Selects elements by HTML attributes.

page.locator("[placeholder='Search']");
page.locator("[name='email']");


7. Role Locator

Uses ARIA roles for accessibility-based selection.

page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit"));


8. Label Locator

Finds input elements using <label> text.

page.getByLabel("Email");


9. Placeholder Locator

Selects input elements by their placeholder attribute.

page.getByPlaceholder("Search");


10. Alt Text Locator

Used for image elements with alt attributes.

page.getByAltText("Company Logo");


11. Title Locator

Used for elements with title attributes.

page.getByTitle("Help");


12. Test ID Locator

Used when elements have a custom data-testid attribute.

page.getByTestId("login-button");


13. Nth Element Locator

Use .nth(index) to select a specific item in a list of matching elements.

page.locator(".list-item").nth(2).click();  // clicks 3rd item


14. Chained Locators

You can chain locators to scope queries:

Locator form = page.locator("form#login");
form.locator("input[type='password']").fill("secret");


15. Locators with Filters

Use hasTexthas, or hasNotText filters for more control:

page.locator("div", new Locator.LocatorOptions().setHasText("Welcome"));

Here is a Java Playwright example demonstrating different types of locators:
  • Text Locator

  • CSS Selector

  • XPath Selector

  • ID Selector

  • Class Selector



1. Maven Dependency

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version>
</dependency>


Java Code (LocatorsDemo.java)

import com.microsoft.playwright.*;

public class LocatorsDemo {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to a demo site (You can replace it with your own test site)
            page.navigate("https://www.saucedemo.com/"); // demo site with multiple selectors

            // 1. Text Locator
            Locator loginButtonByText = page.getByText("Login");
            System.out.println("Text Locator Found: " + loginButtonByText.isVisible());

            // 2. CSS Selector
            Locator usernameByCss = page.locator("input[data-test='username']");
            usernameByCss.fill("standard_user");

            // 3. XPath Selector
            Locator passwordByXpath = page.locator("//input[@id='password']");
            passwordByXpath.fill("secret_sauce");

            // 4. ID Selector
            Locator loginBtnById = page.locator("#login-button");
            loginBtnById.click();

            // 5. Class Selector
            Locator titleByClass = page.locator(".title");
            System.out.println("Title Text: " + titleByClass.textContent());

            browser.close();
        }
    }
}

Output:

Text Locator Found: true
Title Text: Products

Here is Java code using Playwright to demonstrate:

  • Attribute Selector
  • Role Locator
  • Label Locator

import com.microsoft.playwright.*;

public class LocatorExamples {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to demo site
            page.navigate("https://opensource-demo.orangehrmlive.com/");

            // --- Attribute Selector Example ---
            Locator usernameByAttr = page.locator("input[name='username']");
            usernameByAttr.fill("Admin");

            // --- Role Locator Example ---
            // Here, button with role 'button' and name 'Login'
            Locator loginButton = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Login"));
            // We'll not click yet to keep page on login screen

            // --- Label Locator Example ---
            // Playwright tries to map <label> to its associated input
            Locator passwordByLabel = page.getByLabel("Password");
            passwordByLabel.fill("admin123");

            // Click the login button
            loginButton.click();

            // Wait for some indication of login success
            page.waitForURL("**/dashboard", new Page.WaitForURLOptions().setTimeout(5000));

            System.out.println("Login attempted");
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Placeholder Locator
  • Alt Text Locator
  • Title Locator


import com.microsoft.playwright.*;

public class LocatorExamples {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Navigate to a demo form page
            page.navigate("https://www.w3schools.com/html/html_forms.asp");

            // --- Placeholder Locator Example ---
            // (Assume placeholder="First name" exists on input field)
            Locator placeholderInput = page.getByPlaceholder("First name");
            placeholderInput.fill("John");

            // --- Alt Text Locator Example ---
            // Go to page with image alt tags
            page.navigate("https://www.w3schools.com/html/html_images.asp");

            // Locate image with alt text
            Locator altImage = page.getByAltText("Girl in a jacket");
            System.out.println("Is Alt Image Visible? " + altImage.isVisible());

            // --- Title Locator Example ---
            // Go to page with title attribute
            page.navigate("https://www.w3schools.com/html/html_tooltip.asp");

            // Locate element by its title attribute
            Locator titleElement = page.getByTitle("I'm a tooltip");
            System.out.println("Title element text: " + titleElement.textContent());

            browser.close();
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Test ID Locator

import com.microsoft.playwright.*;

public class TestIdLocatorExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      // Navigate to the sample website
      page.navigate("https://testing-playground.com/test-id");

      // Use Test ID Locator to find and click the Login button
      Locator loginButton = page.getByTestId("login-button");
      
      // Check visibility and click the button
      if (loginButton.isVisible()) {
        System.out.println("Login button is visible.");
        loginButton.click();
      } else {
        System.out.println("Login button not found.");
      }

      // Optional wait to see result
      page.waitForTimeout(3000);
      
      browser.close();
    }
  }
}


Here is Java code using Playwright to demonstrate:

  • Nth Element Locator

import com.microsoft.playwright.*;

public class NthElementLocatorExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Go to Google
            page.navigate("https://www.google.com");

            // Accept cookies if prompted
            Locator acceptButton = page.locator("button", new Page.LocatorOptions().setHasText("I agree"));
            if (acceptButton.count() > 0) {
                acceptButton.first().click();
            }

            // Enter search query and hit Enter
            page.locator("textarea[name='q']").fill("Playwright Java Tutorial");
            page.keyboard().press("Enter");

            // Wait for results to appear
            page.waitForSelector("h3");

            // Nth Element Locator - Click the 3rd search result (index starts from 0)
            Locator searchResults = page.locator("h3");
            searchResults.nth(2).click();

            // Optional: Wait to observe
            page.waitForTimeout(5000);

            browser.close();
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Chained Locators
  • Locators with Filters


import com.microsoft.playwright.*;

public class ChainedAndFilterLocators {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Open Swag Labs
            page.navigate("https://www.saucedemo.com/");

            // --- LOGIN ---
            page.locator("#user-name").fill("standard_user");
            page.locator("#password").fill("secret_sauce");
            page.locator("#login-button").click();

            // --- 1. CHAINED LOCATORS ---
            // Example: Find "Add to cart" button for "Sauce Labs Backpack"
            Locator inventoryItem = page.locator(".inventory_item").filter(new Locator.FilterOptions().setHasText("Sauce Labs Backpack"));
            Locator addToCartBtn = inventoryItem.locator("button");
            addToCartBtn.click();
            System.out.println("Added 'Sauce Labs Backpack' to cart using chained locator.");

            // --- 2. LOCATORS WITH FILTERS ---
            // (a) Locate the second inventory item using nth filter
            Locator secondItem = page.locator(".inventory_item").nth(1);
            System.out.println("Second Item Text: " + secondItem.locator(".inventory_item_name").textContent());

            // (b) Locate item with specific text using hasText filter
            Locator bikeLight = page.locator(".inventory_item").filter(
                new Locator.FilterOptions().setHasText("Bike Light")
            );
            bikeLight.locator("button").click();
            System.out.println("Added 'Bike Light' using filter(hasText).");

            // (c) Locate parent based on child (has filter)
            Locator itemWithPrice = page.locator(".inventory_item").filter(
                new Locator.FilterOptions().setHas(page.locator(".inventory_item_price", new Page.LocatorOptions().setHasText("$9.99")))
            );
            System.out.println("Item with price $9.99: " + itemWithPrice.locator(".inventory_item_name").textContent());

            // Keep browser open a bit
            page.waitForTimeout(4000);

            browser.close();
        }
    }
}


Suggested Posts:

1. Locators in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright