Skip to content

CRUD Operations

Every model you define automatically gets 15 HTTP endpoints – with zero boilerplate code. All operations execute through a unified, hardened pipeline: authentication dependency -> permission and access check -> before hooks -> SQL operation -> after hooks -> standard response envelope.

flowchart LR
A["HTTP Request"] --> B["Auth Dependency<br/>(Bearer / Cookie / Key)"]
B --> C["Origin & Rate Limit<br/>Headers Evaluated"]
C --> D["Access Check<br/>(RBAC + RLS Grammar)"]
D --> E["Before Hooks<br/>(Sync Validation / Async)"]
E --> F["DB Operation<br/>(Dialect SQL Builder)"]
F --> G["After Hooks<br/>(Enrichment / Side Effects)"]
G --> H["Response Envelope<br/>(statusCode + data)"]

Operation Method Path Description
fetch GET /{model}/fetch Query records with filters, field selection, ordering, and pagination
search GET /{model}/search Free-text search across all searchable: true fields
count GET /{model}/count Count matching records or group counts by field
exists GET /{model}/exists Fast boolean existence check
fetch, search, count, exists POST /{model}/<operation> The same read, with filters and options in a JSON body
create POST /{model}/create Insert a single record or bulk batch
update PUT /{model}/update Update records matching a required where filter or bulk batch
upsert PUT /{model}/upsert Insert the record its key names, or update it when it exists
delete DELETE /{model}/delete Soft delete records (sets deleted_at)
destroy DELETE /{model}/destroy Hard delete records permanently from the database
restore PATCH /{model}/restore Un-soft-delete records (clears deleted_at)
graphql POST /graphql Multi-model queries, joins, aggregates, and atomic mutations

