Datatable Event Handlers#

The datatable event handler is defined through a json object in the table object. Whenever a row in the table is modified or inserted the handlers lambda function is executed. Execution may not happen in-order and may not be instant due to queueing.

Example json structure of a datatable event handler#
{
    "cp_id": "6AFADCE3A231C57CBA62719B93EC15DB",
    "name": "Custom Lambda Test",
    "lambda_function_name": "datatableCustomEventHandler_test",
    "description": "Invokes datatableCustomEventHandler_test",
    "enabled": true,
    "executing_user_id": "5C0E3E2DEF36104AC255531CA9AA9ABD"
}

Properties

cp_id

Id of the event handler.

name

Descriptive name of the event handler.

lambda_function_name

Name of the lambda function this event handler should trigger. The name MUST start with datatableCustomEventHandler

description

Short description of the purpose and behaviour of this handler function.

enabled

Enables or disables the handler. If invalid configuration is supplied the handler is disabled automatically.

executing_user_id

The handler will be executed in the context of this user. The user must belong to the same organisation as the table.

Lambda Function Implementation#

The lambda function will be called with an event that contains the row, table handler config and a session-id that belongs to the executing user.

Lambda function input#
{
    "event_doc": {
        "from_timed_job": false,
        "row_id": "6AFADCE3EE476C81CDE69B9A58891106",
        "table_id": "6AFADCE3D896BF0ADC43BACB077E68F6",
        "c0": "1",
        "c1": "pending",
        "table_event_handler_doc": {
            "cp_id": "6AFADCE3A231C57CBA62719B93EC15DB",
            "name": "Custom Lambda Test",
            "lambda_function_name": "datatableCustomEventHandler_test",
            "description": "Invokes datatableCustomEventHandler_test",
            "enabled": true,
            "executing_user_id": "5C0E3E2DEF36104AC255531CA9AA9ABD"
        },
        "reserved_until": 0
    },
    "session_id": "6AFADCE34178252FA17A9C5E1812CA0E"
}

Example python Implementation

Example of a lambda function that is used as a custom datatable event handler. The function updates a value in the given row.#
import json
import urllib.request
import urllib.error
import traceback

class CloudplanAPIClient:
    """Clean, minimal API wrapper client using standard library urllib."""

    def __init__(self, base_url: str = "https://uni.cloudplan.biz"):
        self.base_url = base_url.rstrip("/")

    def add_rows(self, table_id: str, rows: list, session_id: str) -> dict:
        """
        Sends rows to the cloudplan tables add_rows endpoint.
        API documentation: https://docs.cloudplan.net/api/tables/add_rows.html
        """
        url = f"{self.base_url}/api/tables/add_rows"
        payload = {
            "table_id": table_id,
            "rows": rows
        }

        data = json.dumps(payload).encode("utf-8")

        headers = {
            "Content-Type": "application/json",
            "session_id": session_id
        }

        req = urllib.request.Request(url, data=data, headers=headers, method="POST")

        try:
            with urllib.request.urlopen(req) as response:
                response_body = response.read().decode("utf-8")
                return json.loads(response_body) if response_body else {}
        except urllib.error.HTTPError as e:
            traceback.print_exc()
            error_body = e.read().decode("utf-8")
            raise Exception(f"HTTP error {e.code}: {error_body}")
        except urllib.error.URLError as e:
            traceback.print_exc()
            raise Exception(f"Failed to connect to API: {e.reason}")


def lambda_handler(event, context):
    """
    AWS Lambda handler function: datatableCustomEventHandler_test
    Expected input payload structure:
        {
            "event_doc": { ... },
            "session_id": "..."
        }
    """
    # 1. Extract inputs from the payload
    event_doc = event.get("event_doc", {})
    session_id = event.get("session_id", "")

    if not event_doc or not session_id:
        return {
            "statusCode": 400,
            "body": json.dumps({"error": "Missing 'event_doc' or 'session_id' in payload."})
        }

    # Extract table_id and row_id from the event document structure
    table_id = event_doc.get("table_id", "")
    row_id = event_doc.get("row_id", "")

    if not table_id or not row_id:
        return {
            "statusCode": 400,
            "body": json.dumps({"error": "Event document missing 'table_id' or 'row_id'."})
        }

    # 2. Define the row modifications/changes
    # Adjust the target column ('c1', etc.) and value as needed for your workflow
    rows_update = {
        "row_id": row_id,
        "c1": "processed_by_lambda"  # Example field change
    }

    # 3. Use the API wrapper client to commit the updates
    client = CloudplanAPIClient()

    try:
        api_result = client.add_rows(
            table_id=table_id,
            rows=[rows_update],
            session_id=session_id
        )

        return {
            "statusCode": 200,
            "body": json.dumps({
                "message": "Successfully updated row via custom event handler lambda.",
                "result": api_result
            })
        }

    except Exception as e:
        return {
            "statusCode": 500,
            "body": json.dumps({"error": str(e)})
        }