π RESTful Architecture & The CRUD Paradigm
Modern distributed applications rely on RESTful APIs to handle data exchange across web interfaces, native mobile apps, and microservices. The foundation of any data-driven backend service is the CRUD lifecycle: Create (HTTP POST), Read (HTTP GET), Update (HTTP PUT for complete replacements and PATCH for partial updates), and Delete (HTTP DELETE). While dedicated libraries like requests or httpx are frequently used for standalone API scripting, Playwright's APIRequestContext delivers an enterprise-grade, browser-aligned HTTP testing client. It natively manages connection pools, auto-serializes JSON payloads, shares browser storage states, and enforces web-first HTTP assertion verification via expect(response).to_be_ok().
REST CRUD MAPPING TOPOLOGY:
βββββββββββββ¬βββββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β Operation β HTTP Method β Endpoint Target Exampleβ Expected Status Code β Primary Playwright Method β
βββββββββββββΌβββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β CREATE β POST β /api/v1/customers β 201 Created / 200 OK β api.post(url, data=...) β
β READ β GET β /api/v1/customers/101 β 200 OK β api.get(url, params=...) β
β UPDATE β PUT (Full) β /api/v1/customers/101 β 200 OK β api.put(url, data=...) β
β UPDATE β PATCH (Part) β /api/v1/customers/101 β 200 OK β api.patch(url, data=...) β
β DELETE β DELETE β /api/v1/customers/101 β 200 OK / 204 No Cont β api.delete(url, params=...) β
βββββββββββββ΄βββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ
STATUS CODE TIERS:
* 200 OK βββΊ Successful Read, Update, or Delete.
* 201 Created βββΊ Successful entity creation via POST (often returns entity ID).
* 204 No Content βββΊ Successful action (common for DELETE), returning empty body.
* 400 Bad Request βββΊ Malformed JSON syntax or schema validation failure.
* 401 Unauthorized βββΊ Missing or expired authentication token.
* 404 Not Found βββΊ Target entity ID does not exist in backend database.
api.post(). Playwright automatically serializes the Python dictionary to JSON, attaches the Content-Type: application/json header, and returns the newly generated entity attributes.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
# Initialize standalone HTTP API context
api = p.request.new_context(base_url="https://httpbin.org")
new_user_payload = {
"user_id": "USR-IN-8891",
"full_name": "Aarav Sharma",
"email": "aarav.sharma@nikita-infotech.com",
"department": "Quality Engineering",
"role": "Automation Lead",
"active": True
}
# Dispatch POST request to create resource
response = api.post(
"/post",
data=new_user_payload,
headers={"X-Client-Trace-Id": "CREATE-REQ-001"}
)
# 1. Assert status indicates success
expect(response).to_be_ok()
assert response.status == 200 # In dedicated REST services, 201 is typical
# 2. Extract and assert response data
response_json = response.json()
created_data = response_json["json"]
print("CREATE Operation Verified:")
print(f" HTTP Status : {response.status} {response.status_text}")
print(f" Assigned ID : {created_data['user_id']}")
print(f" Full Name : {created_data['full_name']}")
print(f" Department : {created_data['department']}")
assert created_data["user_id"] == "USR-IN-8891"
assert created_data["active"] is True
api.dispose()
api.get(url, params=...). Assert status codes, content headers, and payload structures.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Query criteria passed as Python dictionary parameters
query_params = {
"user_id": "USR-IN-8891",
"include_permissions": "true",
"format": "json"
}
response = api.get("/get", params=query_params)
expect(response).to_be_ok()
assert response.status == 200
assert "application/json" in response.headers.get("content-type", "")
data = response.json()
queried_args = data["args"]
print("READ Operation Verified:")
print(f" Target URL : {response.url}")
print(f" Status Code : {response.status}")
print(f" Queried User ID : {queried_args['user_id']}")
print(f" Permissions Flag : {queried_args['include_permissions']}")
assert queried_args["user_id"] == "USR-IN-8891"
api.dispose()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Complete replacement payload: role upgraded and new credentials assigned
full_update_payload = {
"user_id": "USR-IN-8891",
"full_name": "Aarav Sharma",
"email": "aarav.sharma@nikita-infotech.com",
"department": "Platform Architecture",
"role": "Principal Quality Architect",
"active": True,
"security_clearance": "Level-4"
}
response = api.put("/put", data=full_update_payload)
expect(response).to_be_ok()
assert response.status == 200
updated_body = response.json()["json"]
print("UPDATE (PUT) Operation Verified:")
print(f" HTTP Status : {response.status}")
print(f" Updated Role : {updated_body['role']}")
print(f" Updated Department : {updated_body['department']}")
print(f" Security Clearance : {updated_body['security_clearance']}")
assert updated_body["role"] == "Principal Quality Architect"
assert updated_body["security_clearance"] == "Level-4"
api.dispose()
api.patch().
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Partial delta payload: only updating status and deactivation reason
delta_payload = {
"active": False,
"deactivation_reason": "Transferred to On-Site Project"
}
response = api.patch("/patch", data=delta_payload)
expect(response).to_be_ok()
assert response.status == 200
patched_data = response.json()["json"]
print("UPDATE (PATCH) Operation Verified:")
print(f" HTTP Status : {response.status}")
print(f" Updated Active Flag : {patched_data['active']}")
print(f" Deactivation Reason : '{patched_data['deactivation_reason']}'")
assert patched_data["active"] is False
assert patched_data["deactivation_reason"] == "Transferred to On-Site Project"
api.dispose()
api.delete(). Verify that the server returns a successful response code (such as 200 OK or 204 No Content) and confirms record purge.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Identify resource targeted for permanent deletion
target_id = "USR-IN-8891"
response = api.delete(
"/delete",
params={"id": target_id, "permanent": "true"},
headers={"X-Audit-Reason": "Routine Automated Test Cleanup"}
)
expect(response).to_be_ok()
assert response.status in [200, 204]
deleted_info = response.json()
print("DELETE Operation Verified:")
print(f" HTTP Status : {response.status} {response.status_text}")
print(f" Purged Resource ID : {deleted_info['args']['id']}")
print(f" Permanent Flag : {deleted_info['args']['permanent']}")
assert deleted_info["args"]["id"] == target_id
api.dispose()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
print("--- STARTING END-TO-END CRUD ENTITY LIFECYCLE ---")
# STEP 1: CREATE RESOURCE
create_res = api.post("/post", data={"name": "Cloud Sensor Node", "price": 4500})
expect(create_res).to_be_ok()
entity_data = create_res.json()["json"]
print(f"[1. CREATE] Resource generated: '{entity_data['name']}' at price βΉ {entity_data['price']}")
# STEP 2: READ RESOURCE
read_res = api.get("/get", params={"item": entity_data["name"]})
expect(read_res).to_be_ok()
fetched_name = read_res.json()["args"]["item"]
print(f"[2. READ] Queried resource successfully: '{fetched_name}'")
assert fetched_name == "Cloud Sensor Node"
# STEP 3: UPDATE RESOURCE
update_res = api.put("/put", data={"name": "Cloud Sensor Node", "price": 5200, "in_stock": True})
expect(update_res).to_be_ok()
updated_price = update_res.json()["json"]["price"]
print(f"[3. UPDATE] Updated price verified: βΉ {updated_price}")
assert updated_price == 5200
# STEP 4: DELETE RESOURCE
delete_res = api.delete("/delete", params={"item": entity_data["name"]})
expect(delete_res).to_be_ok()
print(f"[4. DELETE] Cleaned up resource: '{delete_res.json()['args']['item']}'")
print("--- COMPLETE CRUD LIFECYCLE VALIDATED WITH ZERO FLAKINESS ---")
api.dispose()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# 1. Assert 404 Not Found for non-existent endpoint
res_404 = api.get("/status/404")
assert not res_404.ok, "Expected 404 request to fail ok check"
assert res_404.status == 404
print(f"Negative Check 1 Passed: Status is {res_404.status} (Not Found)")
# 2. Assert 401 Unauthorized on protected endpoint without auth header
res_401 = api.get("/status/401")
assert res_401.status == 401
print(f"Negative Check 2 Passed: Status is {res_401.status} (Unauthorized)")
# 3. Assert 400 Bad Request on invalid request parameter
res_400 = api.get("/status/400")
assert res_400.status == 400
print(f"Negative Check 3 Passed: Status is {res_400.status} (Bad Request)")
api.dispose()
from typing import Dict, Any
from playwright.sync_api import APIRequestContext, sync_playwright, expect
class UserApiService:
"""Service Object encapsulating CRUD operations for User entities."""
def __init__(self, api_context: APIRequestContext):
self.api = api_context
self.endpoint = "/post"
def create_user(self, user_data: Dict[str, Any]):
return self.api.post(self.endpoint, data=user_data)
def get_user(self, user_id: str):
return self.api.get("/get", params={"id": user_id})
def update_user(self, user_id: str, new_data: Dict[str, Any]):
payload = {"id": user_id, **new_data}
return self.api.put("/put", data=payload)
def delete_user(self, user_id: str):
return self.api.delete("/delete", params={"id": user_id})
with sync_playwright() as p:
api_ctx = p.request.new_context(base_url="https://httpbin.org")
user_service = UserApiService(api_ctx)
# Clean, readable test steps
res = user_service.create_user({"name": "Pooja Patil", "role": "Architect"})
expect(res).to_be_ok()
print("Service Object create_user() executed successfully!")
fetch_res = user_service.get_user("USR-101")
expect(fetch_res).to_be_ok()
print("Service Object get_user() executed successfully!")
api_ctx.dispose()
PLAYWRIGHT CRUD METHODS REFERENCE MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Method / Verb β Key Keyword Arguments β Description / Primary Use Case β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β api.post(url, **kwargs) β data, form, multipart, paramsβ CREATE: Inserts new resource; auto-serializes JSON. β
β api.get(url, **kwargs) β params, headers, timeout β READ: Queries resource by ID or filters via URL params. β
β api.put(url, **kwargs) β data, form, headers β UPDATE: Full resource replacement; overwrites fields. β
β api.patch(url, **kwargs) β data, form, headers β UPDATE: Partial resource modification; delta updates. β
β api.delete(url, **kwargs) β params, headers β DELETE: Destroys target entity; clean test data removal.β
β api.head(url, **kwargs) β headers, params β Queries response headers without downloading body. β
β api.fetch(url, **kwargs) β method, data, headers β Generic HTTP dispatcher method for dynamic verbs. β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β RESPONSE ASSERTIONS & METADATA: β
β * expect(response).to_be_ok() βββΊ Auto-waits and verifies HTTP status code is between 200 and 299 inclusive. β
β * response.status βββΊ int: Returns exact HTTP status integer (e.g. 200, 201, 204, 400, 404). β
β * response.json() βββΊ Dict / List: Parses JSON response body into native Python object structure. β
β * response.text() βββΊ str: Decodes response body into UTF-8 formatted string. β
β * response.headers βββΊ Dict[str, str]: Returns dictionary of normalized lowercased response headers. β
β * response.ok βββΊ bool: Returns True if status is between 200 and 299. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