“Project 3: API + UI Hybrid Test Framework with GitHub Actions CI (Playwright Python)”

Real products are tested at two levels: the API that holds the business rules and the UI that people use. This project builds one framework that does both, with Playwright Python. The API side is a typed client for the SQA Tools practice API with JSON Schema contract tests and role checks; the UI side is a page object for the practice site’s request console; and hybrid tests create data through one layer and verify it through the other. Finally, a GitHub Actions workflow runs API tests without browsers and UI tests with them, in parallel jobs with a results summary.

Advertisement

📖 What You’ll Learn: designing layers (API client, schemas, page objects, fixtures, tests), a typed API client with logging, fetching and caching JSON Schemas, contract tests with jsonschema, role-based authorization tests, a factory fixture that cleans up, a page object for a JSON request console, hybrid API-to-UI and UI-to-API tests, markers to select layers, running layers in parallel, and a two-job GitHub Actions pipeline with a job summary.


🧭 What We Are Building

Layer Target Tests
API SQA Tools practice API (/wp-json/sqa-api/v1) contract (JSON Schema), CRUD, validation, roles
UI The practice page’s custom request console (method, path, body, Send, response panel) the console shows correct status and JSON
Hybrid both API creates → UI reads; UI creates → API verifies and cleans up
api-ui-hybrid/
├── pytest.ini
├── requirements.txt
├── conftest.py                  fixtures for every layer
├── framework/
│   ├── api_client.py            typed client for the practice API
│   └── contracts.py             JSON Schema fetch + validate
├── pages/
│   └── api_console.py           page object for the request console
├── tests/
│   ├── api/test_objects.py
│   ├── api/test_auth.py
│   ├── ui/test_console.py
│   └── hybrid/test_round_trips.py
└── .github/workflows/ci.yml

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
pytest-xdist==3.8.0
jsonschema==4.26.0

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --strict-markers -ra
pythonpath = .
testpaths = tests
markers =
    api: API tests (no browser)
    ui: UI tests
    hybrid: tests that use both layers

🔌 The API Client

One method per business action, typed return values, and a log line per call. Tests never build URLs themselves:

📄 framework/api_client.py

import logging
from dataclasses import dataclass

from playwright.sync_api import APIRequestContext, APIResponse

log = logging.getLogger("api")


@dataclass
class ApiError(Exception):
    status: int
    body: dict

    def __str__(self):
        return f"HTTP {self.status}: {self.body}"


class PracticeApi:
    def __init__(self, request: APIRequestContext, token: str | None = None):
        self.request = request
        self.headers = {"Authorization": f"Bearer {token}"} if token else {}

    def _check(self, response: APIResponse, *expected: int) -> dict:
        log.info("%s -> %s", response.url.split("/v1/")[-1], response.status)
        body = response.json() if response.body() else {}
        if response.status not in expected:
            raise ApiError(response.status, body)
        return body

    # --- auth -----------------------------------------------------------
    def login(self, username: str, password: str) -> "PracticeApi":
        body = self._check(self.request.post("auth/login", data={"username": username, "password": password}), 200)
        return PracticeApi(self.request, body["access_token"])

    # --- temporary objects (no auth) ------------------------------------
    def create_object(self, name: str, data: dict) -> dict:
        return self._check(self.request.post("objects", data={"name": name, "data": data}), 201)

    def get_object(self, object_id: str) -> dict:
        return self._check(self.request.get(f"objects/{object_id}"), 200)

    def object_exists(self, object_id: str) -> bool:
        return self.request.get(f"objects/{object_id}").status == 200

    def delete_object(self, object_id: str) -> None:
        self._check(self.request.delete(f"objects/{object_id}"), 200, 204, 404)

    # --- bearer-protected objects ---------------------------------------
    def create_token_object(self, name: str) -> dict:
        return self._check(self.request.post("token/objects", data={"name": name, "data": {}}, headers=self.headers), 201)

    # --- read-only data ---------------------------------------------------
    def product(self, product_id: int) -> dict:
        return self._check(self.request.get(f"products/{product_id}"), 200)["data"]

