Can you do API testing with Selenium? Not really. Selenium WebDriver automates browsers: it clicks, types and reads the page. It has no API for sending an HTTP request and checking a JSON response. For API testing in Java you use REST Assured (or Java's built-in HttpClient), and the most effective frameworks combine the two. This guide shows why, and four practical ways to use API calls and Selenium together.
Why Selenium Isn't an API Testing Tool
- It talks to a browser through the WebDriver protocol, not to your backend.
- Testing an API through the UI is slow and indirect: a failure could be the UI, the API or the network between them.
- Many API behaviours can't be reached from the UI at all: invalid payloads, missing auth headers, rate limits.
| Selenium | REST Assured | |
|---|---|---|
| Tests | What the user sees in the browser | The HTTP API directly |
| Speed per test | Seconds | Milliseconds |
| Best at | User journeys, rendering, cross-browser behaviour | Business rules, validation, status codes, contracts |
Pattern 1: Create Test Data Through the API
Instead of clicking through five screens to create a user before every UI test, create it with one API call. The UI test then only covers what it's actually about:
@BeforeMethod
public void createUser() {
userId = given()
.baseUri(apiUrl)
.contentType(ContentType.JSON)
.body(Map.of("name", "asha", "email", "asha+" + System.currentTimeMillis() + "@example.com", "password", "Secret#123"))
.when()
.post("/api/users")
.then()
.statusCode(201)
.extract().path("id");
}
@Test
public void userCanUpdateProfile() {
new LoginPage(driver).loginAs(email, "Secret#123")
.openProfile()
.changeCity("Pune");
// ...assert in the UI
}
Pattern 2: Log In Through the API and Reuse the Session
If the application uses a session cookie, get it from the login API and add it to the browser, skipping the login screen for every test that isn't about login:
String session = given().baseUri(apiUrl).contentType(ContentType.JSON)
.body(Map.of("username", "asha", "password", "Secret#123"))
.post("/api/login")
.then().statusCode(200)
.extract().cookie("SESSION");
driver.get(appUrl); // must be on the domain before adding a cookie
driver.manage().addCookie(new Cookie("SESSION", session));
driver.navigate().refresh(); // now logged in
Applications that keep a token in browser storage instead need a small JavaScript call to set it. Keep at least one real UI login test so the login page itself stays covered.
Pattern 3: Verify the Backend After a UI Action
new CheckoutPage(driver).placeOrder();
String orderId = new ConfirmationPage(driver).getOrderId();
given().baseUri(apiUrl).auth().oauth2(token)
.when().get("/api/orders/" + orderId)
.then()
.statusCode(200)
.body("status", equalTo("PLACED"))
.body("items.size()", equalTo(2));
The UI shows a confirmation; the API proves the order really exists with the right data.
Pattern 4: Check Links and Resources with an HTTP Client
Selenium finds the links; a plain HTTP client checks them. Java 11's built-in HttpClient is enough:
HttpClient http = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL).build();
for (WebElement a : driver.findElements(By.cssSelector("a[href^='http']"))) {
String url = a.getAttribute("href");
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
int code = http.send(req, HttpResponse.BodyHandlers.discarding()).statusCode();
if (code >= 400) System.out.println("Broken: " + url + " -> " + code);
}
What About Watching the Browser's API Calls?
Selenium 4 can listen to network traffic in Chromium browsers through the Chrome DevTools Protocol, and WebDriver BiDi is bringing this to other browsers. It's useful for checking which API calls a page makes, but the code depends on the browser version, so use it for specific checks rather than as your API testing approach. Playwright has this built in with page.route() and page.on('response').
Structuring a Combined Framework
- Keep API clients (REST Assured specifications, endpoints, POJOs) in their own package, used by both API tests and UI tests.
- Run API tests first in the pipeline: they're fast and catch most backend bugs before the slower UI suite starts.
- Share configuration (base URLs, credentials, environment) between the API and UI layers.
FAQs
Can Selenium be used for API testing?
No. Selenium automates browsers and has no built-in HTTP client for API requests. Use REST Assured, Postman or Java's HttpClient for APIs, and combine them with Selenium in the same framework.
Which tool is used with Selenium for API testing?
In Java, REST Assured is the most common choice. Postman and Newman are used for exploratory and collection-based API testing, and Karate is another option.
Why combine API and UI tests?
API calls make UI tests faster and more reliable by creating data and logging in without the UI, and they verify that what the UI shows is really stored in the backend.
Should API tests run before UI tests in CI?
Yes. API tests run in seconds and catch most backend defects, so running them first gives faster feedback and avoids running a long UI suite against a broken build.