How to Test GET API in Playwright
















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

In modern software development, APIs (Application Programming Interfaces) play a crucial role in enabling communication between different systems. Whether you are building a web application, mobile app, or enterprise software, APIs help exchange data seamlessly.

One of the most commonly used HTTP methods in API communication is the GET API.

In this detailed guide, you will learn:

  • What is a GET API?

  • How GET API works

  • Real-world examples of GET APIs

  • How to test a GET API using Playwright Java

  • Maven dependency setup

  • Java code example with explanation

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

  • Why Playwright is powerful for API testing

This article is fully SEO optimized, beginner-friendly, and written in a human-like format for better readability and AdSense compliance.


What Is a GET API?

A GET API is an HTTP request method used to retrieve data from a server. It is designed to fetch information without modifying or updating any data on the server.

In simple terms:

GET = Fetch data only
It does not insert, update, or delete anything.

Key Characteristics of GET API

  • Used to retrieve data

  • Does not change server data

  • Safe and idempotent

  • Can be cached

  • Parameters are usually sent in the URL

Example of GET API

If you open this URL in your browser:

https://jsonplaceholder.typicode.com/users

The server responds with user data in JSON format.

This is a simple example of a GET API call where data is retrieved but not modified.


Real-World Examples of GET API

Here are some common real-world examples:

  • Getting user details by ID

  • Fetching product listings in an e-commerce app

  • Retrieving weather data

  • Getting bank transaction history

  • Fetching blog posts from a content platform

Almost every modern application uses GET APIs extensively.


What Does GET API Testing Mean?

When we test a GET API, we verify that:

  1. The API returns the correct status code (e.g., 200 OK)

  2. The response body contains expected data

  3. The response time is within acceptable limits

  4. The headers are correct (e.g., Content-Type: application/json)

  5. The data structure matches the API contract

API testing ensures that backend services are working correctly before they are integrated with frontend UI.


How to Test GET API Using Playwright Java

Many people think Playwright is only for UI automation. However, Playwright also provides powerful API testing capabilities.

With Playwright, you can:

  • Send GET requests

  • Send POST requests

  • Send PUT requests

  • Send DELETE requests

  • Validate response data

  • Test performance

And all this without opening a browser.


Why Use Playwright for API Testing?

Here are some strong reasons:

1. Unified Automation Framework

You can test both UI and API in the same project. No need for separate tools.

2. Faster Execution

API tests are much faster than UI tests because no browser is launched.

3. Pre-Test Data Setup

You can create or fetch test data using API before running UI automation.

Example scenario:

  • Use API to create a user

  • Use UI test to log in with that user

  • Validate UI displays correct data

4. Backend Validation

You can compare UI data with API data to ensure consistency.


Steps to Test a GET API Using Playwright Java

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

We will test this public API:

https://jsonplaceholder.typicode.com/posts/1


Step 1: Add Maven Dependency

First, add Playwright dependency in your pom.xml.

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

Always use the latest stable version available.


Step 2: Java Code to Test GET API

Here is a complete example:

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 response status System.out.println("Status: " + response.status()); System.out.println("Status Text: " + response.statusText()); // Step 5: Get response body String responseBody = response.text(); System.out.println("Response Body:\n" + responseBody); // Optional validation if (response.ok()) { System.out.println("API responded successfully."); } else { System.out.println("API test failed."); } // Close context requestContext.dispose(); } } }


Code Explanation (Step-by-Step)

Let’s break it down for better understanding.

(a) Initialize Playwright

Playwright playwright = Playwright.create();

This starts the Playwright engine.


(b) Create APIRequestContext

APIRequest request = playwright.request(); APIRequestContext requestContext = request.newContext();

This context allows you to send HTTP requests without opening a browser.


(c) Send GET Request

APIResponse response = requestContext.get("API_URL");

This sends a GET request to the specified endpoint.


(d) Validate Response Status

response.status();

Expected status for success = 200


(e) Validate Response Body

response.text();

Extracts JSON response as a string.


(f) Optional Assertion

response.ok();

Returns true if status code is between 200–299.


(g) Close API Context

requestContext.dispose();

Closes request context to avoid memory leaks.


Expected Output

When executed successfully, output will look like:

Status: 200 Status Text: OK Response Body: { "userId": 1, "id": 1, "title": "...", "body": "..." } API responded successfully.

Status code 200 means the API returned a successful response.


How to Validate Specific JSON Fields

To validate response fields, you can use JSONObject.

Example:

import org.json.JSONObject; import org.testng.Assert; JSONObject jsonObject = new JSONObject(response.text()); int id = jsonObject.getInt("id"); Assert.assertEquals(id, 1); System.out.println("JSON fields validated.");

This ensures:

  • Correct ID is returned

  • Data matches expected value

  • API contract is maintained


How to Validate Response Headers

Headers are important in API testing.

Example:

String contentType = response.headers().get("content-type"); System.out.println("Content-Type: " + contentType);

Expected:

application/json


How to Validate Response Time

Performance is critical in real applications.

You can measure response time like this:

long startTime = System.currentTimeMillis(); APIResponse response = requestContext.get("API_URL"); long endTime = System.currentTimeMillis(); System.out.println("Response Time: " + (endTime - startTime) + " ms");

You can set threshold like:

  • API should respond within 2000 ms


Best Practices for GET API Testing

Here are some professional tips:

1. Always Validate Status Code

Do not assume API is successful.

2. Validate Response Schema

Ensure response structure matches API documentation.

3. Validate Edge Cases

Test:

  • Invalid ID

  • Non-existing resource

  • Unauthorized access

4. Use Assertions

Integrate with TestNG or JUnit for structured testing.

5. Avoid Hardcoding

Store base URL and endpoints in configuration files.


Difference Between GET and Other HTTP Methods

MethodPurpose
GETRetrieve data
POSTCreate data
PUTUpdate data
DELETERemove data

GET is read-only and should not modify server state.


Advantages of API Testing Over UI Testing

  • Faster execution

  • More stable

  • No dependency on UI changes

  • Early bug detection

  • Backend validation before UI integration

In professional automation projects, API testing is always recommended alongside UI automation.


When Should You Use GET API Testing?

You should use GET API testing when:

  • Verifying data retrieval

  • Validating backend business logic

  • Checking integration between services

  • Testing microservices architecture

  • Validating database data exposure


Common Interview Questions on GET API Testing

  1. What is GET API?

  2. What is idempotent HTTP method?

  3. How do you validate API response?

  4. How do you test API performance?

  5. Difference between GET and POST?

  6. How to test API using Playwright?

If you are preparing for automation interviews (especially in Java-based frameworks), mastering Playwright API testing is highly beneficial.


Conclusion

A GET API is one of the most fundamental and widely used HTTP methods for retrieving data from a server. Testing GET APIs ensures that backend services return correct, reliable, and performant responses.

Using Playwright Java, you can:

  • Send GET requests easily

  • Validate status codes

  • Validate JSON response

  • Check headers

  • Measure performance

  • Integrate API tests with UI automation

Playwright provides a powerful and lightweight approach to API automation testing, making it a great choice for modern QA engineers and automation testers.


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