How to Test PUT API by Playwright

















What Is a PUT API? Complete Guide to Testing PUT API Using Playwright Java

In modern web applications and RESTful services, APIs are responsible for communication between client and server. While GET is used to retrieve data and POST is used to create data, the PUT API plays a crucial role when it comes to updating existing resources.

If you are an automation tester, backend developer, or preparing for API automation interviews, understanding PUT API and how to test it using Playwright Java is extremely important.

In this comprehensive guide, you will learn:

  • What is a PUT API?

  • How PUT API works in REST architecture

  • Key characteristics of PUT method

  • Difference between PUT and POST

  • Real-world use cases

  • How to test PUT API using Playwright Java

  • Step-by-step explanation with Java code

  • How to validate status code, response body, and headers

  • Error handling and negative testing scenarios

  • Best practices for PUT API testing

This article is written in a natural, human-like tone, fully SEO optimized and AdSense-friendly for blog publishing.


What Is a PUT API?

A PUT API is an HTTP request method used in RESTful web services to update or replace an existing resource on the server.

Unlike POST, which is typically used to create new resources, PUT is generally used when the client wants to update an existing record.

Simple Definition

PUT = Update or Replace existing resource


Example of PUT API

Imagine you have a user profile stored in a database:

{ "id": 2, "name": "Rahul", "job": "Tester" }

If you want to update this user’s job to “Software Developer”, you send a PUT request with the updated information.

After PUT request:

{ "id": 2, "name": "Rahul", "job": "Software Developer" }

The existing resource is updated.


Important Characteristics of PUT API

Understanding these characteristics is essential for interviews and real projects.

1. Idempotent Nature

PUT is idempotent.

This means:

Sending the same PUT request multiple times results in the same final state.

For example:
If you update a user’s job to "Developer" 10 times using the same request, the result remains the same.

This is different from POST, where multiple requests may create multiple resources.


2. Complete Resource Replacement

Traditionally, PUT requires sending the complete representation of the resource.

If partial updates are needed, PATCH method is used instead.

However, some APIs allow partial updates using PUT, depending on implementation.


Real-World Use Cases of PUT API

PUT APIs are commonly used in real-world applications such as:

  • Updating user profile details

  • Changing password

  • Updating product information in e-commerce

  • Editing blog posts

  • Updating employee records

  • Modifying order details

Any scenario where an existing record needs to be updated uses PUT API.


Difference Between PUT and POST API

Many beginners get confused between PUT and POST.

Here is a clear comparison:

FeaturePOSTPUT
PurposeCreate new resourceUpdate existing resource
IdempotentNoYes
Resource URLUsually collection endpointSpecific resource endpoint
Example/users/users/2

Example:

POST → Create new user
PUT → Update user with ID 2


Testing a PUT API with Playwright Java

Playwright is mainly known for UI automation, but it also provides powerful API testing capabilities.

Using Playwright Java, you can:

  • Send PUT requests

  • Send GET requests

  • Send POST requests

  • Send DELETE requests

  • Validate responses

  • Combine API and UI testing

And the best part? No browser launch is required for API testing.


Steps to Test a PUT API in Playwright Java

Let’s understand step-by-step how to test PUT API using Playwright in Java.


Example Scenario

We will update a user using this endpoint:

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

Method:

PUT


Sample JSON Request Body

{ "name": "Himanshu", "job": "Software Developer" }

This JSON will update the user’s name and job.


Step 1: Initialize Playwright and APIRequestContext

We need to create a request context to interact with APIs.


Step 2: Java Code to Test PUT API

Here is the complete working example:

