API-Assisted UI Tests: Faster, Stabler Selenium
Speed up Selenium suites by logging in via API, injecting cookies and tokens, seeding test data over HTTP, and checking the UI against the API responses.
A typical end-to-end test spends most of its time on things it is not testing. To check that a user can cancel an order, it logs in through the login form, creates an order through four checkout pages, navigates to order history, and only then clicks “Cancel”. If the login page has a bug, the cancel test fails too. If checkout is slow, every test that needs an order is slow.
API-assisted UI testing fixes this: do setup and teardown through the application’s HTTP API, and use the browser only for the behaviour under test. It is the single biggest speed and stability improvement available to most mature Selenium suites, routinely cutting test times by 50 to 80 percent.
The Hybrid Test Shape
Arrange (API) create user, log in, seed an order ~200 msAct (UI) open order page, click Cancel, confirm ~3 sAssert (UI) status badge shows "Cancelled"Assert (API) GET /orders/{id} returns status=CANCELLED ~50 msCleanup (API) delete user ~50 msCompare with an all-UI version that logs in through the form (3 to 5 s) and creates an order through checkout (15 to 30 s) before doing anything useful. Multiply by every test in the suite.
The principle: each behaviour is tested through the UI exactly once. The login form has its own tests. The checkout flow has its own tests. Everything else gets there by API.
Logging In via API
Authentication is the setup every test needs, so it is the first thing to move. How you inject the session depends on how the application stores it.
| App stores auth in | Inject by |
|---|---|
| Session cookie (server-rendered apps, most frameworks) | addCookie after navigating to the domain |
Token in localStorage or sessionStorage (many SPAs) | executeScript to set the item, then reload |
Token in memory only, refreshed from an HttpOnly refresh cookie | Inject the refresh cookie; the app bootstraps itself |
| SSO / OAuth via a third-party identity provider | Test-only token endpoint, or a long-lived session cookie created by a setup job |
Cookie-based sessions
Two rules apply to addCookie: the browser must already be on a page of the cookie’s domain (WebDriver will not set cookies for a domain you are not on), and the cookie attributes must be compatible with that page. The cheapest page to visit first is a lightweight static URL on the same domain, such as /favicon.ico or a /health endpoint, rather than the full home page.
import java.net.http.*;import java.net.URI;
HttpClient http = HttpClient.newHttpClient();HttpRequest login = HttpRequest.newBuilder(URI.create("https://app.example.com/api/login")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( "{\"email\":\"alice@example.com\",\"password\":\"" + System.getenv("TEST_PASSWORD") + "\"}")) .build();HttpResponse<String> response = http.send(login, HttpResponse.BodyHandlers.ofString());assertEquals(200, response.statusCode());
// Parse "session=abc123; Path=/; HttpOnly; Secure; SameSite=Lax"String setCookie = response.headers().firstValue("Set-Cookie").orElseThrow();String[] nameValue = setCookie.split(";", 2)[0].split("=", 2);
driver.get("https://app.example.com/favicon.ico"); // be on the domain firstdriver.manage().addCookie(new Cookie.Builder(nameValue[0], nameValue[1]) .path("/").isHttpOnly(true).isSecure(true).sameSite("Lax").build());
driver.get("https://app.example.com/orders"); // already logged inimport osimport requests
session = requests.Session()resp = session.post("https://app.example.com/api/login", json={"email": "alice@example.com", "password": os.environ["TEST_PASSWORD"]}, timeout=10)resp.raise_for_status()
driver.get("https://app.example.com/favicon.ico") # be on the domain firstfor c in session.cookies: driver.add_cookie({ "name": c.name, "value": c.value, "path": c.path or "/", "secure": c.secure, "httpOnly": True, "sameSite": "Lax", })
driver.get("https://app.example.com/orders") # already logged inconst res = await fetch('https://app.example.com/api/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ email: 'alice@example.com', password: process.env.TEST_PASSWORD }),});assert.strictEqual(res.status, 200);
// Node 20+: getSetCookie() returns each Set-Cookie header separatelyconst [name, value] = res.headers.getSetCookie()[0].split(';')[0].split(/=(.*)/s);
await driver.get('https://app.example.com/favicon.ico'); // be on the domain firstawait driver.manage().addCookie({name, value, path: '/', httpOnly: true, secure: true, sameSite: 'Lax',});
await driver.get('https://app.example.com/orders'); // already logged inusing System.Net;using System.Net.Http.Json;
var cookies = new CookieContainer();using var http = new HttpClient(new HttpClientHandler { CookieContainer = cookies });
var resp = await http.PostAsJsonAsync("https://app.example.com/api/login", new { email = "alice@example.com", password = Environment.GetEnvironmentVariable("TEST_PASSWORD") });resp.EnsureSuccessStatusCode();
driver.Navigate().GoToUrl("https://app.example.com/favicon.ico"); // be on the domain firstforeach (System.Net.Cookie c in cookies.GetCookies(new Uri("https://app.example.com"))){ driver.Manage().Cookies.AddCookie(new OpenQA.Selenium.Cookie( c.Name, c.Value, null, "/", null, secure: true, isHttpOnly: true, sameSite: "Lax"));}
driver.Navigate().GoToUrl("https://app.example.com/orders"); // already logged inNote the domain is left unset in the injected cookie. A cookie without an explicit domain becomes a host-only cookie for the current page’s host, which is what the server’s own Set-Cookie usually does. Setting domain explicitly to a different host is a common cause of invalid cookie domain errors. For more on cookie attributes and the classic pitfalls, see Cookies and Storage.
Token-based SPAs
Single-page apps often keep an access token in localStorage. Set it with JavaScript on any page of the origin, then load the app.
String token = apiClient.login("alice@example.com", System.getenv("TEST_PASSWORD")); // returns access token
driver.get("https://app.example.com/favicon.ico");((JavascriptExecutor) driver).executeScript( "localStorage.setItem('auth', JSON.stringify({ accessToken: arguments[0] }));", token);
driver.get("https://app.example.com/dashboard");new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-testid='user-menu']")));token = api_client.login("alice@example.com", os.environ["TEST_PASSWORD"])
driver.get("https://app.example.com/favicon.ico")driver.execute_script( "localStorage.setItem('auth', JSON.stringify({ accessToken: arguments[0] }));", token)
driver.get("https://app.example.com/dashboard")WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-testid='user-menu']")))const token = await apiClient.login('alice@example.com', process.env.TEST_PASSWORD);
await driver.get('https://app.example.com/favicon.ico');await driver.executeScript("localStorage.setItem('auth', JSON.stringify({ accessToken: arguments[0] }));", token);
await driver.get('https://app.example.com/dashboard');await driver.wait(until.elementLocated(By.css("[data-testid='user-menu']")), 10000);var token = await apiClient.LoginAsync("alice@example.com", Environment.GetEnvironmentVariable("TEST_PASSWORD"));
driver.Navigate().GoToUrl("https://app.example.com/favicon.ico");((IJavaScriptExecutor)driver).ExecuteScript( "localStorage.setItem('auth', JSON.stringify({ accessToken: arguments[0] }));", token);
driver.Navigate().GoToUrl("https://app.example.com/dashboard");new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => d.FindElement(By.CssSelector("[data-testid='user-menu']")).Displayed);The storage key and value shape are application-specific. Find them by logging in manually and inspecting Application > Local Storage in DevTools, or ask the front-end team; ideally they expose a documented test hook so tests do not break when the shape changes.
Tip: If a favicon or health URL triggers a redirect to a login page on another domain, any static asset on the app’s origin works: a robots.txt, a 404 page, or a tiny
/test-blank.htmlthe team adds for exactly this purpose.
Caching the session across tests
Even an API login costs a round trip and creates a server session. For read-only tests, log in once per worker and reuse the cookie or token for every test that worker runs. Do not share sessions for tests that change user settings or rely on per-session state; give those their own user.
Seeding Test Data via API
The second big win: create the data a test needs directly, so the test does not depend on other tests, on a shared fixture database, or on slow UI flows.
@Testvoid userCanCancelPendingOrder() throws Exception { // Arrange via API String orderJson = """ {"items":[{"sku":"TSHIRT-M-BLUE","qty":2}],"shippingMethod":"standard"}"""; HttpResponse<String> created = http.send( HttpRequest.newBuilder(URI.create(API + "/orders")) .header("Authorization", "Bearer " + token) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(orderJson)).build(), HttpResponse.BodyHandlers.ofString()); assertEquals(201, created.statusCode()); String orderId = new ObjectMapper().readTree(created.body()).get("id").asText();
// Act via UI OrderPage page = new OrderPage(driver).open(orderId); page.cancel();
// Assert in UI assertEquals("Cancelled", page.statusBadgeText());}def test_user_can_cancel_pending_order(driver, api): # Arrange via API resp = api.post("/orders", json={ "items": [{"sku": "TSHIRT-M-BLUE", "qty": 2}], "shippingMethod": "standard"}) assert resp.status_code == 201 order_id = resp.json()["id"]
# Act via UI page = OrderPage(driver).open(order_id) page.cancel()
# Assert in UI assert page.status_badge_text() == "Cancelled"it('user can cancel a pending order', async () => {// Arrange via APIconst res = await fetch(`${API}/orders`, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ items: [{ sku: 'TSHIRT-M-BLUE', qty: 2 }], shippingMethod: 'standard' }),});assert.strictEqual(res.status, 201);const { id: orderId } = await res.json();
// Act via UIconst page = await new OrderPage(driver).open(orderId);await page.cancel();
// Assert in UIassert.strictEqual(await page.statusBadgeText(), 'Cancelled');});[Test]public async Task UserCanCancelPendingOrder(){ // Arrange via API (HttpClient with BaseAddress and bearer token configured in SetUp) var resp = await api.PostAsJsonAsync("orders", new { items = new[] { new { sku = "TSHIRT-M-BLUE", qty = 2 } }, shippingMethod = "standard", }); Assert.That((int)resp.StatusCode, Is.EqualTo(201)); var orderId = (await resp.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetString();
// Act via UI var page = new OrderPage(driver).Open(orderId); page.Cancel();
// Assert in UI Assert.That(page.StatusBadgeText(), Is.EqualTo("Cancelled"));}Guidelines for seeded data:
- Unique per test. Generate unique emails, names and SKUs (a UUID suffix or the test name plus a timestamp). Tests running in parallel then never collide, which is essential once you run in parallel.
- Clean up in teardown, through the API, and tolerate cleanup failures (log them, do not fail the test). Better still, create data under a per-run tenant or tag that a nightly job deletes in bulk.
- Use the public API where it exists, so seeding exercises the same validation real clients hit. Where it does not (setting an order to “shipped”, back-dating a subscription), ask for test-only endpoints guarded by environment and authentication, rather than writing directly to the database from tests.
- Wrap it in a client class. Tests should call
api.createOrder(items), not build HTTP requests inline. The examples above inline HTTP for clarity; production code puts it behind a small typed client, just as page objects hide locators.
Verifying the UI Against the API
The reverse direction is just as useful: use the API as the oracle for what the UI should show, or to confirm that a UI action had the intended effect on the backend.
// After cancelling in the UI, confirm the backend agreesJsonNode order = apiClient.getOrder(orderId);assertEquals("CANCELLED", order.get("status").asText());assertNotNull(order.get("cancelledAt"));
// UI table shows the same totals as the APIJsonNode summary = apiClient.getAccountSummary();assertEquals(summary.get("openOrders").asInt(), Integer.parseInt(driver.findElement(By.cssSelector("[data-testid='open-orders-count']")).getText()));order = api.get(f"/orders/{order_id}").json()assert order["status"] == "CANCELLED"assert order["cancelledAt"] is not None
summary = api.get("/account/summary").json()shown = driver.find_element(By.CSS_SELECTOR, "[data-testid='open-orders-count']").textassert int(shown) == summary["openOrders"]const order = await (await apiGet(`/orders/${orderId}`)).json();assert.strictEqual(order.status, 'CANCELLED');assert.ok(order.cancelledAt);
const summary = await (await apiGet('/account/summary')).json();const shown = await driver.findElement(By.css("[data-testid='open-orders-count']")).getText();assert.strictEqual(Number(shown), summary.openOrders);var order = await api.GetFromJsonAsync<JsonElement>($"orders/{orderId}");Assert.That(order.GetProperty("status").GetString(), Is.EqualTo("CANCELLED"));
var summary = await api.GetFromJsonAsync<JsonElement>("account/summary");var shown = driver.FindElement(By.CssSelector("[data-testid='open-orders-count']")).Text;Assert.That(int.Parse(shown), Is.EqualTo(summary.GetProperty("openOrders").GetInt32()));Two cautions. First, backend changes may be asynchronous (queues, eventual consistency), so poll the API with a timeout rather than asserting once; the same FluentWait/WebDriverWait machinery works with any condition, not just elements (see Fluent Waits). Second, do not duplicate business logic in the test: if the API returns total: 41.97, compare that string with the UI’s formatted value, rather than recomputing tax and discounts yourself.
An alternative to calling the API separately is to observe the browser’s own API traffic with BiDi and assert on the response the UI received, or to stub it to force edge-case states. See Network Interception with BiDi.
Architecture: Keeping It Clean
A hybrid suite needs structure or it turns into a tangle of HTTP calls inside tests. A layout that scales:
tests/ orders/CancelOrderTest # reads like a spec: arrange (api), act (pages), assertapi/ ApiClient # base URL, auth, retries, JSON (de)serialisation OrdersApi, UsersApi # typed operations: createOrder, getOrder, deleteUserpages/ OrderPage, DashboardPage # page objects, UI onlysupport/ SessionInjector # API login -> cookies/localStorage in the driver TestDataFactory # unique users, orders, products- Page objects never call the API, and API clients never touch the driver. The test (or a fixture) combines them.
SessionInjectoris the only class that knows how auth is stored in the browser. When the front end moves from cookies to tokens, one class changes.- Fixtures do the arranging. In pytest a
logged_in_driverfixture, in JUnit an extension, in NUnit a base class[SetUp]; tests start already authenticated. See Pytest Integration and TestNG and JUnit. - API and UI share configuration (base URLs, credentials from environment variables or a secrets manager), so they always point at the same environment.
Speed Gains in Practice
From a typical mid-sized suite of 400 UI tests after moving login and data setup to the API:
| Step | All-UI | Hybrid |
|---|---|---|
| Login per test | 4 s | 0.3 s |
| Data setup per test (average) | 12 s | 0.5 s |
| Behaviour under test | 6 s | 6 s |
| Total per test | 22 s | 6.8 s |
| Suite on 8 parallel workers | ~18 min | ~6 min |
The stability gain is often worth more than the time. Each UI step removed is one fewer wait, one fewer locator and one fewer place for a test to fail for reasons unrelated to what it checks. For more speed techniques, see Speeding Up Test Suites.
What Not to Move to the API
- The flows you are testing. Login, registration, checkout and password reset need full UI tests of their own. API-assisting them defeats the point.
- Client-side state the user creates. If a feature depends on the user having clicked through an onboarding tour that writes to
localStorage, either set that state deliberately and document it, or keep a UI test that covers the real path. - Third-party-hosted steps. A payment provider’s hosted page or an identity provider’s login cannot be API-assisted from your side; use their sandbox modes and test-mode tokens instead.
Summary
- Arrange and clean up through the API; act and assert through the UI; confirm side effects through the API.
- Inject sessions with
addCookieafter visiting the domain (host-only cookies, no explicit domain), or set tokens inlocalStorageand reload. - Seed unique data per test through a typed API client and clean it up tolerantly.
- Keep page objects and API clients separate, and confine auth injection to one class.
- Expect suites to become several times faster and markedly less flaky.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.