📄 framework/contracts.py

from functools import cache

from jsonschema import Draft7Validator, FormatChecker

_request = None


def use(request):
    """Give the module an APIRequestContext (set once by a session fixture)."""
    global _request
    _request = request


@cache
def schema(name: str) -> dict:
    response = _request.get(f"schema/{name}")
    assert response.ok, f"schema {name}: HTTP {response.status}"
    return response.json()


def assert_matches(instance: dict, name: str) -> None:
    validator = Draft7Validator(schema(name), format_checker=FormatChecker())
    errors = sorted(validator.iter_errors(instance), key=lambda e: list(e.path))
    assert not errors, "\n".join(f"{'/'.join(map(str, e.path)) or '<root>'}: {e.message}" for e in errors)

The schemas come from the API itself (/schema/object, /schema/product …), so the contract tests check that responses match what the service promises, and a schema change shows up in the next run.


🧩 Fixtures for Every Layer

📄 conftest.py

import uuid
from pathlib import Path

import pytest
from playwright.sync_api import Page, Playwright

from framework import contracts
from framework.api_client import PracticeApi

API_URL = "https://sqatools.in/wp-json/sqa-api/v1/"


@pytest.fixture(scope="session")
def api(playwright: Playwright) -> PracticeApi:
    request = playwright.request.new_context(base_url=API_URL)
    contracts.use(request)
    yield PracticeApi(request)
    request.dispose()


@pytest.fixture
def unique_name(worker_id) -> str:
    return f"hybrid-{worker_id}-{uuid.uuid4().hex[:8]}"


@pytest.fixture
def created_objects(api):
    """Collects IDs of objects a test created (through any layer) and deletes them afterwards."""
    ids: list[str] = []
    yield ids
    for object_id in ids:
        api.delete_object(object_id)


@pytest.fixture
def console(page: Page):
    from pages.api_console import ApiConsolePage          # UI layer, written in the next section
    return ApiConsolePage(page).open()


def pytest_collection_modifyitems(items):
    for item in items:                                   # tests/api/... -> @api, tests/ui/... -> @ui, ...
        layer = Path(item.path).parent.name
        if layer in ("api", "ui", "hybrid"):
            item.add_marker(layer)

The last hook marks each test by its folder, so pytest -m api and pytest -m "ui or hybrid" select layers without decorating every test.


Advertisement

🧪 API Tests: Contracts, CRUD, Validation

📄 tests/api/test_objects.py

import pytest

from framework.api_client import ApiError
from framework.contracts import assert_matches


def test_created_object_matches_contract(api, unique_name, created_objects):
    obj = api.create_object(unique_name, {"price": 999})
    created_objects.append(obj["id"])
    assert_matches(obj, "object")
    assert obj["name"] == unique_name and obj["version"] == 1


def test_product_matches_contract(api):
    product = api.product(101)
    assert_matches(product, "product")


def test_contract_catches_a_broken_response(api):
    broken = {"id": "x", "name": "", "data": {}, "version": 0}          # wrong values, missing fields
    with pytest.raises(AssertionError) as info:
        assert_matches(broken, "object")
    print("\n" + str(info.value))


def test_deleted_object_is_gone(api, unique_name):
    obj = api.create_object(unique_name, {})
    api.delete_object(obj["id"])
    assert not api.object_exists(obj["id"])


def test_missing_name_is_rejected(api):
    with pytest.raises(ApiError) as info:
        api.create_object("", {})
    print(f"\n{info.value}")
    assert info.value.status in (400, 422)

📄 tests/api/test_auth.py

import pytest

from framework.api_client import ApiError


@pytest.fixture(scope="module")
def viewer(api):
    return api.login("viewer", "viewer@123")


def test_admin_can_create(api, unique_name):
    admin = api.login("admin", "admin@123")
    created = admin.create_token_object(unique_name)
    assert created["name"] == unique_name


