CRUD API OPERATIONS IN PLAYWRIGHT PYTHON

Master complete RESTful service automation in Playwright with Python: executing Create (POST), Read (GET), Update (PUT & PATCH), and Delete (DELETE) operations, validating JSON schemas, managing bearer authentication, asserting HTTP status codes, and executing end-to-end entity lifecycle flows.

πŸ”„ 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().

1. RESTful CRUD HTTP Mapping & Status Code Conventions
Standard REST architecture maps the four primary persistent data operations to specific HTTP verbs and returns semantic status codes indicating success or failure.
CRUD Architectural Mapping Matrix
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.
Architectural Standard: Playwright API calls automatically handle SSL handshakes, connection pooling, and payload encoding without external third-party dependencies.
Real-Time Example 1: CREATE Operation via api.post() (Entity Insertion)
Send an entity creation payload using api.post(). Playwright automatically serializes the Python dictionary to JSON, attaches the Content-Type: application/json header, and returns the newly generated entity attributes.
Python (Entity Creation with api.post)
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()
Output: CREATE Operation Verified: HTTP Status : 200 OK Assigned ID : USR-IN-8891 Full Name : Aarav Sharma Department : Quality Engineering
Real-Time Example 2: READ Operation via api.get() (Querying Records)
Fetch single records by entity ID or retrieve filtered datasets using query parameters with api.get(url, params=...). Assert status codes, content headers, and payload structures.
Python (Entity Retrieval with api.get)
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()
Output: READ Operation Verified: Target URL : https://httpbin.org/get?user_id=USR-IN-8891&include_permissions=true&format=json Status Code : 200 Queried User ID : USR-IN-8891 Permissions Flag : true
Real-Time Example 3: UPDATE (Full Replacement) via api.put()
Under RESTful conventions, an HTTP PUT completely replaces the existing target resource with the new payload. Execute full resource updates and verify the modified attributes.
Python (Full Resource Update with api.put)
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()
Output: UPDATE (PUT) Operation Verified: HTTP Status : 200 Updated Role : Principal Quality Architect Updated Department : Platform Architecture Security Clearance : Level-4
Real-Time Example 4: UPDATE (Partial Delta Modification) via api.patch()
Unlike PUT, an HTTP PATCH modifies only the specified fields without affecting unchanged attributes. Dispatch delta updates using api.patch().
Python (Partial Update with 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()
Output: UPDATE (PATCH) Operation Verified: HTTP Status : 200 Updated Active Flag : False Deactivation Reason : 'Transferred to On-Site Project'
Real-Time Example 5: DELETE Operation via api.delete() (Entity Teardown)
Remove an entity from the database using api.delete(). Verify that the server returns a successful response code (such as 200 OK or 204 No Content) and confirms record purge.
Python (Resource Deletion with api.delete)
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()
Output: DELETE Operation Verified: HTTP Status : 200 OK Purged Resource ID : USR-IN-8891 Permanent Flag : true
Real-Time Example 6: End-to-End Dynamic CRUD Lifecycle Test Suite
Chain all four operations sequentially within a single automated test scenario: Create an entity, Read and verify it, Update its attributes, and Delete it to guarantee zero test data pollution.
Python (Full End-to-End CRUD Lifecycle Flow)
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()
Output: --- STARTING END-TO-END CRUD ENTITY LIFECYCLE --- [1. CREATE] Resource generated: 'Cloud Sensor Node' at price β‚Ή 4500 [2. READ] Queried resource successfully: 'Cloud Sensor Node' [3. UPDATE] Updated price verified: β‚Ή 5200 [4. DELETE] Cleaned up resource: 'Cloud Sensor Node' --- COMPLETE CRUD LIFECYCLE VALIDATED WITH ZERO FLAKINESS ---
Real-Time Example 7: Handling Negative Scenarios & Error Validations
Assert that the API returns appropriate client-side HTTP error codes (400 Bad Request, 401 Unauthorized, 404 Not Found) when presented with invalid credentials or malformed payloads.
Python (Negative Response Assertions)
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()
Output: Negative Check 1 Passed: Status is 404 (Not Found) Negative Check 2 Passed: Status is 401 (Unauthorized) Negative Check 3 Passed: Status is 400 (Bad Request)
Real-Time Example 8: Modular CRUD Page/Service Object Architecture
Encapsulate API endpoints inside clean Service Object Model classes in Python, promoting code reuse across backend integration tests and frontend UI setup helpers.
Python (Service Object Model Pattern)
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()
Output: Service Object create_user() executed successfully! Service Object get_user() executed successfully!
Real-Time Example 9: CRUD Methods & Parameters Reference Matrix
A comprehensive reference summary of methods, signatures, and payload arguments used for executing RESTful CRUD operations in Playwright Python.
CRUD API Methods Reference Matrix
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.                                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Isolate your end-to-end test scenarios by utilizing api.post() for instantaneous test data generation, and always execute api.delete() in test teardown blocks to maintain clean database states.