Skip to content

GraphQL

A single shared GraphQL endpoint serves queries, relationship joins, aggregates, and mutations across every model in your application. Under the hood, Kirak translates GraphQL documents directly into the same CRUD operations that REST endpoints use – enforcing identical role-based access control, row-level security, and rate limits.

flowchart TD
A["POST /graphql Document"] --> B["Parser & Budget Gate<br/>(Max 20k Tokens, 50 Roots, 1k Selections)"]
B --> C["Rate Limit Evaluation<br/>(Tracks All Queried Models; Attaches Tightest Quota)"]
C --> D{"Query Type"}
D -->|"Read Queries / Aggregates"| E["Translate to _fetch / _search<br/>(RLS & Field Masking Applied)"]
D -->|"Multi-Root Mutation"| F["Single Atomic Transaction<br/>(Executes Serially; Rolls Back on Any Failure)"]
E --> G["Unified Response Envelope<br/>(statusCode + data)"]
F --> G

POST /graphql

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

Models marked "internal": true cannot be queried as root fields over HTTP (returns 404 NOT_FOUND). However, a public model with a foreign-key relationship can resolve an internal model (e.g., selecting user_id { id email }), provided the caller’s role satisfies the internal model’s own access rules (see Relationships). Server-side Python code calling kirak.graphql() can reach all models.


GraphQL returns the same response envelope as REST. It does not use the standard GraphQL-over-HTTP {data, errors[]} shape.

Success:

{
"statusCode": 200,
"status": "success",
"message": "GraphQL executed successfully",
"data": {
"posts": [
{ "id": 1, "title": "Hello Kirak" }
]
}
}

Error:

{
"statusCode": 403,
"status": "error",
"error": "PERMISSION_DENIED",
"message": "Access denied for 'secrets'",
"data": null
}

[!IMPORTANT] Any error in any root field fails the entire request – partial data responses are never returned. An unknown model returns 404 NOT_FOUND. An unknown mutation verb, syntax error, or unresolvable field returns 400 VALIDATION_ERROR.


GraphQL triggers the same per-model CRUD hooks as REST:

  • Mutations: before_<op> and after_<op> fire on the model for each mutation root field. For example, createPosts triggers before_create and after_create on "posts".
  • Simple Queries: before_fetch and after_fetch fire for field queries; before_search and after_search fire when a search: argument is present.

In addition, two request-level hooks wrap the entire GraphQL lifecycle:

@kirak.on("graphql").hook("before_graphql")
async def inspect_query(payload):
# payload = {"query": "...", "variables": {...}}
return payload
@kirak.on("graphql").hook("after_graphql")
async def post_process(result):
# result = full response envelope
return result

Relationship join queries and aggregate queries (<model>_aggregate) fire before_graphql and after_graphql, but bypass individual per-model CRUD hooks.


A mutation document with multiple root fields executes inside one database transaction, serially:

mutation {
createPosts(input: { title: "Draft Post" }) {
id
}
updateUsers(where: { id: 1 }, input: { post_count: 5 }) {
id
}
}

If any root field fails (due to a validation error, unique constraint violation, or permission failure), the entire transaction rolls back immediately and earlier mutations are discarded.

[!NOTE] On databases that lack transactional support (such as Cloudflare D1), mutations are restricted to a single root field per request. Multi-root mutations on such databases return 400 VALIDATION_ERROR.


Filters are supplied as direct arguments matching the model’s schema fields. A plain scalar argument indicates equality; nested objects express comparison operators:

{
posts(status: "published", price: { gt: 100, lte: 500 }) {
id
title
}
}
Operator SQL Equivalent Description
(scalar value) = Exact equality match
eq = Explicit equality match
neq != Inequality match
gt / gte > / >= Greater than / greater than or equal
lt / lte < / <= Less than / less than or equal
like / ilike LIKE / ILIKE Pattern matching. Explicit % wildcards are preserved; unadorned strings auto-wrap as %value%.
in / nin IN (...) / NOT IN (...) Array membership
is_null IS NULL / IS NOT NULL Evaluates boolean flag (true or false)

