Skip to content

Common Patterns

A cookbook of recurring architectural, access control, and operational patterns for Kirak applications.


Ownership: Users Can Only See Their Own Records

Section titled “Ownership: Users Can Only See Their Own Records”

Use an RLS condition to automatically scope queries and operations to the authenticated caller’s user ID. In models/posts.json:

{
"table": "posts",
"schema": {
"user_id": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "text" }
},
"access": {
"fetch": [{ "role": "user", "condition": "user_id = {user_id}" }],
"create": [{ "role": "user", "condition": "user_id = {user_id}" }],
"update": [{ "role": "user", "condition": "user_id = {user_id}" }],
"delete": [{ "role": "user", "condition": "user_id = {user_id}" }]
}
}

On create, Kirak automatically injects user_id = <caller's JWT user_id> into the SQL INSERT statement – the caller does not need to send it in the request body and cannot forge an ownership assignment.


Provide multiple role rules per operation. In models/orders.json:

{
"table": "orders",
"schema": {
"user_id": { "type": "integer" },
"total": { "type": "decimal" },
"status": { "type": "string" }
},
"access": {
"fetch": [
{ "role": "admin" },
{ "role": "user", "condition": "user_id = {user_id}" }
],
"update": [
{ "role": "admin" },
{ "role": "user", "condition": "user_id = {user_id}" }
],
"delete": [
{ "role": "admin" }
]
}
}
  • Admins match the unrestricted { "role": "admin" } rule and can fetch/update any order.
  • Regular users match the row-level condition and can only fetch/update their own orders.
  • Delete is restricted to admins only.

Scope records by organization_id or tenant_id. Because standard access tokens carry only sub, email, and role, tenant variables come from custom identity contexts set in your route handlers:

{
"table": "invoices",
"schema": {
"organization_id": { "type": "integer" },
"amount": { "type": "decimal" }
},
"access": {
"fetch": [
{ "role": "user", "condition": "organization_id = {organization_id}" },
{ "role": "admin", "condition": "organization_id = {organization_id}" }
],
"create": [
{ "role": "user", "condition": "organization_id = {organization_id}" },
{ "role": "admin", "condition": "organization_id = {organization_id}" }
]
}
}

On Kirak’s default REST routes, {organization_id} resolves to NULL (failing closed and returning no rows). Serve tenant queries from custom endpoints that resolve the caller’s organization:

from kirak import Caller, user_context
async def caller_with_org(caller: dict) -> dict:
membership = await kirak.fetch("memberships", {"user_id": caller["user_id"]}, limit=1)
rows = membership.get("data") or []
org_id = rows[0]["organization_id"] if rows else None
return {**caller, "organization_id": org_id}
@app.get("/org/invoices")
async def org_invoices(caller: Caller):
with user_context(await caller_with_org(caller)):
return await kirak.fetch("invoices")

Enable soft delete in models/articles.json:

{
"table": "articles",
"soft_delete": true,
"schema": {
"title": { "type": "string" },
"content": { "type": "text" }
}
}
  • DELETE /articles/delete?id=1 sets deleted_at = NOW() – records are automatically hidden from all subsequent fetch, search, count, and exists queries.
  • PATCH /articles/restore with body {"where": {"id": 1}} clears deleted_at, restoring record visibility.
  • destroy (DELETE /articles/destroy?id=1) returns 400 VALIDATION_ERROR for all standard roles. Only system role can permanently destroy rows on a soft-delete table.

Use an auth after-hook to trigger notifications:

def on_kirak_ready(kirak):
@kirak.auth.hook("after_register")
async def send_welcome_email(result):
if result.get("status") != "success":
return result
user = result["data"]["user"]
try:
await kirak.notifications.send_email({
"to": user["email"],
"subject": "Welcome to Acme",
"text_body": f"Hi {user.get('first_name', 'there')}, welcome to our platform!",
})
except Exception as e:
# Log failure without blocking user registration
kirak.logger.error(f"Failed to send welcome email: {e}")
return result

