How to Test GET API in Playwright

    

To test a GET API using Playwright in Java, you can use Playwright’s built-in APIRequestContext to send HTTP requests. This is useful for API testing in addition to browser automation.
















Steps to Test a GET API using Playwright Java:

  • Initialize Playwright and APIRequestContext
  • Send GET request to the API endpoint
  • Validate the response: Status code, body content, headers, etc.
  • Close Playwright

Example: Test GET API in Playwright Java

Let’s test a public API like:
https://jsonplaceholder.typicode.com/posts/1


Maven Dependency

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




Java Code to Test GET API
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;

public class GetApiTest {
    public static void main(String[] args) {
        // Step 1: Initialize Playwright
        try (Playwright playwright = Playwright.create()) {
            // Step 2: Create APIRequest context
            APIRequest request = playwright.request();
            APIRequestContext requestContext = request.newContext();

            // Step 3: Send GET request
            APIResponse response = requestContext.get("https://jsonplaceholder.typicode.com/posts/1");

            // Step 4: Validate the response
            System.out.println("Status: " + response.status()); // 200 expected
            System.out.println("Status Text: " + response.statusText());

            // Step 5: Validate body content
            String responseBody = response.text();
            System.out.println("Response Body: \n" + responseBody);

            // Optional: Assert status code and content
            if (response.ok()) {
                System.out.println("API responded successfully.");
            } else {
                System.out.println("API test failed.");
            }

            // Close API request context
            requestContext.dispose();
        }
    }
}




Expected Output:
Status: 200
Status Text: OK
Response Body:
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "..."
}
API responded successfully.



You Can Also Validate Specific Fields:
import org.json.JSONObject;

JSONObject json = new JSONObject(response.text());
assert json.getInt("id") == 1;
assert json.getInt("userId") == 1;
System.out.println("JSON fields validated.");


Suggested Posts:

1. Automate POST API in Playwright
2. Automate PUT 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