def test_viewer_cannot_create(viewer, unique_name):
    with pytest.raises(ApiError) as info:
        viewer.create_token_object(unique_name)
    assert info.value.status == 403


def test_wrong_password(api):
    with pytest.raises(ApiError) as info:
        api.login("admin", "nope")
    assert info.value.status == 401

⌨️ Terminal

pytest -m api -v -s

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 8 items

tests/api/test_auth.py::test_admin_can_create PASSED
tests/api/test_auth.py::test_viewer_cannot_create PASSED
tests/api/test_auth.py::test_wrong_password PASSED
tests/api/test_objects.py::test_created_object_matches_contract PASSED
tests/api/test_objects.py::test_product_matches_contract PASSED
tests/api/test_objects.py::test_contract_catches_a_broken_response 
<root>: 'created_at' is a required property
<root>: 'updated_at' is a required property
<root>: 'expires_at' is a required property
<root>: 'ttl_seconds' is a required property
id: 'x' does not match '^[A-Za-z0-9_-]{3,40}$'
name: '' should be non-empty
version: 0 is less than the minimum of 1
PASSED
tests/api/test_objects.py::test_deleted_object_is_gone PASSED
tests/api/test_objects.py::test_missing_name_is_rejected 
HTTP 422: {'error': {'status': 422, 'code': 'validation_failed', 'message': '1 field(s) failed validation.', 'details': [{'field': 'name', 'message': 'name is required: text of 1 to 100 characters.'}]}}
PASSED

============================== 8 passed in 6.31s ==============================

test_contract_catches_a_broken_response proves the contract check works by feeding it an invalid object: a check that never fails is not a check. Note how ApiError carries the status and body, so failures explain themselves.


🖥️ The UI Layer: a Page Object for the Request Console

The practice page has a custom request console: choose a method, type a path, add a body, press Send, and the response status and JSON appear.

📄 pages/api_console.py

import json

from playwright.sync_api import Page


class ApiConsolePage:
    URL = "/api-testing-practice/"

    def __init__(self, page: Page):
        self.page = page
        self.method = page.locator("#ap-method")
        self.path = page.locator("#ap-path")
        self.body = page.locator("#ap-body")
        self.json_header = page.locator("#ap-json")
        self.send_button = page.locator("#ap-send")
        self.status = page.get_by_test_id("res-status")
        self.response_body = page.get_by_test_id("res-body")

    def open(self):
        self.page.goto(self.URL)
        self.path.wait_for()
        return self

    def send(self, method: str, path: str, body: dict | None = None):
        self.method.select_option(method)
        self.path.fill(path)
        self.body.fill(json.dumps(body) if body is not None else "")
        if body is not None:
            self.json_header.click()                        # adds Content-Type: application/json
        previous = self.response_body.inner_text() if self.response_body.count() else None
        self.send_button.click()
        self.page.wait_for_function(
            "prev => { const el = document.querySelector('[data-testid=res-body]'); return el && el.textContent !== prev; }",
            arg=previous)
        return self

    def json(self) -> dict:
        return json.loads(self.response_body.inner_text())

send() waits until the response panel shows a new body, the console’s equivalent of waiting for the next page.

📄 tests/ui/test_console.py

from playwright.sync_api import expect


def test_console_shows_a_product(console):
    console.send("GET", "/products/101")
    expect(console.status).to_have_text("200")
    assert console.json()["data"]["name"] == "Wireless Mouse"


def test_console_shows_not_found(console):
    console.send("GET", "/products/99999")
    expect(console.status).to_have_text("404")
    assert console.json()["error"]["code"] == "not_found"

⌨️ Terminal

pytest -m ui -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 10 items / 8 deselected / 2 selected

tests/ui/test_console.py::test_console_shows_a_product[chromium] PASSED  [ 50%]
tests/ui/test_console.py::test_console_shows_not_found[chromium] PASSED  [100%]

======================= 2 passed, 8 deselected in 6.15s =======================

Advertisement

🔁 Hybrid Tests: Cross-Layer Round Trips

