Hooks & Events
Hooks are the primary extension point in Kirak. Every CRUD operation, authentication event, payment transaction, and notification lifecycle event emits before_* and after_* hooks.
Custom business logic, validation rules, audit logging, and external service triggers belong in hooks—never in framework runtime code.
Registration Window
Section titled “Registration Window”All hooks must be registered inside the on_kirak_ready callback.
This lifecycle callback executes after database connectivity is verified but before FastAPI routers are mounted, ensuring every hook is guaranteed to be in place for the very first incoming request:
from kirak import create_kirak_app
def on_kirak_ready(kirak): @kirak.on("orders").hook("after_create") async def process_order(result): order_id = result["data"]["id"] print(f"Order #{order_id} created successfully!") return result
app = create_kirak_app( models_path="./models/", on_kirak_ready=on_kirak_ready,)Warning: Never attempt to register hooks at import time or after
create_kirak_app()has mounted routers. Hooks registered late may miss initial requests or cause race conditions.
Where the Code Lives
Section titled “Where the Code Lives”A project made by kirak new keeps all its Python in the src/ package: hooks, agent tools, custom routes, scheduler tasks and custom providers. main.py passes register() from src/__init__.py as on_kirak_ready, and register() calls the register(kirak) of each module:
my-api/+-- main.py # create_kirak_app(models_path="./models/", on_kirak_ready=register)+-- src/ +-- __init__.py # def register(kirak): hooks.register(kirak); tools.register(kirak) ... +-- hooks.py +-- tools.py # add modules as needed: routes.py, tasks.py, providers.pysrc is a plain package imported from the project root, so imports are from src.hooks import ..., not from hooks import .... A module that grows can become a package (src/hooks.py -> src/hooks/__init__.py) without changing its imports.
This layout is a default, not a requirement. Kirak discovers no Python by location: it runs what on_kirak_ready registers, so the code can live in any importable module or package.
Hook Execution & Error Boundaries
Section titled “Hook Execution & Error Boundaries”Sync and async hooks have fundamentally different error boundaries:
sequenceDiagram autonumber participant Client as Client Request participant Engine as CRUD Engine participant Hooks as Hook Pipeline participant DB as Database Transaction
Client->>Engine: POST /{model}/create Engine->>Hooks: Execute before_create hooks (Serial)
alt Sync Hook (def) raises an Exception Hooks-->>Engine: Raises ValidationError / PermissionDenied Engine-->>Client: 400 / 403 / 500 Abort Request (Guards & validation) else Async Hook (async def) fails or times out Hooks->>Hooks: Log warning & continue pipeline with previous payload end
Engine->>DB: Open Transaction & Execute SQL (RLS Enforced) DB-->>Engine: Record Committed
Engine->>Hooks: Execute after_create hooks (Serial) alt Async Hook executes side effects Hooks->>Hooks: Dispatches emails, pushes, or background tasks end
Engine-->>Client: 200 OK (Uniform Response Envelope)Sync vs. Async Comparison:
Section titled “Sync vs. Async Comparison:”| Characteristic | Sync Hook (def) |
Async Hook (async def) |
|---|---|---|
| Can Abort Operation? | Yes. Raising an exception halts the hook chain and aborts the request immediately. | No. Exceptions and timeouts are logged and skipped; the pipeline continues with the previous payload. |
| Best Used For | Input validation, business invariant guards, rejecting invalid states. | Asynchronous side effects (emails, push notifications, audit logging, webhook dispatch). |
| Timeout Limit | None (blocks execution). | Controlled by hook_timeout_seconds in kirak.json (default: 5.0 seconds). |
| Execution Order | Serial in order of registration. | Serial in order of registration (awaited sequentially). |
Rejecting an Operation with Sync Hooks
Section titled “Rejecting an Operation with Sync Hooks”To block an invalid operation before any database write occurs, raise a standard KirakException subclass from a sync hook:
from kirak.core.exceptions import ValidationError
def on_kirak_ready(kirak): @kirak.on("reservations").hook("before_create") def validate_reservation_dates(payload): data = payload.get("data", {}) start_date = data.get("start_date") end_date = data.get("end_date")
if start_date and end_date and start_date >= end_date: raise ValidationError("end_date must be strictly after start_date")
return payload # Always return payload to continue pipelineIf the validation check fails, Kirak halts the pipeline and returns a clean 400 VALIDATION_ERROR response envelope:
{ "statusCode": 400, "status": "error", "error": "VALIDATION_ERROR", "message": "end_date must be strictly after start_date", "data": null}Registration Syntaxes
Section titled “Registration Syntaxes”Kirak supports two registration styles: inline decorators and structured hook classes.
1. Function Decorators
Section titled “1. Function Decorators”Best for concise hooks:
# Model CRUD hook@kirak.on("posts").hook("after_create")async def after_post_create(result): return result
# Single-purpose module hook (auth, payments, notifications)@kirak.auth.hook("after_login")async def after_login(result): return result2. Hook Classes (Recommended for Production)
Section titled “2. Hook Classes (Recommended for Production)”Group related hooks into dedicated classes to keep your codebase modular:
class OrderHooks: @classmethod def register(cls, kirak): @kirak.on("orders").hook("before_create") def validate_inventory(payload): # Sync guard return payload
@kirak.on("orders").hook("after_create") async def send_invoice(result): # Async side effect return resultRegister one or multiple hook classes from register() in src/__init__.py:
from src.order_hooks import OrderHooksfrom src.user_hooks import UserHooks
def register(kirak): kirak.register_hook_classes(OrderHooks, UserHooks)Payload vs. Result
Section titled “Payload vs. Result”Hooks receive exactly one argument and must return a value:
| Hook Phase | Argument | Description |
|---|---|---|
before_* |
payload |
The incoming request parameters dictionary; the record being written is payload["data"]. Return modified or unmodified payload. |
after_* |
result |
The outgoing canonical response envelope dictionary. Return modified or unmodified result. |
An after_* hook gets the operation’s result, not the record: ids and counts (see the Event Reference). A hook that needs the record’s fields fetches them by id. This is the same for a single-record write, a write that changed many rows, and a bulk write:
@kirak.on("orders").hook("after_update")async def notify_on_ship(result): ids = result["data"]["id"] # one id, or a list when the update changed several rows ids = ids if isinstance(ids, list) else [ids] orders = await kirak.fetch("orders", {"id__in": ids}) for order in orders["data"]: if order["status"] == "shipped": await kirak.notifications.send_email({"to": order["buyer_email"], "subject": "Your order shipped"}) return resultThe fetch runs as the caller, with the caller’s read and row rules. Inside with as_system(): (from kirak.core.context) it reads every field of every row.
Return Contract: Always return the argument received (or return
Noneto pass it through unchanged). Failing to return a value will result inNonebeing forwarded down the chain.
Setting fields the caller may not write
Section titled “Setting fields the caller may not write”A before_create, before_update or before_upsert hook can set fields that the caller’s role may not write under access.fields – a computed total, a value copied from a related record, a status the app manages. Kirak compares payload["data"] before and after the hooks: a field the hooks added or changed is written even when the caller’s write rules exclude it, and is validated like any other field. A value the caller sent for such a field, and which no hook changed, is still refused. This holds over REST, the Python facade and GraphQL.
@kirak.on("orders").hook("before_create")async def price_order(payload): data = payload["data"] product = (await kirak.fetch("products", {"id": data["product_id"]}))["data"][0] payload["data"] = {**data, "total_price": product["price"] * data["quantity"]} return payloadWith "total_price": {"write": []} in the model’s access.fields, buyers cannot send a price, and every order still gets one. A hook cannot use this to move a row to another owner: an owner field fixed by the operation’s row rule ("condition": "buyer_id = {user_id}") is refused when it differs from the caller’s.
Event Reference Directory
Section titled “Event Reference Directory”1. Model CRUD Events
Section titled “1. Model CRUD Events”Registered on model names via kirak.on("model_name").hook("event"):
| Event | Trigger Point | Hook Argument |
|---|---|---|
before_fetch / after_fetch |
Querying records | payload (where, and the options sent: limit, order_by, …) / result (contains data: [...]) |
before_search / after_search |
Full-text searching | payload (search, where, options) / result |
before_count / after_count |
Counting records | payload (where, group_by) / result (contains data.count) |
before_create / after_create |
Inserting record | payload (data: the new record) / result (data: {"id": ...}; a bulk create: inserted_ids, inserted_count) |
before_update / after_update |
Updating record | payload (where, data: the changes) / result (data: updated_count and id, a list when several rows changed; a bulk update: updated_ids) |
before_delete / after_delete |
Soft-deleting record | payload (where, e.g. {"where": {"id": 1}}) / result (data: deleted_count) |
before_destroy / after_destroy |
Hard-deleting record | payload (where) / result (data: deleted_count) |
before_restore / after_restore |
Restoring soft-deleted record | payload (where, data) / result (data: restored_count) |
No after_* hook gets the record. After a create or update, fetch it by the ids in result["data"]. A delete, destroy or restore result has counts only, so a hook that needs the row (to notify its owner, to cascade) fetches it in the before_* hook, while it can still be read.
2. Auth Events
Section titled “2. Auth Events”Registered via @kirak.auth.hook("event"):
| Event | Trigger Point |
|---|---|
before_login / after_login |
User credential authentication |
before_register / after_register |
A new account from /auth/register, a first phone-code sign-in or a first social sign-in; method says which (Who Can Sign Up) |
before_refresh_token / after_refresh_token |
Token renewal and rotation |
before_logout / after_logout |
Session termination |
before_change_password / after_change_password |
Authenticated password change |
before_request_reset_password / after_request_reset_password |
Forgot password email dispatch |
before_mfa_challenge / after_mfa_challenge |
Second-factor TOTP verification |
before_verify_otp / after_verify_otp |
Phone SMS code verification |
purge_account |
Scheduled account deletion |