NỘI DUNG BÀI HỌC

✅ Hiểu APIRequestContext là gì và dùng khi nào trong Playwright
✅ Biết tạo request context (baseURL, headers, auth, storageState)
✅ Thực hành gọi API: GET / POST / PUT / PATCH / DELETE
✅ Kiểm tra response: status, headers, body, schema đơn giản
✅ Viết test API bằng pytest + Playwright request
✅ Ứng dụng vào automation thực tế:

  • Setup dữ liệu qua API để test UI nhanh hơn

  • Login bằng API rồi mở UI với storageState

  • Verify UI bằng cách đối chiếu API (API vs UI)



1. Khái niệm APIRequestContext

APIRequestContext là “client HTTP” tích hợp sẵn trong Playwright để bạn gọi API trực tiếp (không cần requests library).

Dùng khi:

  • Muốn test API nhanh + đồng nhất trong cùng framework Playwright

  • Muốn “chuẩn bị data” trước khi test UI (seed data)

  • Muốn login qua API rồi reuse session cho UI

  • Muốn verify UI bằng dữ liệu trả về từ API

Khác với page.request:

  • page.request: Sử dụng context của trang hiện tại (kế thừa cookies, headers từ trình duyệt). Thường dùng khi đang test UI mà muốn gọi thêm API.

  • playwright.request.new_context() : Tạo một context hoàn toàn mới, không liên quan đến trình duyệt. Thường dùng cho các bộ test API độc lập.

2. Các phương thức HTTP cơ bản

Dưới đây là bảng tổng hợp cách viết trong Playwright Python:

Phương thức Cú pháp lệnh Mục đích
GET request.get(url) Lấy thông tin từ server.
POST request.post(url, data={...}) Tạo mới một tài nguyên.
PUT request.put(url, data={...}) Cập nhật toàn bộ tài nguyên.
DELETE request.delete(url) Xóa tài nguyên.


3) Setup cơ bản: Tạo APIRequestContext


Ví dụ: tạo context với baseURL + headers

import pytest
from playwright.sync_api import sync_playwright

@pytest.fixture(scope="session")
def api_context():
    with sync_playwright() as p:
        request_context = p.request.new_context(
            base_url="https://jsonplaceholder.typicode.com",
            extra_http_headers={
                "Accept": "application/json"
            }
        )
        yield request_context
        request_context.dispose()
​

 

📌 Giải thích:

  • base_url: khỏi phải viết full URL mỗi lần

  • extra_http_headers: header mặc định cho mọi request

  • dispose(): giải phóng tài nguyên


4) Kiểm tra Response trong Playwright


Một response thường cần check:

  • statusok

  • headers

  • body (json/text)

  • field quan trọng (assert business)

  • Thời gian phản hồi (tùy yêu cầu)

Ví dụ: GET + assert response

def test_get_post(api_context):
    res = api_context.get("/posts/1")

    assert res.ok
    assert res.status == 200

    data = res.json()
    assert data["id"] == 1
    assert "title" in data
 

5) Thực hành đủ CRUD

✅ GET list

def test_get_list(api_context):
    res = api_context.get("/posts")
    assert res.status == 200
    data = res.json()
    assert isinstance(data, list)
    assert len(data) > 0


✅ POST tạo mới

def test_create_post(api_context):
    payload = {"title": "hello", "body": "playwright", "userId": 1}
    res = api_context.post("/posts", data=payload)

    assert res.status in (200, 201)
    data = res.json()
    assert data["title"] == "hello"


✅ PUT update full

def test_update_post_put(api_context):
    payload = {"id": 1, "title": "updated", "body": "body", "userId": 1}
    res = api_context.put("/posts/1", data=payload)

    assert res.ok
    data = res.json()
    assert data["title"] == "updated"


✅ PATCH update partial

def test_update_post_patch(api_context):
    payload = {"title": "patched"}
    res = api_context.patch("/posts/1", data=payload)

    assert res.ok
    data = res.json()
    assert data["title"] == "patched"


✅ DELETE