📄 tests/hybrid/test_round_trips.py

from playwright.sync_api import expect


def test_created_by_api_is_visible_in_ui(api, console, unique_name, created_objects):
    obj = api.create_object(unique_name, {"source": "api"})              # arrange through the API
    created_objects.append(obj["id"])

    console.send("GET", f"/objects/{obj['id']}")                         # act and assert through the UI
    expect(console.status).to_have_text("200")
    shown = console.json()
    assert shown["name"] == unique_name and shown["data"] == {"source": "api"}


def test_created_in_ui_is_stored_in_api(api, console, unique_name, created_objects):
    console.send("POST", "/objects", body={"name": unique_name, "data": {"source": "ui"}})   # act through the UI
    expect(console.status).to_have_text("201")
    object_id = console.json()["id"]
    created_objects.append(object_id)                                    # cleaned up through the API

    stored = api.get_object(object_id)                                   # assert through the API
    assert stored["name"] == unique_name and stored["data"] == {"source": "ui"}


def test_ui_update_increments_version(api, console, unique_name, created_objects):
    obj = api.create_object(unique_name, {"qty": 1})
    created_objects.append(obj["id"])
    console.send("PATCH", f"/objects/{obj['id']}", body={"data": {"qty": 2}})
    expect(console.status).to_have_text("200")
    assert api.get_object(obj["id"])["version"] == 2

⌨️ Terminal

pytest -m hybrid -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 13 items / 10 deselected / 3 selected

tests/hybrid/test_round_trips.py::test_created_by_api_is_visible_in_ui[chromium] PASSED [ 33%]
tests/hybrid/test_round_trips.py::test_created_in_ui_is_stored_in_api[chromium] PASSED [ 66%]
tests/hybrid/test_round_trips.py::test_ui_update_increments_version[chromium] PASSED [100%]

====================== 3 passed, 10 deselected in 11.19s ======================

Each hybrid test crosses the boundary in one direction, so a failure tells you which layer is wrong: if the API stores correct data but the UI shows something else, it is a UI bug; if the UI says 201 but the API cannot find the object, it is a backend bug.


⚡ All Layers in Parallel

⌨️ Terminal

pytest -n 4 -q

🖥️ Output

bringing up nodes...
bringing up nodes...

.............                                                            [100%]
13 passed in 10.64s

Every test uses unique names (with the worker id) and cleans up what it created, so all layers run safely in parallel.


🚀 The CI Pipeline

Two jobs: API tests need no browser, so they start in seconds; UI and hybrid tests install Chromium. Both publish a summary.

📄 .github/workflows/ci.yml

name: API + UI tests

on:
  push:
    branches: [main]
  pull_request:
  schedule:
    - cron: "0 21 * * *"          # 02:30 IST nightly

concurrency:
  group: tests-${{ github.ref }}
  cancel-in-progress: true

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: pytest -m api -n 4 --junitxml=reports/api.xml
      - if: always()
        uses: actions/upload-artifact@v7
        with:
          name: api-results
          path: reports/

  ui:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: playwright install --with-deps chromium
      - run: pytest -m "ui or hybrid" -n 4 --tracing retain-on-failure --junitxml=reports/ui.xml
      - if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: ui-traces
          path: test-results/
      - if: always()
        uses: actions/upload-artifact@v7
        with:
          name: ui-results
          path: reports/

📄 check_ci.py

import yaml

wf = yaml.safe_load(open(".github/workflows/ci.yml", encoding="utf-8"))
for name, job in wf["jobs"].items():
    runs = [s["run"] for s in job["steps"] if "run" in s]
    installs_browsers = any("playwright install" in r for r in runs)
    print(f"{name:4} browsers={installs_browsers!s:5} test step: {runs[-1]}")

⌨️ Terminal

python check_ci.py

🖥️ Output

api  browsers=False test step: pytest -m api -n 4 --junitxml=reports/api.xml
ui   browsers=True  test step: pytest -m "ui or hybrid" -n 4 --tracing retain-on-failure --junitxml=reports/ui.xml