Dates and timestamps require valid ISO-8601 strings (created_at: { gte: "2026-09-01T00:00:00Z" }).

Unlike REST, GraphQL natively supports or: filters:

{
posts(
published: true,
or: [
{ status: "open" },
{ due_at: { lt: "2026-11-01" }, assignee_id: { is_null: true } }
]
) {
id
title
}
}
  • Takes a list of up to 10 filter objects.
  • Conditions within one object are ANDed; objects in the list are ORed.
  • The overall or: block is ANDed with top-level field filters.
  • Available only on simple queries (not valid on relationship joins, aggregates, or mutations).

Add a search: argument to search across all searchable: true fields:

{
posts(search: "kirak runtime") {
id
title
}
}

Evaluates as a case-insensitive LIKE match across all searchable fields readable by the caller.


{
posts(limit: 10, offset: 20, orderBy: { field: "created_at", dir: "DESC" }) {
id
title
}
}
  • limit defaults to 10 (capped by the model’s max_limit, default 1000).
  • orderBy accepts an object with field and dir (ASC or DESC). Sorting by a field marked "sortable": false returns 400 VALIDATION_ERROR.
  • limit, offset, orderBy, order_by, search, and or are reserved argument names across all models.

Foreign-key fields declaring a relationship object in their schema can be expanded using sub-selections:

{
posts {
id
title
user_id {
id
email
}
}
}
  • Executes as an optimized SQL LEFT JOIN.
  • The joined model’s own access rules and row conditions apply. If the caller lacks permission to fetch the related model or fails its row condition, the parent record is still returned with the relationship field set to null.
  • Relationships expand one level deep. Nested joins (user_id { org_id { name } }) return 400 VALIDATION_ERROR.

Every model automatically exposes a <model>_aggregate root query:

{
orders_aggregate(status: "completed", groupBy: "user_id") {
count
sum { total }
avg { total }
min { total }
max { total }
}
}
  • count requires no sub-selection.
  • sum, avg, min, and max require sub-selections of numeric fields.
  • groupBy groups results by one or more fields. Capped at max_limit groups (default 1,000).
  • Output fields are named <function>_<field> (e.g. sum_total).
  • Access Control: Aggregates evaluate permissions against the model’s search rules (not fetch), and row conditions restrict the aggregated dataset.

Mutation root fields follow the naming convention {operation}{Model} (createPosts, updatePosts, upsertPosts, deletePosts, destroyPosts, restorePosts):

mutation {
createPosts(input: { title: "Hello", content: "World" }) {
id
title
}
updatePosts(where: { id: 42 }, input: { status: "published" }) {
id
status
}
deletePosts(ids: [1, 2, 3]) {
id
}
}
Mutation Arguments Description
create<Model> input Single record insert. Returns requested fields fetched by ID after insert.
update<Model> input, where Update matching records. where is required.
upsert<Model> where, input where is the row’s key: the primary key, one unique field or one unique index.
delete<Model> ids or where Soft delete.
destroy<Model> ids or where Permanent hard delete (restricted to system on soft-delete models).
restore<Model> where, input (optional) Un-soft-delete records. Clears deleted_at.

Every GraphQL document is parsed and validated against strict safety budgets before executing:

Limit Maximum Description
Tokens 20,000 Names, punctuation, and values parsed by the GraphQL lexer
Root Fields 50 Top-level operations and aliases
Selections 1,000 Fields, fragment spreads, and inline fragments visited

Documents exceeding any budget return 400 VALIDATION_ERROR.

Every model queried in a GraphQL document is evaluated against its respective rate limit. The response headers reflect the tightest remaining quota:

  • X-RateLimit-Limit
  • X-RateLimit-Remaining
  • X-RateLimit-Reset

If any queried model has exceeded its quota, the entire request fails immediately with 429 RATE_LIMIT_EXCEEDED.


[!SECURITY] Schema introspection (__schema and __type) is unconditionally disabled in Kirak runtime. Attempting to query introspection fields returns 403 PERMISSION_DENIED (GraphQL introspection is disabled). To inspect schema definitions for client tooling, reference the JSON schema files directly or use GET /openapi.json.