import com.microsoft.playwright.*; import com.microsoft.playwright.options.*; import java.util.*; public class PutApiTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { APIRequest request = playwright.request(); APIRequestContext requestContext = request.newContext(new APIRequest.NewContextOptions() .setBaseURL("https://reqres.in/api")); // Prepare JSON request body Map<String, Object> data = new HashMap<>(); data.put("name", "Himanshu"); data.put("job", "Software Developer"); // Send PUT request APIResponse response = requestContext.put("/users/2", RequestOptions.create() .setHeader("Content-Type", "application/json") .setData(data) ); // Print status code System.out.println("Status Code: " + response.status()); // Print response body System.out.println("Response Body: " + response.text()); // Validate status code if (response.ok()) { System.out.println("PUT request successful."); } else { System.out.println("PUT request failed."); } } } }


Code Explanation (Step-by-Step)

Let’s break it down in simple language.


(a) Create APIRequestContext

APIRequestContext requestContext = request.newContext();

This creates a lightweight HTTP client for sending API requests.

We also set a base URL:

.setBaseURL("https://reqres.in/api")

So we don’t need to repeat the full URL.


(b) Prepare JSON Request Body

Map<String, Object> data = new HashMap<>();

We create a Map object and add key-value pairs to simulate JSON.


(c) Send PUT Request

requestContext.put("/users/2", options);

This sends a PUT request to update user with ID 2.

We also add:

  • Content-Type header

  • JSON payload


(d) Print Status Code

response.status();

Expected successful status code = 200 OK


(e) Print Response Body

response.text();

This prints the JSON response from server.


(f) Validate Status Code

response.ok();

Returns true if status code is between 200–299.


Expected Output

Status Code: 200 Response Body: { "name": "Himanshu", "job": "Software Developer", "updatedAt": "2025-07-28T12:13:45.012Z" } PUT request successful.

Status 200 means update was successful.

The response also contains updated timestamp.


How to Validate Specific Fields

You can validate response fields like this:

String name = response.json().get("name").toString(); System.out.println("Updated Name: " + name);

Or use JSONObject for better validation:

import org.json.JSONObject; JSONObject jsonObject = new JSONObject(response.text()); String job = jsonObject.getString("job"); System.out.println("Updated Job: " + job);


Negative Testing for PUT API

Professional API testing always includes negative scenarios.

1. Invalid Data

If you send invalid JSON:

Expected status → 400 Bad Request


2. Non-Existing Resource

If you update:

/users/9999

Expected status → 404 Not Found


3. Unauthorized Access

If authorization token is missing:

Expected status → 401 Unauthorized

Always test error scenarios.


Measuring Response Time

Performance testing is important.

Example:

long start = System.currentTimeMillis(); APIResponse response = requestContext.put("/users/2", options); long end = System.currentTimeMillis(); System.out.println("Response Time: " + (end - start) + " ms");

You can define threshold like:

  • Should respond within 2000 ms


Best Practices for PUT API Testing

Here are some professional tips:

1. Always Validate Status Code

Never assume API works correctly.

2. Validate Response Schema

Ensure response matches API documentation.

3. Test Idempotency

Send same PUT request multiple times and verify result remains same.

4. Use Assertions Framework

Integrate with TestNG or JUnit.

5. Store Base URL in Config File

Avoid hardcoding.


Combining API and UI Testing

Playwright allows powerful integration.

Example flow:

  1. Use PUT API to update user profile.

  2. Launch browser.

  3. Login using that user.

  4. Validate updated details appear in UI.

This improves automation efficiency.


Common Interview Questions on PUT API

  1. What is PUT API?

  2. What is idempotent method?

  3. Difference between PUT and PATCH?

  4. What status code indicates successful update?

  5. How to test PUT API using Playwright?

  6. How to handle negative scenarios?

Mastering these concepts will help in automation interviews.


Advantages of API Testing

  • Faster than UI testing

  • More stable

  • Detect backend issues early

  • Supports CI/CD pipelines

  • Useful in microservices architecture

Modern automation frameworks always include API testing.


Conclusion

A PUT API is used to update or replace an existing resource in RESTful services. It is idempotent and typically requires a complete representation of the resource in the request body.

Using Playwright Java, you can easily:

  • Send PUT requests

  • Add headers

  • Pass JSON payload

  • Validate status codes

  • Validate response body

  • Test performance

  • Combine API and UI automation

If you are learning automation testing or preparing for interviews, mastering PUT API testing with Playwright is highly recommended.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate DELETE API in Playwright
4. Automate Lombok API in Playwright
5. Test API by POJO Class in Playwright

No comments:

Post a Comment