All paths are relative to the optional routes.crud_prefix in kirak.json. Example with "crud_prefix": "/api/v1": /api/v1/posts/fetch.

  • Custom Slugs: If a model defines "slug": "custom-path", all CRUD endpoints are mounted at /custom-path/*. Direct access using the internal model name (/posts/fetch), or its singular or plural form (/post/fetch), returns 404 NOT_FOUND.
  • Internal Models: Models marked "internal": true are completely excluded from the HTTP router, returning 404 NOT_FOUND on all REST endpoints and blocked from public GraphQL root queries. They are accessible only via server-side Python facade calls (kirak.fetch(), etc.).
  • Rate Limit Headers: Every CRUD endpoint evaluates rate limits and returns quota tracking headers:
    • X-RateLimit-Limit: Maximum requests permitted in the current window.
    • X-RateLimit-Remaining: Requests remaining in the current window.
    • X-RateLimit-Reset: UTC epoch timestamp when the quota resets.

Every operation takes the same three parts: the filters (where), the payload (data), and the operation’s options.

Operation Python facade HTTP
fetch kirak.fetch(model, where, limit=, offset=, page=, order_by=, order=, select=) GET query string, or POST body
search kirak.search(model, term, where, <fetch options>) GET ?search=..., or POST body
count kirak.count(model, where, group_by=) GET query string, or POST body
exists kirak.exists(model, where) GET query string, or POST body
create kirak.create(model, data, batch_size=, chunk_size=) body {"data": ...}
update kirak.update(model, where, data) body {"where": {...}, "data": {...}}
upsert kirak.upsert(model, where, data) body {"where": {...}, "data": {...}}
delete, destroy kirak.delete(model, where, chunk_size=) query string
restore kirak.restore(model, where, data=None) body {"where": {...}, "data": {...}}

In a query string, the operation’s options (limit, offset, page, order_by, order, select, search, group_by, chunk_size) are read as options and every other key is a filter. In a JSON body, filters go under where and field values under data; any other key that is not one of the operation’s options returns 400 VALIDATION_ERROR (Unknown parameter(s) for fetch: status. Filters go under 'where'.), so a misplaced filter is never dropped. before_* hooks receive the same dict: {"where": {...}, "data": ..., <options>}.


Every CRUD and GraphQL operation returns the same shape. The HTTP status line always equals statusCode. See Response Envelope for the full contract.

{
"statusCode": 200,
"status": "success",
"message": "Records fetched successfully",
"data": [...],
"pagination": {
"limit": 20,
"page": 1,
"offset": 0,
"total": 156,
"total_pages": 8,
"has_more": true
}
}

pagination is only present when page or offset is passed to fetch or search. There is no token key.

Error envelope (HTTP status == statusCode):

{
"statusCode": 403,
"status": "error",
"error": "PERMISSION_DENIED",
"message": "Role 'user' is not authorized to destroy 'posts'",
"data": null
}

error is the stable machine code – branch on it, not on message. details is added only when the failure carries structured context.


Filters are the where dict of a facade call (kirak.fetch("posts", {"status": "active"}, limit=20)) or of a JSON body, and the non-option keys of a query string (GET /posts/fetch?status=active&limit=20). Keys follow the field__operator convention:

Suffix SQL operator Example
(none) = {"status": "active"}
__ne != {"status__ne": "deleted"}
__gte >= {"age__gte": 18}
__gt > {"price__gt": 100}
__lte <= {"score__lte": 99}
__lt < {"stock__lt": 10}
__like LIKE {"name__like": "john"} – auto-wrapped in %...%. Explicit % wildcards ("john%", "%john") are preserved as given.
__ilike Case-insensitive LIKE {"name__ilike": "john"} – PostgreSQL native ILIKE, MySQL/SQLite fallback to LOWER(field) LIKE LOWER(...). Explicit % preserved.
__in IN (...) {"id__in": [1,2,3]}, "1,2,3" or "[1,2,3]"
__not_in NOT IN (...) {"status__not_in": ["draft","archived"]}
__between BETWEEN ... AND ... {"price__between": [10, 50]} or "10,50" (requires exactly 2 items)
__is_null IS NULL {"deleted_at__is_null": true} – value ignored
__is_not_null IS NOT NULL {"photo__is_not_null": true}

All REST filters are combined with AND. All values are parameterized – never interpolated into SQL strings.

[!IMPORTANT] REST requests strictly prohibit or and or_groups query parameters. Any REST call that attempts to pass an or key raises a 400 VALIDATION_ERROR ('or' is only available on GraphQL fetch and search). To query with disjunctive (OR) logic, use the /graphql endpoint.

Every operation, read or write, rejects a filter key that is not a field of the model (with or without an operator suffix) with 400 VALIDATION_ERROR (Unknown filter field(s): ...), so a typo such as statuss=open cannot widen a read or a write. A field named like an option (limit, page, …) cannot be filtered in a query string; send the read as POST with the filter under where. A filter on a field the caller’s role cannot read returns 403 PERMISSION_DENIED.

Filter values are coerced by the field’s schema type, ensuring identical matching behavior across MySQL, PostgreSQL, and SQLite:

  • integer fields require whole numbers.
  • float / decimal require valid numeric representations.
  • boolean accepts true, false, 1, 0.
  • string fields always compare as exact text (code=007 matches "007", not 7).
  • Date and timestamp fields (created_at, updated_at, deleted_at, datetime, date) require ISO-8601 strings ("2026-09-01", "2026-09-01T12:00:00Z"). Non-conforming strings ("today", "2026-13-01") return 400 VALIDATION_ERROR.

Query records with filters, field selection, ordering, and pagination.

GET /{model}/fetch

Parameter Type Default Description
<field>__<operator> any – Filter conditions (see Filter Operators)
limit int 10 Records to return, at least 1. Capped at model’s max_limit (default 1000). Below 1 is 400 VALIDATION_ERROR.
page int – Page number (1-based; 0 or omitted means no page). Triggers pagination metadata. Negative is 400 VALIDATION_ERROR.
offset int – Row offset, 0 or more. Alternative to page. Negative is 400 VALIDATION_ERROR.
order_by string default_order Field to sort by. Comma-separated for multiple: "name,created_at". Prefix with - for DESC: "-created_at". A field the model does not declare, or the role cannot read, returns 400 VALIDATION_ERROR.
order string ASC Default direction for order_by fields without a prefix (ASC or DESC).
select string/array all readable fields Comma-separated list or JSON array of fields to return. Requesting an unauthorized field returns 403.

[!NOTE] If a model schema marks a field "sortable": false (such as large JSON or TEXT columns), attempting to sort by it returns 400 VALIDATION_ERROR (Field(s) not sortable: ...).

Examples:

Terminal window
# Basic fetch with filters
GET /posts/fetch?status=published&user_id=42
# Pagination
GET /posts/fetch?page=2&limit=20
# Date range + ordering
GET /orders/fetch?created_at__gte=2025-01-01&order_by=-created_at&limit=50
# Select specific fields
GET /posts/fetch?select=id,title,created_at

The same read as POST, with the filters under where:

POST /posts/fetch
{"where": {"status": "published", "user_id": 42}, "limit": 20, "order_by": "-created_at"}

Via Python facade:

await kirak.fetch("posts", {
"status": "published",
"user_id": 42,
}, limit=20, page=1, order_by="-created_at", select=["id", "title", "created_at"])

Full-text search across all fields marked "searchable": true in the model schema.

GET /{model}/search

Parameter Type Description
search string Text to search for. Applied as case-insensitive LIKE %term% across all searchable fields.
<field>__<operator> any Additional filters combined with the search term.
limit int Max records. Default 10.
page / offset int Pagination parameters, as in fetch.
order_by string Sort field.
order string Sort direction (ASC / DESC).
select string/array Fields to return, as in fetch.
Terminal window
GET /posts/search?search=kirak+runtime&limit=5

A model with no searchable: true field readable by the caller’s role returns 403 PERMISSION_DENIED (No searchable fields available for role ...).


Count records matching filters without fetching full row data.

GET /{model}/count

Terminal window
GET /orders/count?status=pending
# -> {"statusCode": 200, "status": "success", "data": {"count": 42}}

Pass group_by to get counts grouped by a field:

Terminal window
GET /orders/count?group_by=status
# -> {"statusCode": 200, "status": "success", "data": {"pending": 12, "shipped": 30}}

Grouped results are capped at 1,000 groups (GROUP BY ... LIMIT 1000).


High-performance boolean existence check.

GET /{model}/exists

Terminal window
GET /users/exists?email=alice@example.com
# -> {"statusCode": 200, "status": "success", "data": {"exists": true}}

Insert a single record. Returns the new record’s id.

POST /{model}/create

{
"data": {
"title": "Hello Kirak",
"content": "My first post",
"user_id": 1
}
}

Response:

{
"statusCode": 200,
"status": "success",
"message": "posts created successfully",
"data": { "id": 42 }
}

Ownership injection: If the model’s access.create rule includes an ownership condition like "user_id = {user_id}", Kirak automatically injects user_id from the caller’s JWT claims into the INSERT statement. The caller cannot override this value.

Pass data as a list to insert multiple records in a single transactional batch:

{
"data": [
{ "title": "Post 1", "user_id": 1 },
{ "title": "Post 2", "user_id": 1 }
],
"chunk_size": 500,
"batch_size": 200
}
Parameter Description
chunk_size Records validated and inserted per memory chunk. Default: all records.
batch_size Records per single INSERT statement. Automatically capped for the database parameter limit (PostgreSQL 32,767, SQLite 32,766 total parameters).

Validation runs before anything is written. A record that fails validation or duplicates a unique field is recorded in failed_records; valid records are inserted. If all records fail, the endpoint returns 400 VALIDATION_ERROR. Database-level execution errors roll back all chunks in the transaction.


Update records matching a required filter.

PUT /{model}/update

{
"where": { "id": 42 },
"data": { "title": "Updated Title", "status": "published" }
}

where is mandatory. A non-bulk update without where returns 400 VALIDATION_ERROR (Update operation requires 'where' filters for safety). Row-level ownership conditions (e.g. "user_id = {user_id}") are automatically appended to the WHERE clause.

Returns {updated_count, id}: id is the updated row ID when a single record changed, or an array of updated IDs when multiple changed.

Pass data as a list of records, where each record includes its id:

{
"data": [
{ "id": 1, "status": "active" },
{ "id": 2, "status": "inactive", "title": "Renamed" }
],
"chunk_size": 500,
"batch_size": 200
}

[!NOTE] Roles whose update access specifies a row-level condition ("condition": "user_id = {user_id}") cannot execute bulk updates (403 PERMISSION_DENIED); update records individually instead.


Insert the record where names, or update it when it exists, in one atomic INSERT ... ON CONFLICT.

PUT /{model}/upsert

{
"where": { "email": "alice@example.com" },
"data": { "name": "Alice Smith", "role": "admin" }
}

where is the row’s key: equality on exactly the primary key (id), one field marked "unique": true, or the columns of one unique entry in indexes. Any other where returns 400 VALIDATION_ERROR, as does a key field repeated in data. An insert writes where and data together; an update writes data.

On a model with soft_delete, a key that belongs to a soft-deleted row is refused with the same 400 VALIDATION_ERROR that create gives for an existing key (... already exists when the key is a unique field). The deleted row is neither updated nor revived; use restore for that.

A write to a unique field reveals whether the value exists. Creating or updating a row with a value that is already taken fails, whether or not the caller can read the row that holds it, and a soft-deleted row still holds its value. Kirak does not hide this, because the database refuses the duplicate insert regardless of any pre-check. Do not put a value in a unique field if callers must not learn that it exists. See Security Hardening.

[!NOTE] Unlike create and update, upsert does not automatically update updated_at on conflict unless updated_at is explicitly provided in data.


Soft-delete records by setting deleted_at. Available only on models with "soft_delete": true.

DELETE /{model}/delete

Filters go in the query string; at least one is required:

Terminal window
DELETE /posts/delete?id=42

A filter on id__in alone runs in chunks of chunk_size (default bulk_chunk_size in kirak.json):

Terminal window
DELETE /posts/delete?id__in=1,2,3,4,5&chunk_size=500

Soft-deleted records are automatically excluded from all subsequent fetch, search, count, and exists queries.


Permanently remove records from the database.

DELETE /{model}/destroy

Terminal window
DELETE /audit_logs/destroy?id=42

[!WARNING] destroy is irreversible. On a model with "soft_delete": true, calling destroy returns 400 VALIDATION_ERROR for all roles except system. Only the system role is permitted to permanently destroy soft-deleted rows (e.g. for GDPR account purging).

Terminal window
DELETE /audit_logs/destroy?id__in=1,2,3&chunk_size=500

Restore a soft-deleted record by clearing deleted_at.

PATCH /{model}/restore

{
"where": { "id": 42 },
"data": { "status": "draft" }
}

where is required. data is optional and allows updating readable fields at the same time deleted_at is cleared. Returns {restored_count}. Only applicable to models with "soft_delete": true (403 otherwise).


A shared GraphQL endpoint supporting queries, aggregates, and mutations across all models.

POST /graphql

{
"query": "{ posts(status: \"published\", limit: 10) { id title created_at } }"
}

Enforces identical RBAC and RLS permissions as REST routes. Multi-root mutations execute within a single atomic database transaction. See GraphQL Guide.


All operations are available directly on the kirak instance:

await kirak.fetch("products", {"is_active": True}, limit=100)
await kirak.create("orders", {"user_id": 1, "total": 99.99})
await kirak.update("orders", {"id": 5}, {"status": "shipped"})
await kirak.delete("orders", {"id": 5})
await kirak.destroy("audit_logs", {"created_at__lt": "2024-01-01"})
await kirak.count("orders", {"status": "pending"})
await kirak.exists("users", {"email": "alice@example.com"})
await kirak.search("products", "bluetooth", limit=10)
await kirak.upsert("settings", {"key": "theme"}, {"value": "dark"})
await kirak.restore("posts", {"id": 42})
Call Location Execution Identity
Inside an HTTP request (or its hooks) The request’s authenticated caller (resolved from Bearer token, cookie, or API key; guest if none)
Scheduler task with run_as="system" / run_as="caller" system / the user who enqueued the job
Scheduler cron with run_as="system" system
Inside with user_context(user): / with as_system(): That user / system
Anywhere else (startup scripts, worker processes) Guest (unauthenticated)

Inside an active HTTP request, the caller identity cannot be overridden by user_context(). Outside a request, wrap calls with user_context:

from kirak import user_context
with user_context({"role": "user", "user_id": 42, "token": None}):
await kirak.fetch("orders", {"status": "pending"})

For background operations that lack an owning user, run as the system identity:

from kirak.core.context import as_system
with as_system():
await kirak.fetch("orders", {"status": "completed"})

[!CAUTION] Never use as_system() inside a route handler to bypass access controls. It turns the request into Kirak’s internal identity and exposes cross-tenant data. kirak validate --code flags as_system() in route handlers as a warning.


Decorate async functions with @kirak.transaction() to execute all model writes within a single database transaction:

@kirak.transaction()
async def place_order(user_id, items):
order = await kirak.create("orders", {"user_id": user_id, "total": 99.99})
await kirak.create("order_items", [dict(item, order_id=order["data"]["id"]) for item in items])
await kirak.update("products", {"id": items[0]["product_id"]}, {"stock": 9})
return order
  • Nesting: Decorated functions called from within another transactional function participate in the parent transaction.
  • Rollback: Any unhandled exception rolls back all writes.
  • Reads: fetch, search, count, and exists calls inside the function read from the active transaction connection, seeing uncommitted changes immediately.
  • Side Effects: Hand external side effects (emails, payments) to kirak.on_commit():
@kirak.transaction()
async def place_order(user_id, items):
order = await kirak.create("orders", {"user_id": user_id, "total": 99.99})
await kirak.on_commit(lambda: kirak.notifications.send_email({
"to": "alice@example.com",
"subject": "Order confirmed",
"text_body": f"Order #{order['data']['id']}",
}))
return order