Handle payment webhooks safely using the payments after-hook:

def on_kirak_ready(kirak):
@kirak.payments.hook("after_webhook")
async def fulfil_order(result):
data = result.get("data", {})
if data.get("event") != "payment_completed":
return result
# Webhook hooks execute as role 'system': orders.access.update must list {"role": "system"}
await kirak.update("orders", {"payment_transaction_id": data["transaction_id"]}, {"status": "paid"})
return result

[!IMPORTANT] Because incoming webhooks originate from external providers (e.g. Stripe, Razorpay) without a user JWT, webhook hooks execute in the system context. Target models must explicitly grant access to {"role": "system"}.


Create cron jobs using the scheduler module:

from datetime import date
from kirak.core.context import as_system
def on_kirak_ready(kirak):
@kirak.scheduler.cron("0 0 * * *", name="nightly_revenue_report")
async def nightly_report(payload):
# Scheduled jobs have no request caller: execute inside as_system() block
with as_system():
result = await kirak.fetch("orders", {
"status": "completed",
"created_at__gte": date.today().isoformat(),
}, limit=10000)
total = sum(r["amount"] for r in result.get("data", []))
await kirak.notifications.send_email({
"to": "finance@acme.example",
"subject": f"Daily Revenue: ${total:.2f}",
"text_body": f"{len(result.get('data', []))} orders processed today.",
})

Upload images and generate resized variants asynchronously in the background. Requires "thumbnail_mode": "background" in the storage section of kirak.json:

from fastapi import BackgroundTasks, Depends, UploadFile
from kirak import Caller
@app.post("/upload-avatar")
async def upload_avatar(file: UploadFile, background_tasks: BackgroundTasks,
caller: Caller):
file_bytes = await file.read()
# Executes as caller; stored under "{user_id}/avatars/avatar.jpg"
return await kirak.storage.upload_image({
"file": file_bytes,
"filename": file.filename,
"path": "avatars/avatar.jpg",
"thumbnails": [
{"name": "sm", "width": 64, "height": 64},
{"name": "md", "width": 128, "height": 128},
],
"background_tasks": background_tasks,
})

Generated thumbnails are placed under the deterministic path thumbnails/<filename>/<size>.<ext> and pre-computed URLs are returned immediately in the response.


Validating Input Before It Hits the Database

Section titled “Validating Input Before It Hits the Database”

Use a synchronous before_* hook to reject invalid operations before SQL execution. Synchronous hooks that raise a KirakException abort the request and return the standard error envelope with the exception’s status code:

from kirak.core.exceptions import ValidationError
def on_kirak_ready(kirak):
@kirak.on("bookings").hook("before_create")
def validate_booking_dates(payload):
data = payload.get("data", {})
start = data.get("start_date")
end = data.get("end_date")
if start and end and start >= end:
raise ValidationError("end_date must be strictly after start_date")
return payload

[!TIP] Use synchronous hooks (def) when you need to validate complex business constraints and reject the operation. Use asynchronous hooks (async def) for non-blocking side effects and payload enrichment.


Allow public anonymous access to read endpoints while requiring authentication for write operations. In models/articles.json:

{
"table": "articles",
"schema": {
"title": { "type": "string" },
"content": { "type": "text" }
},
"access": {
"fetch": [{ "role": "*" }],
"search": [{ "role": "*" }],
"count": [{ "role": "*" }],
"create": [{ "role": "editor" }, { "role": "admin" }],
"update": [{ "role": "editor" }, { "role": "admin" }],
"delete": [{ "role": "admin" }]
}
}

The wildcard rule {"role": "*"} matches any caller, including unauthenticated guest requests.


Mount custom lightweight routes alongside Kirak’s generated API:

from fastapi import APIRouter
def on_kirak_ready(kirak):
router = APIRouter()
@router.get("/health")
async def health():
return {"status": "ok", "version": "1.0.0"}
kirak.app.include_router(router)