def test_delete_post(api_context):
    res = api_context.delete("/posts/1")
    assert res.status in (200, 204)
 

6) Kiểm tra headers, content-type, và debug response

Check content-type + print debug khi fail

def test_headers(api_context):
    res = api_context.get("/posts/1")
    assert "application/json" in res.headers.get("content-type", "")

    data = res.json()
    assert data["id"] == 1


Tip debug nhanh:

if not res.ok:
    print(res.status, res.text())


7) Gửi form / gửi json / gửi query params


Query params

def test_query_params(api_context):
    res = api_context.get("/comments", params={"postId": "1"})
    assert res.ok
    data = res.json()
    assert all(item["postId"] == 1 for item in data)


Gửi JSON rõ ràng (dùng json=)

(tùy phiên bản Playwright Python, data= thường cũng auto JSON; nhưng json= giúp rõ intent hơn nếu bạn dùng async API hoặc muốn nhất quán)


8) Authentication: Token / Bearer / Basic

 Bearer token (mẫu)

@pytest.fixture
def api_with_token(playwright):
    token = "YOUR_TOKEN"
    ctx = playwright.request.new_context(
        base_url="https://api.yourapp.com",
        extra_http_headers={"Authorization": f"Bearer {token}"}
    )
    yield ctx
    ctx.dispose()


9) Ứng dụng quan trọng trong automation UI: Login bằng API → mở UI đã login

Ý tưởng

  1. Gọi API login → lấy cookie/token/session

  2. Lưu state (storageState)

  3. Tạo browser context từ state → vào UI không cần login

Flow mẫu (concept)

  • API login xong -> set cookie/localStorage -> export storage state

  • UI context dùng storage_state=...

(Phần này phụ thuộc app của bạn lưu session kiểu gì: cookie hay localStorage. Nhưng pattern thì giống nhau.)


10) Kết hợp API + UI để tăng độ tin cậy test

Pattern hay dùng

Seed data bằng API → vào UI verify hiển thị đúng
UI thao tác tạo record → gọi API verify record đúng trong backend
So sánh API vs UI khi cần chắc chắn dữ liệu không bị cache sai

Ví dụ bài toán:

  • API tạo “Employee”

  • UI vào trang Employee list

  • Verify employee mới xuất hiện


11) Best Practices (chuẩn framework)

 Tách rõ:

  • api_client.py (class gọi API)

  • conftest.py (fixture context + config)

  • tests/api/test_*.py

  • tests/ui/test_*.py

Không hard-code:

  • baseURL, token, username/password → đọc từ env/config

Luôn assert “đủ dùng”:

  • status code

  • field quan trọng

  • error message khi negative


12) Bài tập thực hành (Homework)

🧩 Bài 1: Viết 5 test API CRUD

  • GET /posts/1 (assert id)

  • GET /posts (assert list not empty)

  • POST /posts (assert title)

  • PATCH /posts/1 (assert changed)

  • DELETE /posts/1 (assert status)

🧩 Bài 2: Viết hàm helper assert_response()

Tạo function dùng lại:

  • check status

  • check content-type json

  • return json data

🧩 Bài 3: Mini framework

Tạo cấu trúc:

project/
  configs/
  pages/
  api/
    base_api.py
    posts_api.py
  tests/
    api/
      test_posts.py

Trong đó PostsAPI có method:

  • get_post(id)

  • list_posts()

  • create_post(payload)

  • update_post(id, payload)

  • delete_post(id)

Teacher

Teacher

Hà Lan

QA Automation

With over 5 years of experience in web, API, and mobile test automation, built strong expertise in designing and maintaining automation frameworks across various domains and international projects. Committed to mentoring and knowledge sharing, I provide practical guidance and proven techniques to help aspiring testers develop their skills and succeed in the automation field.

Cộng đồng Automation Testing Việt Nam:

🌱 Telegram Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 
Facebook Fanpage: Cộng đồng Automation Testing Việt Nam - Selenium
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

Chia sẻ khóa học lên trang

Bạn có thể đăng khóa học của chính bạn lên trang Anh Tester để kiếm tiền

Danh sách bài học