
Selenium API Testing: What Works and What Doesn't
Selenium can't test APIs on its own. Selenium WebDriver drives a browser the way a user would, and it has no HTTP client: there is no method for sending a GET or POST to a REST endpoint and asserting on the JSON. For API testing in a Selenium project you add an HTTP library next to it (REST Assured in Java, Requests with pytest in Python), use the API to set up state for your UI tests, and use Selenium 4's WebDriver BiDi network module when you need to watch or stub the API calls the browser itself makes. This guide shows all three with complete code, checked against Selenium 4.52.0 (released October 29, 2026, per PyPI).
Is Selenium an API or a framework?
Both words get used, and that is where most of the confusion around "Selenium API" starts:
- The Selenium API is the WebDriver client library: the classes and methods you call, such as
driver.get(),find_element()andclick(). It ships for Java, Python, C#, Ruby and JavaScript and talks to browsers through the W3C WebDriver protocol. Since Selenium 4 it can also open a WebDriver BiDi WebSocket for browser events. - Selenium is not a test framework. It has no test runner, assertions or reports. You pair it with JUnit or TestNG (Java), pytest (Python) or NUnit/xUnit (C#).
- Selenium is not an API testing tool. It drives browsers, not HTTP endpoints.
When people search for the Python Selenium API or the Selenium Java API, they usually mean that client library. In Python it is the selenium package on PyPI (4.52.0 as of November 2026, requires Python 3.10 or newer per PyPI). In Java it is org.seleniumhq.selenium:selenium-java on Maven Central, also 4.52.0, built to run on Java 11 and newer according to the Java changelog. The project is Apache-2.0 licensed (GitHub).
What Selenium's own docs say about API checks
Two pages in the official docs settle the question. The HTTP response codes page explains that Selenium RC could read status codes because it sat between the browser and the site as a proxy, while WebDriver acts like a user, so you should check the page title or a known element after each load instead. The Generating application state page goes the other way: it says "Selenium should not be used to prepare a test case" and tells you to log in and create test data through existing APIs.
Put together: API calls belong in your Selenium test suite, but they are made by an HTTP library, not by WebDriver.
Can you do API testing with Selenium?
Not with WebDriver alone: REST API automation testing using Selenium WebDriver commands isn't possible, because every WebDriver command acts on a browser. What you can do is API automation testing using Selenium's project as the home for it: one repository, one CI job, one config, with two kinds of tests inside.
API automation means sending requests to an API from code and asserting on the response (status, headers, body, schema, timing) without a person clicking anything. An API test needs only an HTTP client and a test runner. A Selenium test needs a browser, a driver and a page that renders. That difference is why the two layers are written with different tools even when they live side by side.
Here is how the pieces fit:
| Goal | Tool | Where it runs |
|---|---|---|
| Test REST endpoints directly (status, JSON, schema) | REST Assured, Requests + pytest, Newman | Your test code, no browser |
| Set up test data or log in fast before a UI test | Same HTTP library, plus Selenium cookies | Test code, then browser |
| Check the API calls the browser makes during a UI flow | Selenium WebDriver BiDi network events | Browser |
| Test the UI when an API fails or returns odd data | Selenium BiDi request interception (stub a response) | Browser |
Pure API tests vs UI tests vs hybrid tests
Most suites need all three kinds. The question is how many of each. This table is the quickest way to decide where a check belongs:
| Question | Pure API test | Selenium UI test | Hybrid (API setup + UI check) |
|---|---|---|---|
| What it proves | The endpoint returns the right status and data | A user can complete a journey in a real browser | Data created on the backend shows up correctly in the UI |
| Needs a browser | No | Yes | Yes |
| Typical tools | REST Assured, Requests + pytest, Newman | Selenium + JUnit/pytest | HTTP client + Selenium |
| Good for | Validation rules, error codes (400, 401, 404, 409), auth, pagination, contracts | Login, checkout, forms, navigation, rendering | "Order placed via API appears in My Orders", permissions in the UI |
| Bad for | Layout, JavaScript errors, real user flows | Field-by-field validation, every error code | Exhaustive data permutations |
| Where it breaks | API contract changes | Locators, timing, browser versions | Both, so keep these few |
Where API tests sit in the test pyramid
The test pyramid is the usual shorthand: many fast unit tests at the bottom, fewer API (service or integration) tests in the middle, and a small number of end-to-end UI tests at the top. Selenium tests live at the top. API tests are the layer that lets you keep that top layer small, because most of what a UI test could check (does saving fail with a bad email? does the list paginate?) is cheaper to check one level down.
Selenium's own overview of test automation makes the same point from the other side: each browser test should set up data, perform a short set of actions and evaluate the result, and browser tests get their flaky reputation mostly because people ask too much of them.
Three ways to combine Selenium and API testing
The examples below use one small demo app so the code is complete: POST /api/login sets a session cookie, POST /api/orders creates an order (and returns 400 if qty is not an integer), GET /api/orders lists orders, and the /orders page loads that list with fetch() and renders one li per order, or "Could not load orders (status)" if the call fails. Swap in your own endpoints and selectors.
1. Test the API directly with REST Assured (Java)
For API testing, Selenium Java projects usually add REST Assured: a Java DSL for HTTP tests, Apache-2.0 licensed (GitHub). The current release is 6.3.0 (October 23, 2026, per its changelog and Maven Central). REST Assured 6.0.0 raised the minimum to Java 17, so a project on Java 11 has to stay on 5.5.x or upgrade the JDK.
Add both libraries to one Maven module:
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.52.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>6.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>6.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
A pure API test reads like a sentence: given a request, when you send it, then the response must match.
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
class OrdersApiTest {
static final String BASE_URL = "http://127.0.0.1:8765";
@Test
void rejectsNonIntegerQuantity() {
String session =
given().baseUri(BASE_URL).contentType("application/json")
.body("""
{"email": "qa@example.com", "password": "demo-password"}
""")
.when().post("/api/login")
.then().statusCode(200)
.extract().cookie("session");
given().baseUri(BASE_URL).contentType("application/json").cookie("session", session)
.body("""
{"item": "Keyboard", "qty": "two"}
""")
.when().post("/api/orders")
.then()
.statusCode(400)
.body("error", equalTo("qty must be an integer"));
}
}
No browser starts, so a test like this finishes in the time one HTTP round trip takes. Run your API tests first in CI: if the API is broken, the UI run can't pass anyway. For a deeper look at what a good 400 response looks like and how to assert on it, see 400 Bad Request in REST APIs.
API automation testing with Python: Requests and pytest
For API automation testing using Selenium Python projects, the HTTP side needs two packages: Requests (2.34.2 as of November 2026, Apache-2.0) and pytest (9.2.0). Put the login in a fixture so every test gets an authenticated session:
# conftest.py
import pytest
import requests
from selenium import webdriver
BASE_URL = "http://127.0.0.1:8765"
@pytest.fixture
def api():
s = requests.Session()
r = s.post(f"{BASE_URL}/api/login",
json={"email": "qa@example.com", "password": "demo-password"},
timeout=10)
r.raise_for_status()
yield s
s.close()
@pytest.fixture
def driver():
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.enable_bidi = True # opens the WebDriver BiDi websocket (used in section 3)
d = webdriver.Chrome(options=options)
yield d
d.quit()
# test_orders.py (part 1)
from conftest import BASE_URL
def test_api_rejects_bad_qty(api):
r = api.post(f"{BASE_URL}/api/orders", json={"item": "Keyboard", "qty": "two"}, timeout=10)
assert r.status_code == 400
assert r.json() == {"error": "qty must be an integer"}
json= serializes the body and sets Content-Type: application/json for you, and the Session keeps the session cookie from the login response for every later call. Always pass a timeout: per the Requests docs, requests do not time out unless you set one, so a hung server hangs the test.
2. Use the API to set up a UI test (Python)
This is the most useful Selenium-plus-API pattern, and the one Selenium's docs recommend: skip slow UI steps by logging in and creating data through the API, then hand the session to the browser.
# test_orders.py (part 2)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from conftest import BASE_URL
def test_order_created_by_api_shows_in_ui(api, driver):
# 1. Log in through the API (fast, no browser): the api fixture did that,
# so create the test data the same way
r = api.post(f"{BASE_URL}/api/orders", json={"item": "Keyboard", "qty": 2}, timeout=10)
assert r.status_code == 201
order_id = r.json()["id"]
# 2. Give the session cookie to the browser (open the domain first)
driver.get(f"{BASE_URL}/login")
driver.add_cookie({"name": "session", "value": api.cookies["session"], "path": "/"})
# 3. Start the UI test already signed in
driver.get(f"{BASE_URL}/orders")
row = WebDriverWait(driver, 5).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, f'li[data-id="{order_id}"]')))
assert row.text == "Keyboard x2"
Three details make or break this test:
- Visit the domain before
add_cookie. WebDriver only accepts a cookie for the domain of the current page. Callingadd_cookieon the start page throwsInvalidCookieDomainException: Message: invalid cookie domain. - Copy the cookie the server set, not a value you made up. If your app sets
HttpOnlyorSecureflags, pass them too ("httpOnly": True,"secure": True) so the browser treats it like the real thing. - Wait for the element, not for time. The list is rendered by JavaScript after
fetch()returns, soWebDriverWaitwith an expected condition is the reliable signal.time.sleep()is either too short or wastes time.
If your app keeps a token in localStorage instead of a cookie, set it with driver.execute_script("localStorage.setItem('token', arguments[0])", token) after opening the domain, then reload.
The same hybrid test in Java
This is what API testing using Selenium Java code looks like end to end: REST Assured logs in and creates the order, then Selenium checks the page. Most tutorials on API testing with Selenium Java stop at the pure API test above; this is where the two tools meet. extract().cookie() and extract().path() pull values out of the response for the next step.
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
class OrdersHybridTest {
static final String BASE_URL = "http://127.0.0.1:8765";
WebDriver driver;
@BeforeEach
void startBrowser() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@AfterEach
void stopBrowser() {
driver.quit();
}
@Test
void orderCreatedByApiShowsInUi() {
// 1. Log in and create the order through the API
String session =
given().baseUri(BASE_URL).contentType("application/json")
.body("""
{"email": "qa@example.com", "password": "demo-password"}
""")
.when().post("/api/login")
.then().statusCode(200)
.extract().cookie("session");
int orderId =
given().baseUri(BASE_URL).contentType("application/json").cookie("session", session)
.body("""
{"item": "Keyboard", "qty": 2}
""")
.when().post("/api/orders")
.then().statusCode(201)
.extract().path("id");
// 2. Give the session to the browser (open the domain first)
driver.get(BASE_URL + "/login");
driver.manage().addCookie(new Cookie("session", session, "/"));
// 3. Check the UI
driver.get(BASE_URL + "/orders");
WebElement row = new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("li[data-id='" + orderId + "']")));
assertEquals("Keyboard x2", row.getText());
}
}
Selenium 4.6 and later include Selenium Manager, which finds your installed Chrome and downloads the matching driver, so new ChromeDriver(options) works without a separate chromedriver download.
3. Watch the browser's API calls with WebDriver BiDi (Java)
Selenium 4 supports WebDriver BiDi, the W3C protocol that adds a WebSocket to WebDriver so your test can subscribe to browser events. The Selenium network guide (updated November 3, 2026) describes two halves: events (beforeRequestSent, responseStarted, responseCompleted, authRequired) that you can record and assert on, and intercepts that pause a request so your code can continue it, fail it, or answer it.
You turn BiDi on in the browser options when the session starts: options.setCapability("webSocketUrl", true) in Java and options.enable_bidi = True in Python, per Enabling BiDi.
This test waits for the page's call to /api/orders and checks its status. The Network methods and their signatures are from the Selenium 4.52.0 Network module source and the docs' network events test:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.ResponseDetails;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.setCapability("webSocketUrl", true); // enables BiDi
ChromeDriver driver = new ChromeDriver(options);
try (Network network = new Network(driver)) {
CompletableFuture<ResponseDetails> ordersCall = new CompletableFuture<>();
network.onResponseCompleted(r -> {
if (r.getRequest().getUrl().endsWith("/api/orders")) ordersCall.complete(r);
});
driver.get(BASE_URL + "/login");
driver.manage().addCookie(new Cookie("session", session, "/"));
driver.get(BASE_URL + "/orders");
ResponseDetails response = ordersCall.get(5, TimeUnit.SECONDS);
assertEquals(200, response.getResponseData().getStatus());
} finally {
driver.quit();
}
Use this to catch a UI that looks fine while a background call fails, or to confirm the frontend sent the request you expect. Don't use it as your API test suite: it only sees traffic the page happens to trigger.
Stub an API response with Selenium 4 (Java)
Interception lets you test the UI's error state without breaking the real server. Add an intercept for one URL at the BEFORE_REQUEST_SENT phase, then answer the paused request with provideResponse. The classes below exist in Selenium 4.52.0; ProvideResponseParameters is marked @Beta in the source, so expect changes.
import java.util.List;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.AddInterceptParameters;
import org.openqa.selenium.bidi.network.BytesValue;
import org.openqa.selenium.bidi.network.Header;
import org.openqa.selenium.bidi.network.InterceptPhase;
import org.openqa.selenium.bidi.network.ProvideResponseParameters;
try (Network network = new Network(driver)) {
network.addIntercept(new AddInterceptParameters(InterceptPhase.BEFORE_REQUEST_SENT)
.urlStringPattern(BASE_URL + "/api/orders"));
network.onBeforeRequestSent(event -> {
if (!event.isBlocked()) return; // events fire for every request; only intercepted ones wait
network.provideResponse(
new ProvideResponseParameters(event.getRequest().getRequestId())
.statusCode(500)
.headers(List.of(new Header("Content-Type",
new BytesValue(BytesValue.Type.STRING, "application/json"))))
.body(new BytesValue(BytesValue.Type.STRING, "{}")));
});
driver.get(BASE_URL + "/orders");
WebElement error = new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.visibilityOfElementLocated(By.id("error")));
assertEquals("Could not load orders (500)", error.getText());
}
To simulate a network failure instead of an error status, call network.failRequest(event.getRequest().getRequestId()), which is the docs' own fail request example.
Watch and stub network calls in Python (Selenium 4.52)
The Python binding exposes BiDi as driver.network. These two tests ran against the demo app with Selenium 4.52.0, Chrome 157 and Python 3.11 on macOS (output at the end of this section).
Listening is the simple case. add_event_handler("response_completed", ...) gets every finished response without pausing anything:
# test_network.py
from selenium.webdriver.support.ui import WebDriverWait
from conftest import BASE_URL
def login_browser(api, driver):
driver.get(f"{BASE_URL}/login")
driver.add_cookie({"name": "session", "value": api.cookies["session"], "path": "/"})
def test_page_calls_orders_api_and_gets_200(api, driver):
seen = []
def on_response(event):
if event.response["url"].endswith("/api/orders"):
seen.append((event.response["url"], event.response["status"]))
handler = driver.network.add_event_handler("response_completed", on_response)
try:
login_browser(api, driver)
driver.get(f"{BASE_URL}/orders")
WebDriverWait(driver, 5).until(lambda d: seen)
finally:
driver.network.remove_event_handler("response_completed", handler)
url, status = seen[0]
assert url.endswith("/api/orders")
assert status == 200
Stubbing uses add_request_handler with an intercept on one URL. The phase-based form below is documented in the method's docstring in 4.52.0: your callback must resolve the request itself.
# test_stub.py
import threading
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from conftest import BASE_URL
def test_ui_shows_error_when_api_fails(api, driver):
def stub_500(request):
if not request.url.endswith("/api/orders"):
return # the event fires for every request; only this one is paused
# Answer off the websocket thread so the BiDi reply can be read
threading.Thread(target=request.provide_response, kwargs={
"status": 500, "headers": {"Content-Type": "application/json"}, "body": "{}"}).start()
cid = driver.network.add_request_handler(
"before_request", stub_500,
url_patterns=[{"type": "string", "pattern": f"{BASE_URL}/api/orders"}])
try:
driver.get(f"{BASE_URL}/login")
driver.add_cookie({"name": "session", "value": api.cookies["session"], "path": "/"})
driver.get(f"{BASE_URL}/orders")
error = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.ID, "error")))
assert error.text == "Could not load orders (500)"
finally:
driver.network.remove_request_handler("before_request", cid)
Running all four Python tests from this guide (pytest -v) printed:
test_orders.py::test_api_rejects_bad_qty PASSED [ 25%]
test_orders.py::test_order_created_by_api_shows_in_ui PASSED [ 50%]
test_network.py::test_page_calls_orders_api_and_gets_200 PASSED [ 75%]
test_stub.py::test_ui_shows_error_when_api_fails PASSED [100%]
============================== 4 passed in 4.29s ===============================
The older route: Chrome DevTools Protocol (CDP)
Before BiDi, Selenium 4 offered network interception through the Chrome DevTools Protocol (NetworkInterceptor in Java, execute_cdp_cmd in Python). The Selenium docs now say CDP support is temporary until BiDi is implemented, that CDP is Chromium-only and tied to specific browser versions, and that you should not start new work on it (CDP network page, network guide). Each Selenium release supports only a few CDP versions: 4.52.0 supports v154 to v156 (Python changes). If you maintain old CDP code, plan the move to BiDi.
SOAP API testing and web services testing using Selenium
SOAP API testing using Selenium hits the same wall as REST: WebDriver cannot call SOAP and other XML web services, because they are HTTP endpoints, not pages. For webservices testing using Selenium WebDriver in Java, REST Assured covers SOAP well enough for most suites, since a SOAP call is an HTTP POST with an XML body and REST Assured asserts on XML with Groovy XmlSlurper-style paths. Without declared namespaces, paths use local element names, per the REST Assured usage guide:
given()
.baseUri("https://soap.example.com")
.contentType("text/xml; charset=utf-8")
.header("SOAPAction", "urn:GetOrder")
.body("""
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ord="urn:orders">
<soapenv:Body><ord:GetOrder><ord:id>42</ord:id></ord:GetOrder></soapenv:Body>
</soapenv:Envelope>
""")
.when()
.post("/OrderService")
.then()
.statusCode(200)
.body("Envelope.Body.GetOrderResponse.status", equalTo("SHIPPED"));
The SOAPAction value, namespace and path depend on your WSDL; copy them from a working request. In Python, requests.post(url, data=envelope, headers={...}) does the same job, and the zeep library can build calls from the WSDL. If your team works mostly with SOAP and wants a GUI, SmartBear's SoapUI open source edition is built for it. Once the service call works, the hybrid pattern above applies unchanged: create the data through the service, then check it in the browser with Selenium.
Selenium vs REST API, FastAPI, OpenAI API and OAuth
These comparisons show up in searches, but they compare things that do different jobs. Each one sits on a different layer:
| Comparison | What each one is | How they relate |
|---|---|---|
| Selenium vs REST API | Selenium automates a browser. A REST API is an HTTP interface your backend exposes. | You test a REST API with an HTTP client; you test the UI that calls it with Selenium. |
| Selenium vs FastAPI | FastAPI is a Python framework for building APIs. | You build the API with FastAPI and test it with pytest and FastAPI's TestClient, then test the web UI with Selenium. |
| Selenium vs OpenAI API | The OpenAI API is a hosted model API you call over HTTP. | OpenAI API vs Selenium is not an either/or. Some teams call a model API to generate test data or read failures; Selenium still drives the browser. |
| Selenium vs OAuth | OAuth is an authorization protocol that issues access tokens. | In tests, get a token through the API (or a test-only login endpoint) and inject it, rather than clicking through a third-party login page in Selenium. |
The OAuth row matters most in practice. Third-party login pages (Google, GitHub, Microsoft) change their markup, add bot checks and enforce two-factor prompts. Selenium's docs list two-factor authentication as something to avoid automating, and suggest a special token that works only in the test environment or disabling 2FA for test users.
How to set up a Selenium API testing framework
- Keep two layers in one repository. An
apipackage with HTTP clients and API tests, and auipackage with page objects and Selenium tests. Share config (base URLs, test accounts) between them. - Write API clients once. Wrap endpoints in small methods (
login(),create_order()) that both the API tests and the UI test setup call. When an endpoint changes, you fix one method. - Run API tests first in CI. They are fast and tell you whether the UI run is worth starting.
- Seed and clean data through the API, not through the UI. Selenium's docs list avoiding shared state and test independency as encouraged practices; fresh data per test is how you get there.
- Keep UI tests for user journeys. Validation rules, error codes and edge cases belong in the API layer.
- Stub third parties in the browser. For payment widgets, analytics and maps, use BiDi interception (or a stub server) rather than letting UI tests depend on someone else's uptime. The docs' Mock external services page makes the same recommendation.
A layout that works for both Java and Python:
tests/
api/
client.py # login(), create_order(), delete_order()
test_orders_api.py # pure API tests
ui/
pages/orders.py # page objects
test_orders_ui.py # hybrid tests: client.py for setup, Selenium for checks
conftest.py # fixtures: api session, driver, base URL from env
Running Selenium and API tests in CI
The Selenium CI guide lists the usual failure causes on a build server: no display, a different browser version, no driver on the PATH, and a locked-down network. The fixes that matter for a mixed suite:
- Headless browsers. Chrome and Edge take
--headless=new, Firefox takes-headless. Keep it behind a config flag so you can watch tests locally. - Let Selenium Manager fetch drivers. It caches them in
~/.cache/selenium; cache that directory between CI runs. A stale driver preinstalled on the runner'sPATHtakes precedence, so remove it or keep it current. Behind a proxy, setSE_PROXY. - Two jobs, API first. Run
pytest tests/api(ormvn test -Dgroups=apiwith JUnit tags) as its own step before the browser tests. A broken endpoint then fails in seconds with a clear message. - One report format. pytest writes JUnit XML with
--junitxml=report.xml; Maven Surefire writes it by default; Newman writes it with-r cli,junit --reporter-junit-export results.xml(Newman README). Most CI systems merge JUnit XML from all three. - Artifacts on failure. The CI guide recommends collecting a screenshot and the Selenium log on every failure. For hybrid tests, also log the API responses you used for setup.
- Point the base URL at an environment variable, never at production by accident. API setup calls create real data.
Common errors when mixing Selenium and API tests
| Error or symptom | Cause | Fix |
|---|---|---|
InvalidCookieDomainException: Message: invalid cookie domain |
add_cookie called before the browser opened your site, or with a domain that doesn't match the current page |
driver.get() a page on the same domain first; drop the domain key or make it match |
| UI still shows the login page after adding the cookie | Wrong cookie name, missing path, or the app also checks a CSRF token or localStorage |
Copy every cookie from the API session; set path: "/"; inspect what a real browser login stores |
TimeoutException on driver.get() with interception on |
An intercepted request was never continued, failed or answered | Resolve every paused request; narrow the URL pattern; remove intercepts after the test (from the Selenium network guide) |
UnsupportedCommandException on a network command |
BiDi was not enabled for the session, or the browser doesn't implement that command yet (same source) | Set enable_bidi = True / webSocketUrl before creating the driver; check the BiDi tracking issue |
Python: no such request: Network request with ID '...' doesn't exist |
Your callback tried to answer a request that was never intercepted (the event fires for all requests) | Check request.url (or the blocked flag) before calling provide_response or fail |
| Python: BiDi test hangs inside a network callback | A BiDi command sent from the WebSocket thread waits for its own reply (seen on 4.52.0) | Run the command on another thread, as in test_stub.py above |
| API test passes, hybrid test fails with 401 | The API session and browser session are not the same user, or the token expired | Create the session in the same test; don't share sessions across tests |
requests call hangs forever in CI |
No timeout set | Always pass timeout=; Requests does not time out by default |
When to use something other than Selenium
- Playwright is the main alternative if you are starting fresh and want UI and API tests in one tool. Its APIRequestContext sends HTTP requests from the test, and when you use
context.requestorpage.requestit reads cookies from the browser context and storesSet-Cookieresponses back into it. Playwright is Apache-2.0 licensed (GitHub) and at 1.65.0 on npm and PyPI as of November 2026. Its limitation for existing teams: you rewrite your page objects and lose Selenium Grid. See the Playwright page on DevHunt and how it stacks up in Cypress vs Playwright. - Postman and Newman for exploring APIs and sharing collections with a team. Newman (6.2.3 on npm, Apache-2.0, needs Node.js 16 or newer per its README) runs a Postman collection from the command line, so the same collection runs in CI. The limitation: collection tests live in JSON outside your codebase, so they drift from your Selenium code. If you want something lighter, see these Postman alternatives.
- Insomnia, Bruno and other REST clients for manual exploration before you automate. Our roundups of Insomnia best practices and REST clients for developers compare them.
- REST Assured or Requests + pytest alone if you only need API tests and no browser at all.
Here is the hybrid test from section 2 rewritten with Playwright for Python. I ran it against the same demo app with Playwright 1.65.0 and the installed Chrome (channel="chrome"), and it printed ok, order 4 visible:
from playwright.sync_api import sync_playwright, expect
BASE_URL = "http://127.0.0.1:8765"
with sync_playwright() as p:
browser = p.chromium.launch(channel="chrome") # uses the installed Google Chrome
context = browser.new_context(base_url=BASE_URL)
# context.request shares cookies with the browser context
context.request.post("/api/login", data={"email": "qa@example.com", "password": "demo-password"})
order = context.request.post("/api/orders", data={"item": "Mouse", "qty": 1}).json()
page = context.new_page()
page.goto("/orders")
expect(page.locator(f'li[data-id="{order["id"]}"]')).to_have_text("Mouse x1")
print("ok, order", order["id"], "visible")
browser.close()
No cookie copying: the login response's Set-Cookie lands in the browser context directly. That is the real difference between the two tools for hybrid tests.
Python web automation without Selenium
If you only need data from a site and not a test of its UI, skip the browser. Call the site's API (open DevTools, watch the Network tab while the page loads, and call the same endpoint with Requests), or fetch the HTML and parse it. Reach for a browser (Selenium or Playwright) only when the page needs JavaScript to render or a real login flow. For more options, browse the testing tools on DevHunt.
Versions at a glance (November 2026)
How this guide was checked: on November 10 and 11, 2026 I read the Selenium documentation pages linked above (BiDi, network guide, CI guide, test practices), the Selenium 4.52.0 Python and Java changelogs and Java sources, the REST Assured changelog, the Playwright API testing docs and the Newman README, and pulled current versions from PyPI, npm and Maven Central. The Python tests and the Playwright script were run locally against a small demo app (Selenium 4.52.0, Chrome 157, Python 3.11, macOS). The Java examples were not compiled here (no JDK on the machine); they use only classes and methods present in the Selenium 4.52.0 and REST Assured 6.3.0 releases.
FAQ
Can Selenium be used for API testing?
Not by itself. Selenium automates browsers. Use REST Assured, Requests with pytest, or another HTTP client for API tests, and use Selenium for the UI. Selenium 4's BiDi network events can observe and stub the API calls a browser makes, but that complements API tests rather than replacing them.
What is the Selenium API?
It's the WebDriver client library you call from Java, Python, C#, JavaScript or Ruby (methods such as get, findElement and click). It sends commands to the browser over the W3C WebDriver protocol, and since Selenium 4 also over WebDriver BiDi for events such as network traffic.
How do I do API testing with Selenium in Java?
Add REST Assured as a test dependency in the same project, write API tests with given().when().post().then(), and call the same endpoints from your Selenium tests' setup to log in or create data. Note that REST Assured 6.x requires Java 17, while Selenium's Java client still supports Java 11.
How do I do API automation testing using Selenium and Python?
Use Requests (or httpx) with pytest for the API tests, and share a logged-in requests.Session with your Selenium tests through a fixture. For hybrid tests, create data with the session, copy its cookie into the browser with driver.add_cookie() after opening your domain, then assert on the page.
Can Selenium read the HTTP status code of a page?
WebDriver Classic can't. With WebDriver BiDi enabled (webSocketUrl capability in Java, enable_bidi in Python), you can subscribe to network response events and read the status. Selenium recommends checking the page content instead for most UI tests.
Is Playwright better than Selenium for API testing?
For tests that mix UI and API, Playwright is simpler: its request context shares cookies with the browser, so you skip the cookie copying. Selenium supports more languages, has Selenium Grid, and is already in many test suites, so existing Selenium teams usually add REST Assured or Requests rather than migrate.
Can I test SOAP web services with Selenium?
No. SOAP services are HTTP endpoints with XML bodies, so test them with an HTTP client (REST Assured in Java, Requests or zeep in Python) or a SOAP tool such as SoapUI. Use Selenium only for the web pages that use those services.
REST API vs Selenium: which one do I need?
A REST API is an HTTP interface a server exposes; Selenium is a library that drives a web browser. They are not alternatives: you test the REST API with an HTTP client and the web app built on top of it with Selenium, often in the same suite.
What is API automation?
API automation is testing an API from code: a script sends requests, checks the status, headers and body of each response, and runs on every build without anyone clicking. It needs an HTTP client and a test runner, not a browser, which is why Selenium is not part of it.
Does Selenium 4 network interception work in every browser?
The BiDi network module is a W3C standard, but browser and binding coverage still differs. The Selenium docs' examples run on Firefox and the project tracks progress in issue #13993. The older CDP route works only in Chromium-based browsers and is being phased out.