The API job never downloads a browser, which keeps it fast and cheap; the UI job keeps traces only when something failed. Add the job-summary script from Lesson 66 to both jobs for a results table on the run page.


Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Add a contract test for /people/1 against the user schema. Which client method do you add?

Show answer
def person(self, person_id: int) -> dict:
    return self._check(self.request.get(f"people/{person_id}"), 200)["data"]
def test_person_matches_contract(api):
    assert_matches(api.person(1), "user")

(Remember: list endpoints use /people, never a path ending in /users, on this site.)

Exercise 2: Write a hybrid test: create an object through the UI console, delete it through the API, then check the UI console shows 404 for it.

Show answer
def test_api_delete_visible_in_ui(api, console, unique_name):
    console.send("POST", "/objects", body={"name": unique_name, "data": {}})
    object_id = console.json()["id"]
    api.delete_object(object_id)
    console.send("GET", f"/objects/{object_id}")
    expect(console.status).to_have_text("404")

Exercise 3: Your UI job fails but the API job passes. The failing hybrid test says the API returned the right data. Where is the bug most likely, and which artifact do you open first?

Show answer

In the UI layer (the console rendering or the page object), because the API side was verified directly. Open the trace from the ui-traces artifact: check the request the console sent (Network tab) and what the response panel showed at the failing step.

Exercise 4: Make the API client log the HTTP method as well as the path and status. Why can _check not read the method from the response, and how do you add it?

Show answer

APIResponse knows the URL and status but not the request method. Pass the method in from each call and include it in the log:

def _check(self, response, *expected, method="GET"):
    log.info("%s %s -> %s", method, response.url.split("/v1/")[-1], response.status)
    ...

def create_object(self, name, data):
    return self._check(self.request.post("objects", data={"name": name, "data": data}), 201, method="POST")

🧠 MCQ Quiz: Project 3: API + UI Hybrid Framework with CI

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why split tests into api, ui and hybrid layers?
  2. Where do the JSON Schemas in this project come from?
  3. Why does the project include a test that feeds an invalid object to assert_matches?
  4. What does ApiError give a failing test?
  5. How does ApiConsolePage.send() know the response arrived?
  6. What does a hybrid test that creates through the UI and verifies through the API catch?
  7. How are layer markers applied?
  8. Why can all layers run with -n 4?
  9. Why does the API CI job not run playwright install?
  10. Which artifact does the UI job upload only when tests fail?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


Advertisement

❓ Frequently Asked Questions

🤔 Why test the API console page instead of a normal web app?

Because it is a real UI on top of the same API, which makes cross-layer checks easy to see and to run against a public practice site. The same pattern applies to any app: create through the API, verify in the UI, and vice versa.

🤔 Can I validate responses without fetching schemas over the network?

Yes: store the schemas as JSON files in the repository and load them in contracts.schema(). Fetching them from the service detects contract changes automatically; storing them detects unexpected changes in the service. Many teams do both.

🤔 Where would a database check fit?

As a third layer with its own client and fixtures (for example db.fetch_order(id)), used in hybrid tests exactly like the API client here. Keep credentials in CI secrets.

🤔 How do I add an authenticated UI flow?

Log in through the API, save storage state or cookies (Lessons 51, 55), and give the UI fixtures a logged-in context. The console here also has “Add auth” buttons for its own requests.

🤔 Should the API tests use the browser’s page.request?

Not for pure API tests: a standalone playwright.request.new_context() needs no browser. Use page.request when an API step must share cookies with the UI session.


🏁 Summary

  • A typed API client with self-explaining errors, JSON Schema contracts from the service itself, and role checks form the API layer.
  • A page object for the request console forms the UI layer; send() synchronises on a new response.
  • Hybrid tests cross the layers in both directions and point to the failing layer.
  • Folder-based markers select layers; unique names and clean-up allow parallel runs.
  • GitHub Actions runs API tests without browsers and UI tests with traces on failure, in separate jobs.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page