Why Mix API and UI?
UI tests are slow. Do not use the UI for steps that are not the focus of the test. If you test the checkout page, you do not need to click through registration, login and product search first. Create the data with the API (fast and stable) and use Selenium only for the part you want to test.
| Task | Best tool |
| Create a user, product or order | API |
| Log in to reach the page under test | API (set cookie or token) |
| Test what a user sees and clicks | Selenium |
| Verify that data was saved correctly | API or database |
| Clean up after the test | API |
bash
pip install requests
A Small API Client
python
# utils/api_client.py
import requests
class ApiClient:
def __init__(self, base_url):
self.base = base_url.rstrip("/")
self.session = requests.Session()
def login(self, username, password):
r = self.session.post(f"{self.base}/api/login",
json={"username": username, "password": password}, timeout=15)
r.raise_for_status()
token = r.json()["token"]
self.session.headers["Authorization"] = f"Bearer {token}"
return token
def create_item(self, name, price):
r = self.session.post(f"{self.base}/api/items", json={"name": name, "price": price}, timeout=15)
r.raise_for_status()
return r.json()
def get_item(self, item_id):
r = self.session.get(f"{self.base}/api/items/{item_id}", timeout=15)
r.raise_for_status()
return r.json()
def delete_item(self, item_id):
self.session.delete(f"{self.base}/api/items/{item_id}", timeout=15)
Note: The endpoints above are examples. Use the real API of your application (find it in the Network tab of DevTools or in Swagger/OpenAPI documentation).
Fixture: Create and Clean Up Data
python
@pytest.fixture
def api(config):
client = ApiClient(config["base_url"])
client.login(os.environ["APP_USER"], os.environ["APP_PASSWORD"])
return client
@pytest.fixture
def item(api):
created = api.create_item(name=f"Test item {uuid.uuid4().hex[:6]}", price=19.99)
yield created
api.delete_item(created["id"]) # cleanup even if the test fails
Login by API, Then Open the UI Page
python
@pytest.fixture
def logged_in_driver(driver, config, api):
driver.get(config["base_url"]) # open the domain first
for cookie in api.session.cookies:
driver.add_cookie({"name": cookie.name, "value": cookie.value, "path": "/"})
driver.refresh()
return driver
If the application stores a token in local storage instead of a cookie:
python
driver.execute_script("window.localStorage.setItem('token', arguments[0]);", token)
driver.refresh()
The Test
python
def test_edit_item_price(logged_in_driver, item, api):
page = ItemsPage(logged_in_driver).open()
page.edit_price(item["name"], 24.50) # UI: the behavior under test
saved = api.get_item(item["id"]) # API: verify the backend
assert saved["price"] == 24.50
Network Tab: Find the API
- Open DevTools (F12) and the Network tab
- Filter by Fetch/XHR
- Perform the action in the UI
- Click the request: you see the URL, method, headers, payload and response
- Right click and choose Copy as cURL to recreate it in Python
Also check the response of the UI: To verify that clicking Save sent the right data, compare the UI result with the API result, as in the test above.
Conclusion
Use requests to create data, log in and verify results quickly and keep Selenium for what the user sees. This makes tests faster, shorter and less flaky.
Quick Summary: API for setup/cleanup/verification; Selenium for the user journey.