Skip to content

karni.api

Posture: read first. Every BaseViewSet must declare access, and it is the only gate. A viewset without it answers 403 to every request (the message names the fix) and fails the build (viewset-access). Nothing is anonymously readable unless the declaration says Public(). Set auto_register = False to keep a viewset off the router.

A model becomes a full API resource with four lines:

# myapp/viewsets.py  (or myapp/api/viewsets.py)
from karni.api import Access, BaseViewSet, HasRole, Public
from myapp.models import Event

class EventViewSet(BaseViewSet):
    model = Event
    access = Access(read=Public(), write=HasRole("staff"))
    search_fields = ["title"]

That yields CRUD, filtering, pagination, ordering, search, access control, N+1-free queries and a correct OpenAPI schema at /api/events/. Mount once:

# config/urls.py
path("api/", include("karni.api.urls")),

BaseViewSet

Declarative attributes (all optional except model and access):

attribute default meaning
model none drives queryset, serializer, filters, route
access none (required) Access(read=, write=, create=) or Unscoped(reason=). See Access control
serializer_class None explicit class always beats generation
queryset model._default_manager.all() replace to pre-filter
search_fields () enables ?search= via the search provider
expand_depth 0 server-side default expansion depth
expandable_fields auto (forward FK/O2O/M2M) mapping of expand key → relation, with reverse relations only when listed explicitly
auto_register True False → auto-router skips it
route kebab-plural of the model name router prefix
select_related / prefetch_related () query hints merged into the derived lookups (see Performance)
optimize True False → only the hints apply
query_budget None (KARNI_QUERY_BUDGET) Budget(list=25, reason=...)
pagination None (pagination_class) Unpaginated(max_rows=N, reason=...), the only way to return plain lists
cache None (KARNI_API_CACHE) Uncached(reason=...) or Cache(ttl=..., depends_on=[...])
aggregation None (class Karni: aggregate) Experimental. What GET <resource>/aggregate/ may group and sum. See aggregations

Default ordering: model Meta.ordering, else -created_at when the field exists, else -pk. Every normal DRF hook (get_queryset, get_serializer_class, permission_classes, filterset_class, …) remains overridable. BaseViewSet is a plain ModelViewSet underneath, plus ObjectPermissionsMixin (filter_queryset_for_user) from karni.accounts. Overriding get_queryset (with or without super()) never loses the access scope, because BaseViewSet.__init_subclass__ wraps it.

?ordering= accepts the fields the request's serializer reads back. So a write-only field, or one that Karni.field_roles hides from the requester, cannot order the list (its values would leak through the order). A forward relation orders by its key column: ?ordering=venue sorts by venue_id, never by the venue model's Meta.ordering, which may be a field of a row the requester cannot read. To-many and reverse relations are not orderable. Ordering by one repeats a row once per related row, readable or not, and pushes others off the page. An explicit ordering_fields on the viewset is honoured as DRF does.

Access control

One declaration per viewset (ADR 0001, Decision 2), compiled into both enforcement layers:

  1. A request gate: a DRF permission (karni.api.access.AccessPermission) that get_permissions() always puts first, so 401/403 comes before any query.
  2. A row filter: the read predicate as a Q, applied in get_queryset(). It is authoritative: lists, details, custom actions, relation-field PK validation and ?expand= all go through it.

The default declaration, which is what karni make viewset writes, is the roles' grants (ADR 0002, P2):

from karni.api import BaseViewSet, Granted

class EventViewSet(BaseViewSet):
    model = Event
    access = Granted()      # whatever KARNI_ROLES grants for Event, row-scoped

Granted() resolves to the viewset's model and the current action. Reads need events.event:view, create needs add, and writes need change / delete on a row that is also readable. A custom @action declared in class Karni: actions is its own permission (an undeclared unsafe one is E211). The rows are the union of the matching grants' scopes (all, own, related:<key>, custom:<name>, see roles as data), so an agent writing a viewset gets row scoping without naming it. With per-user grants on, a user's own grants join their role grants in that union. Bare access = Granted() is Access(read=Granted(), write=Granted()), and it combines like any predicate (read=Granted() | HasRole("auditor")). The admin applies the same grants to its rows.

A custom rule names the predicates itself:

from karni.api import Access, Authenticated, BaseViewSet, HasRole, Owned

class EventViewSet(BaseViewSet):
    model = Event
    access = Access(
        read=Owned("organizer") | HasRole("staff"),
        write=Owned("organizer"),
        create=Authenticated(),        # organizer is stamped server-side
    )

The vocabulary is closed. Every predicate has a request-level and a row-level answer:

predicate gate rows
Granted() holds a grant for the viewset's model and the current action the union of those grants' scopes. The model's Karni.owner_field is stamped on create
Public() everyone all
Authenticated() authenticated users all (none for anonymous)
HasRole("a", "b") holds any of the roles (Django groups, one query per request) all for holders, none otherwise
Owned("organizer") authenticated users organizer = request.user. Traversals ("event__organizer") and to-many paths ("members", automatic distinct()) work. On the user model, use Owned("pk")
Owned("user", bypass=HasRole("x")) same as Owned("user") \| HasRole("x")
Where(lambda request: Q(...)) passes (or the function returns a bool for both) the returned Q
Where(Matching(published=True)) (experimental) passes, anonymous included the rows whose fields hold the values. With \| it shows rows on a flag to everyone and every row to the others: Where(Matching(published=True)) \| Owned("author") \| HasRole("staff") (karni.yaml: where:published)
a \| b, a & b any / all OR / AND of the row filters
Can("events.event:approve") holds a grant for any of the permissions (app_label.model:action, roles as data, one query per request) the union of the grants' scopes: all, own (Karni.owner_field = user), related:<key>, custom:<name> (see roles as data). The permission must name the viewset's model

Owned() without a field is a class-definition error that names the fix (created_by only when written explicitly). An Owned path that does not lead to the user model fails at class definition too. Python's or/and on predicates raise TypeError, so use |/&.

Which predicate governs which action:

action predicate out of scope
list read row not listed
retrieve, safe custom @action read 404 (the message names the read scope, and there is no existence oracle)
create create (default: write) 401/403 at the gate
update / partial_update, unsafe custom @action write, row looked up through read unreadable → 404, readable but not writable → 403
destroy delete (default: write, experimental), row looked up through read as above
@action(detail=True, methods=["post"], access=HasRole("x")), or a row action's by that predicate, and the lookup still goes through read as above

Owner fields: a direct FK to the user model named by Owned in write or create is stamped from request.user on create (perform_create) and is read-only in the generated serializer. The body never chooses the owner, unless assign says who may (experimental):

access = Access(
    read=Owned("member") | HasRole("staff"),
    write=Owned("member") | HasRole("staff"),
    delete=HasRole("staff"),     # members cancel, staff delete
    assign=HasRole("staff"),     # staff book for a member
)

With assign, the owner field is writable and optional: left out, it is the caller; set to someone else by a caller assign does not admit, the request is refused with a 403 (E135), on create and on update (a manager reassigning a deal passes, a salesperson handing it on does not).

The written row stays in scope (experimental). A create or an update is saved and then checked against its own predicate's rows in one transaction: a row the caller could not change afterwards is refused with a 403 (E134) and nothing is saved. With write=Owned("seller__user"), a listing posted into someone else's shop, or moved there by a PATCH, is refused, and so is a lesson in another instructor's course under Owned("course__instructor"). A predicate that admits every row (a HasRole holder) costs no query. Override check_written_row() on the viewset to change it.

Posture and DRF permissions. REST_FRAMEWORK["DEFAULT_PERMISSION_CLASSES"] (Karni default: IsAuthenticated) is not consulted for a viewset with an Access declaration. The declaration is the gate, so a permissive project default cannot open one. permission_classes set on a viewset (or an @action) are ANDed after the access gate, so they can only narrow. The DRF default still covers plain DRF views and Unscoped viewsets.

Model scopes cannot be lifted. The row filter is only ever filter()-ed onto the model's default manager, so no predicate (HasRole bypasses included) can reach soft-deleted rows or, later, another tenant's rows. Lifting a model scope takes Model.objects.without(name, reason=...).

Relations and expansion follow the target's scope. A writable relation field of a generated serializer (KarniPrimaryKeyRelatedField) accepts only primary keys of rows the requester can read through the target model's viewset. An out-of-scope PK fails exactly like a missing one. ?expand= embeds only readable rows. To-many levels are scoped Prefetches, and a to-one level into a narrowed target becomes a scoped Prefetch too (one extra query, and an unreadable target renders as null). The target viewset is the first viewset registered for the target model on the KARNI_API_ROUTER router (karni.api.routers.viewset_for_model, the same map x-karni-relation uses). Its access.read and filter_queryset_for_user apply, but its own get_queryset does not. A target with no routed viewset (auto_register = False and not registered explicitly, or simply no viewset) is not an API resource and has no row policy. PKs and expansion use its default manager, so model scopes still hold. A target whose viewset has no access accepts no PK and expands to nothing. Serializers used without a request in their context (server-side code) are not narrowed.

That holds for every response, not only list and retrieve. A write's response (create, update), a viewset with optimize = False, a hint that wins over the scoped lookup, and a custom action rendering a generated serializer all show the same related rows. The generated serializers check them at render time (karni.api.related). Rows fetched through a scoped lookup render as they are, and any other related row is checked against its model's read scope, in one query per related model and page. An unreadable to-one renders as null, an unreadable member of a to-many relation (expanded, or a list of primary keys) is left out, and an export never names an unreadable related row by its natural key. A hand-written serializer or action that renders related rows itself can run the same check with karni.api.related.readable_related(serializer.context, rows).

Why is a row missing? karni why events/<id> --as <user> prints the decision for that user: the gate, each part of read and write against the row, the grants and roles behind them, file:line and the fix. The code above computes it. karni why-empty events --as <user> explains an empty list step by step. See debugging.

Escape hatches, least to most drastic:

  1. Change the declaration.
  2. Where(...) for arbitrary row logic, @action(access=...) for one action, get_access() to compute the declaration per request.
  3. scope_exempt = True with scope_exempt_reason = "...". The gate stays and the row filter goes, so every row the gate admits is visible. The reason is required (E210), and karni check prints every exemption in the project on each run, so they stay visible instead of accumulating.
  4. Override filter_queryset_for_user(queryset). It receives the access-scoped queryset, and the access-override rule requires # karni: allow(access-override): <reason>.
  5. access = Unscoped(reason="..."): no compiled gate and no row policy. The viewset's permission_classes (else the DRF default) decide, and rows are limited only by model scopes and filter_queryset_for_user. The reason is published as x-karni-access.
  6. auto_register = False plus your own view (the viewset-base rule still applies).

Deprecated: object_permission_classes on a BaseViewSet warns (KarniDeprecationWarning) and is removed in 1.0. Until then it still runs, after the access object check. Express the rule in access instead (migration note). karni upgrade lists every viewset that sets it. IsOwner, RolePermission and ObjectPermissionsMixin remain for plain DRF views (see accounts).

Row actions (experimental)

A lifecycle moves by named actions, not by a free PATCH of its state. A viewset declares them with the states and roles where each is legal (karni.api.actions, karni.yaml: actions):

from karni.api import Access, BaseViewSet, HasRole, Owned, RowAction

class OrderViewSet(BaseViewSet):
    model = Order
    access = Access(read=..., write=Owned("buyer") | HasRole("staff"))
    row_actions = {
        "pay": RowAction(from_="pending", by=Owned("buyer")),
        "ship": RowAction(from_="paid", to="shipped", by=Owned("listing__seller__user")),
        "refund": RowAction(from_="paid", to="refunded", by=HasRole("staff")),
    }

    @action(detail=True, methods=["post"])
    def pay(self, request, pk=None):
        ...  # open the payment: Karni has checked the state and `by` first

Each one is POST <resource>/<id>/<name>/:

who may by, like @action(access=...): the gate and the row (default: write)
where it is legal the row's state is one of from_ (empty: any). Elsewhere: 409, E997, naming the state and the legal ones
an action with to Karni routes it when the class has no method of that name: it moves the row with transition(), reading the fields class Karni: moves requires for that state from the body, and answers the row
twice an action with to whose row is there already answers 200 and changes nothing
an action without to the viewset's own @action method of that name runs after the checks. karni check warns about one that has none yet (W136)

The list and retrieve operations carry x-karni-actions (each action's from, to, field, by as x-karni-access writes it, and requires), and each action's own operation carries its entry as x-karni-action, so a client offers only the buttons the row's state allows. The server still decides.

Rate limits

A form open to anonymous visitors needs a tighter limit than the project-wide anon throttle, and Karni gives it one by itself.

Public creates are limited by default. When a viewset's create predicate lets anonymous callers in (create=Public(), or a write=Public() that create defaults to, or Public() | ...), its create action is limited to KARNI_PUBLIC_CREATE_RATE, default "10/hour". Each caller is counted on its own: the user id when signed in, else the client IP (honouring NUM_PROXIES). Over the rate, create answers 429 with Retry-After. A gate built from Where(...) is not treated as public, because its function decides per request. Declare a limit for it.

from karni.api import Access, BaseViewSet, HasRole, Public

class EnquiryViewSet(BaseViewSet):
    model = Enquiry
    # A contact form: anyone sends one, only staff read them. 10 per hour
    # and caller, and a honeypot field, without a line of throttling code.
    access = Access(read=HasRole("staff"), write=HasRole("staff"), create=Public())

karni make model Enquiry ... --with viewset --access public-create writes that declaration.

Rates for any action. throttle = Throttle(...) names actions and their rates in DRF's format ("<number>/<period>", the period s, min, hour or day):

from karni.api import Throttle

class EnquiryViewSet(BaseViewSet):
    ...
    throttle = Throttle(create="3/hour", subscribe="20/day")

A declaration that names create replaces the public-create default, and Throttle(create=None) turns it off for that viewset. Actions without a rate keep only the project-wide anon and user throttles. A custom @action is named by its method name, and an unknown name fails at class definition (E132).

Settings win over both. The scope is "<route>.<action>" (enquiries.create), so REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"]["enquiries.create"] replaces the rate, and None there switches the limit off. KARNI_PUBLIC_CREATE_RATE = None (or an empty KARNI_PUBLIC_CREATE_RATE= in .env) turns the default off for every viewset. The rate in force is published on the operation as x-karni-throttle.

The limit rides in throttle_classes, so anything that turns DRF throttling off (assert_crud, karni why) turns it off too, and the pytest plugin gives each test empty counters (rate limits in tests). A viewset that sets its own throttle_classes and declares no throttle owns its throttling, as in plain DRF, and gets no default. For another caller identity, subclass karni.api.throttling.ActionRateThrottle and set action_throttle_class on the viewset. get_throttles() still works as in plain DRF.

A honeypot on public creates. The same viewsets accept one extra field, named by KARNI_PUBLIC_CREATE_HONEYPOT_FIELD (default homepage). A person never sees it: @karni/ui's ResourceForm renders it out of sight, out of the tab order and hidden from screen readers. A request that fills it is a script, and is answered 202 Accepted with nothing saved, the way register/ treats its own honeypot. The event karni.api.honeypot is logged on karni.api. The field is not in the request body of the OpenAPI schema, so it is never required and never generated as a form field. The create operation names it in x-karni-honeypot instead.

It is a separate setting from registration's KARNI_ACCOUNTS_HONEYPOT_FIELD because that one's default, website, is a common model field: a contact form that asks for a website would drop every real submission. When the model or its serializer has a field of the honeypot's name, the honeypot is off for that viewset. "" turns it off everywhere, and a viewset's get_honeypot_field() can return None (off) or another name.

Imports stay closed. A public create lets anyone send one row, not a file of rows. When create or write lets anonymous callers in, the import endpoints (import/, preview, commit) also need a signed-in user, who must still pass create or write.

Field visibility

A role can see a record without seeing every field of it (ADR 0002, P3). Declare it once on the model. No serializer per role is needed anywhere:

class Customer(BaseModel):
    ...

    class Karni:
        field_roles = {
            "phone": {"read": ["staff", "support"], "write": ["staff"]},
            "internal_note": ["staff"],            # shorthand: read and write
        }

The role slugs are the project's own (KARNI_ROLES). A field not listed stays visible to whoever may read the row, and superusers see everything. The generated serializer applies the rule per request:

  • A field the user may not read is absent from the payload, never null (a null would say the field exists). It is absent from ?expand= embeddings too, because nested serializers are generated the same way.
  • A field the user may read but not write is published read-only, and an explicit attempt to send it is refused with a 400 naming the field and the roles that may: {"phone": ["Only roles staff may change phone."]}.
  • ?ordering=, filters and ?search= on a hidden field are ignored, because a ranking or a match is a value oracle on a column the user cannot see. The same applies to APIMeta.write_only fields, which never order and never search (karni.E131 refuses a search_fields entry that names one).

The OpenAPI document follows: /api/schema/ describes the fields the requesting user may see, and marks the ones they may not write read-only, so ResourceTable, ResourceForm and ResourceDetail render only those. @karni/ui invalidates its cached schema when the identity changes, so a login or logout refetches the right document. The admin honours the same rules. karni check refuses a field_roles entry naming a field the model does not have or a role KARNI_ROLES does not declare (E212): a role nobody holds would hide the field from everyone. assert_crud(ViewSet, "role") checks all of it in its visibility step.

Import and export

Every BaseViewSet serves GET /<resource>/export/?format=csv|xlsx. That is the list as this request sees it (filters, search, ordering, row scope, field visibility), with relations written as natural keys (a related row the requester cannot read keeps its primary key). It also serves the import flow under /<resource>/import/. GET describes the importable fields, POST uploads a file, …/<job>/preview/ is the mandatory dry run, …/<job>/commit/ writes in one transaction and one audit batch, and …/import/template/ is the downloadable template. The gate is the declaration's create or write (write_or_create_actions), and each row is then checked on its own. When either lets anonymous callers in, the gate also needs a signed-in user (imports stay closed). See import and export.

Read-only models

Experimental

BaseViewSet.is_read_only and read_only_refused_actions are experimental.

A viewset over an external model that is not writable answers create, update, partial_update, destroy and the import actions with 405 to every caller, signed in or not, and leaves them out of the OpenAPI document and the Allow header. Reads, ?expand=, filters and export work as usual. read_only_refused_actions lists the refused actions, and is_read_only() decides per viewset: override it to serve writes from one viewset.

Tree models

Experimental

The tree endpoints and filters are experimental.

A viewset whose model is a tree model also serves tree/ (nested, a few levels at a time), <id>/children/, <id>/ancestors/, <id>/move/ and access/ (the requester's access forest, the tree scope), and its list takes ?parent=<id>, ?parent=null and ?descendants_of=<id>. A node with live children answers DELETE with 409 (E341) unless the request says ?branch=true. Access applies to each of them, and tree_max_nodes, tree_default_depth and tree_max_depth bound tree/. See the API of tree models.

Taxonomies

Experimental

The taxonomy filters and endpoints are experimental.

A viewset whose model declares class Karni: taxonomies takes ?<key>=<id>,<id> and ?<key>_descendants=true on its list and serves facets/?taxonomy=<key>&rollup=true: the rows per node under the list's filters, search and access, in two queries. A tree resource that a taxonomy points at serves <id>/tagged/?descendants=true: the rows tagged with the node, per tagging model, each under its own access. facet_queryset() is the escape hatch for the rows the facets count, and taxonomy_actions turns the routes off. The relation field of a taxonomy carries x-karni-taxonomy: "<key>" in the OpenAPI document.

Deferred writes

When a karni.signals.pre_write receiver defers a write (the karni-approvals module does, for a guarded change), create, update, partial_update and destroy answer 202 with the receiver's payload (the pending change) instead of writing. BaseViewSet.deferred_response(exc) shapes that answer. See write interception.

Vetoes

A veto refuses an action at the gate after the access declaration admitted it. Its reason comes from the state the request runs in, not from who the user is. karni.vetoes.register_veto(fn, name=...) registers a callable that receives a VetoContext and returns a reason string to refuse, or None. The context carries the request, the kind ("api" or "admin"), the action, the model, the resolved permission key and the view. AccessPermission consults every registered veto after the predicate passes (the refusal is the 403's detail). The admin consults them in has_add/change/delete_permission, drops vetoed names from the actions menu and hides Import. context.names() is every name a pattern may match: the action, the permission, the model label and model:action.

The karni-impersonation module is built on it. While a support user acts as someone else, deleting, exporting and payment changes are refused whatever the target may do. Projects use the same hook for a maintenance freeze or a read-only tenant. unregister_veto and vetoes() manage the registry.

APIMeta: model-side API metadata

class Event(BaseModel):
    ...
    class APIMeta:
        fields = [...]        # or exclude = [...] (mutually exclusive)
        read_only = ["status"]
        write_only = ["internal_note"]
        schema_name = "Event"  # optional: replaces the AppLabelModel stem
        select = ["venue"]     # optional query hints for properties listed in fields
        prefetch = ["tags"]    #   (see Performance → Query optimisation)
        validate = True        # run Model.clean() on create/update (default)

Model validation. A domain invariant lives in the model's clean():

class Booking(BaseModel):
    def clean(self):
        if self.tier.event_id != self.event_id:
            raise ValidationError({"tier": "This ticket tier belongs to another event."})

The generated serializer runs clean() on the would-be row before every create and update, including the values the viewset stamps on save, such as owner fields. A django.core.exceptions.ValidationError becomes the 400 response, keyed by field. No serializer is needed for a cross-field rule. A rule that depends on other rows ("only N seats left", "the room is free") does not belong in clean(), because two requests can pass the check together. Declare it so the database enforces it, with a CapacityField consumed with karni.capacity.reserve() or with class Karni: no_overlap. The API then answers 409 naming the conflict (lifecycle and capacity). Opt out per model with APIMeta.validate = False. An explicit serializer_class built on KarniModelSerializer keeps the behaviour and can override run_model_clean().

Rules enforced at build time (violations raise ImproperlyConfigured naming the model):

  • fields and exclude are mutually exclusive. read_only/write_only must be subsets of the effective fields.
  • id, created_at, updated_at (from BaseModel) are always read-only.
  • Password-named CharFields are never auto-exposed. User-like models (AbstractBaseUser/PermissionsMixin subclasses) additionally force last_login, is_staff, is_superuser, is_active, groups, user_permissions read-only.
  • M2M fields are writable by default. Mark them in read_only to freeze.

Generated serializers get deterministic app-qualified component names (MyappEventSerializer, expanded variants suffixed per expand path), so schema components never collide across apps. An explicit serializer_class (karni make serializer) is named by drf-spectacular from its class name (EventSerializer → Event), so switching to one changes the schema snapshot and the generated frontend types once. x-karni-access.owned is published only when the read predicate is a single Owned(...). Top-level generated classes are cached per (model, expand-set, max-depth). build_serializer.cache_clear() resets the cache (it also resets when KARNI_API_MAX_EXPAND_DEPTH changes under override_settings).

Filtering

KarniFilterBackend auto-derives a FilterSet when a BaseViewSet (or a view setting karni_auto_filterset = True) declares no filterset_class/ filterset_fields. For any other view it behaves exactly like stock DjangoFilterBackend. Derived lookups:

field type lookups
Char/Slug/Email exact, icontains
Int/Float/Decimal/Date/DateTime exact, gte, lte
Boolean exact
FK/O2O exact (typed by the target pk: a UUID filter for UUID keys, IntegerFilter for integer keys)
fields with choices exact via ChoiceFilter (stays an enum)

Excluded from derivation: the model's own primary key, TextField (unindexed seq scans, so opt back in with explicit filterset_fields), File/Image/JSON/binary fields, APIMeta.write_only/excluded fields, and password-named fields. The primary key gets no ?id=, ?id__gte= or ?id__lte= whatever its type: on integer keys a range would page through the table by key. Declare one where you want it:

class ReadingViewSet(BaseViewSet):
    model = Reading
    access = Access(read=HasRole("analyst"), write=HasRole("analyst"))
    filterset_fields = {"id": ["exact", "gte", "lte"], "sensor": ["exact"]}

karni.api.filters.IntegerFilter (experimental) is an exact filter that takes whole numbers only, so ?sensor=1.5 is refused (400) instead of matching row 1, and the schema documents an integer. The type→lookups map is the overridable lookup_map class attribute on KarniFilterBackend. Explicit filterset_* on the viewset always wins, untouched, except for one thing. A relation named in filterset_fields becomes a choice filter over the target's readable rows (KarniFilterSet, the backend's filterset_base). So naming a row the requester cannot read is refused exactly like naming one that does not exist (a 200 for one and a 400 for the other would confirm the row exists). A hand-written filterset_class declares its own querysets. Give a ModelChoiceFilter queryset=lambda request: readable(<queryset>, request) (karni.api.access.readable).

Expansion

?expand=organizer,venue inlines related objects, and dotted paths (?expand=venue.city_ref) nest. Multiple expand params merge.

  • Allowed keys per level: expandable_fields or all forward FK/O2O/M2M names. Each dotted segment is validated against the model at that level, and an unknown key answers 400 listing the allowed keys there.
  • Depth is capped by KARNI_API_MAX_EXPAND_DEPTH (env, default 2), and deeper paths answer 400. A path may come back to a model already on it: on a tree resource ?expand=parent nests the parent, ?expand=parent.parent the grandparent, and ?expand=region.parent the parent of a row's region. Each segment is one level, so the path bounds the nesting.
  • Expanded relations are just nested serializers to the query optimiser. It uses select_related for FK/O2O paths into targets whose read scope keeps every row, and a scoped Prefetch for any M2M/reverse segment or narrowed target. So expansion adds no N+1.
  • Expanded nested representations are read-only. Writes keep using PKs.
  • Only rows the requester can read are embedded. Every level goes through its target's read scope (see Access control), and a to-one target outside it renders as null. This holds on every response that renders the expanded serializer, writes included (PATCH …?expand=venue). On a tree, the parent of the highest node a requester may read (under the tree scope, the parent above a grant) expands to null, so an expanded parent: null does not by itself mean a root. A relation that is not expanded stays its key, readable target or not, so a form that sends a row back keeps the relation.

karni.api.expansion.related_lookups() and scoped_related_lookups() are deprecated (they warn, and they are removed in 1.0). The optimiser derives the same lookups from the expanded serializer, so call karni.api.optimizer.optimize().

v0.1 bound: each distinct expand-set builds (and caches) one serializer class, so pathological clients can grow that cache breadth-wise. The cap on depth bounds each entry's size. Clear it with build_serializer.cache_clear().

Performance

ADR 0001 Decision 3. Four defaults, all on without project code, each with an escape hatch that is a declaration on the viewset and never silence. karni context lists every declared exception (PERF: line) so you see the existing ones before adding another.

Query optimisation

Every list and retrieve runs the queryset through karni.api.optimizer.optimize() after the access scope. It walks the serializer that will render the response (generated, expanded or hand-written, nested to any depth) and derives the lookups:

Serializer field Derived
PK relation over a forward FK/O2O nothing (DRF reads the *_id column)
PK list over an M2M / reverse FK Prefetch(name, queryset=<target>.only("pk"))
nested serializer on a FK/O2O select_related(name), recursing with the prefix
nested serializer many=True Prefetch(name, queryset=<optimised target queryset>)
dotted source="venue.city.name" select_related("venue__city")
SlugRelatedField, StringRelatedField, … select_related / a full-row Prefetch
SerializerMethodField, a model property opaque, needs a hint

Every Prefetch queryset starts at the target's default manager (soft delete and other model scopes) narrowed by the target viewset's read scope. A to-one level into a narrowed target is a scoped Prefetch instead of a join, so an unreadable row renders as null (ADR 0001 R3). Measured: a publisher list nesting writers → novels → chapters (+ an M2M PK list and an M2M slug list) costs 6 queries at 2 or 12 publishers. With optimize = False it costs 32 and 182 (tests/api/test_optimizer.py).

Hints cover what the walker cannot see. They are merged with the derived lookups and never replace them:

class NovelViewSet(BaseViewSet):
    model = Novel
    access = Access(read=Public(), write=HasRole("staff"))
    serializer_class = NovelSerializer   # has chapter_count = SerializerMethodField()
    prefetch_related = ["chapters"]      # what get_chapter_count reads
    select_related = []                  # same, for to-one reads

class Novel(BaseModel):
    ...
    class APIMeta:
        select = ["writer"]              # for the writer_name property in APIMeta.fields;
        prefetch = []                    # applied wherever Novel is rendered, at any depth

A hint string is applied as written (model scopes apply, the target viewset's read scope does not). A hint changes how rows are fetched, never which related rows a response shows. The render-time check (access control) still applies, in one query per related model and page. A hinted Prefetch(...) owns its whole subtree. A lookup already on the incoming queryset (queryset = ...prefetch_related(...)) wins over a derived one at the same level. optimize = False keeps only the hints. Override optimize_queryset(queryset, serializer_class=None) for a hand-built strategy. Custom actions are not optimised automatically, so return self.paginated_response(qs) (which is) or call self.optimize_queryset(qs).

What the walker cannot see it records on the plan as blind spots (karni.api.optimizer.blind_spots(serializer, model): method fields, properties named by source, to_representation overrides, whole-object fields). karni queries reads them to say which field repeats a query and which hint fixes it:

karni queries /api/events/ --as organizer@example.com

Query budgets

Every BaseViewSet request is counted (auth, role lookups and the pagination COUNT included, per ADR 0001 R5) against its action's budget:

Action Budget (KARNI_QUERY_BUDGET)
list, retrieve 8
create, update, partial_update 12
destroy 10
anything else ("*") 15

KARNI_QUERY_BUDGET_MODE decides what an overrun does: raise in tests (the karni pytest plugin sets it, see testing), warn in the dev profile (a log line with the grouped duplicate report), off in production (no wrapper at all). Both counting modes set X-Karni-Queries (and X-Karni-Query-Budget). The failure names the repeated statement and what rendered it:

EventViewSet.list ran 14 queries against a budget of 8.
14 queries, 12 duplicated, 3.1 ms in SQL
  12× SELECT … FROM "app_tag" INNER JOIN "app_event_tags" ON … WHERE … = %s
      ← EventSerializer.tag_names (app/serializers.py:41 in get_tag_names)

Raising a budget is a declaration with a reason:

class ReportViewSet(BaseViewSet):
    model = Report
    access = Access(read=HasRole("staff"), write=HasRole("staff"))
    query_budget = Budget(list=25, reason="per-row signed URLs, measured 2026-10")
    # Budget(export=None, reason=...) stops checking one action;
    # Budget(default=20, reason=...) covers every action not named.

Budget keys are action names (typos fail at class definition). Unnamed actions keep the project budget. Project-wide: KARNI_QUERY_BUDGET = {"list": 10} (a partial dict merged over the defaults). Non-viewset code: with karni.testing.query_budget(n): ....

Dev query log. karni.middleware.QueryLogMiddleware is first in Karni's MIDDLEWARE and is on when KARNI_QUERY_LOG is (the dev profile). It logs every request that ran SQL on the karni.queries logger: query count, duplicated count, SQL time and total time, plus one line per repeated statement with what rendered it. The level is WARNING when anything repeated, INFO otherwise. When it is off, it removes itself from the chain at startup.

Pagination

Every list is paginated by a karni.pagination.KarniPagination subclass: KarniPageNumberPagination (default: ?page=, ?page_size=) or KarniCursorPagination (?cursor=, with no COUNT(*) for very large tables). A page holds the rows in the model's ordering (Meta.ordering, karni.yaml's order), else newest first, so a row just created is on the first page only when the order puts it there. karni context states the project's own values on its API: line (experimental): API: lists answer {count, next, previous, results}, 50 rows a page (?page=, ?page_size= up to 100), in the model's ordering, else newest first.

  • Hard cap. ?page_size= and the default PAGE_SIZE (env KARNI_PAGE_SIZE, 50) are capped at KARNI_MAX_PAGE_SIZE (env, default 100). A paginator subclass may set a lower max_page_size, never a higher one.
  • Floor. KARNI_MAX_PAGE_SIZE may not be configured below KARNI_MAX_PAGE_SIZE_FLOOR (env, default 25, the smallest page size @karni/ui's ResourceTable offers in its size menu). The floor itself is at least 1. A cap of 0/None would switch DRF's cap off, and a cap below what the UI requests silently hides rows from its page count. Boot validation refuses both. Lowering the floor is the explicit, project-wide way to allow a smaller cap.
  • Cannot be switched off by accident. pagination_class = None on a viewset is a class-definition error, a non-Karni paginator class too, and boot refuses REST_FRAMEWORK["PAGE_SIZE"] = None (or missing) and a DEFAULT_PAGINATION_CLASS that is missing or not a KarniPagination.
  • The opt-out states a reason and stays bounded:
class ExportViewSet(BaseViewSet):
    model = Event
    access = Access(read=HasRole("staff"), write=HasRole("staff"))
    pagination = Unpaginated(max_rows=2000, reason="CSV export")

The list is a plain JSON array of at most max_rows rows, and X-Karni-Truncated: true says rows were cut. - Custom actions that return lists use the helper (the unpaginated-action rule fails the build on Serializer(qs, many=True).data in an action, see enforcement):

@action(detail=False)
def upcoming(self, request):
    return self.paginated_response(self.get_queryset().filter(starts_at__gte=now()))

paginated_response(queryset, serializer_class=None) paginates (same envelope and cap as list), optimises for the serializer, and orders an unordered queryset by the viewset's default ordering. Pass self.filter_queryset(qs) to honour the request's filters too.

Response caching

Off by default. One setting turns it on: KARNI_API_CACHE = True (env), or features: api_cache: true in karni.yaml. Then the data of every successful GET list and retrieve of every BaseViewSet is cached for KARNI_API_CACHE_TTL seconds (300) in the KARNI_API_CACHE_ALIAS cache ("default"). Keep that cache one every process shares (Redis): with a per-process cache a write in one worker never reaches the entries of another (karni.W580 warns with DEBUG off).

Who shares an entry. A key is karni:api:r:<app_label.model>:<sha256>, for example karni:api:r:shop.product:9f2c41…. The hash covers the viewset and its action, the scheme, host and path, the query string normalised (parameters sorted by name, empty values dropped, the comma lists of ?expand= and of __in filters sorted; ?ordering= and ?search= keep their order, which matters), the API version, the language, the caller's access scope and the version tokens of every model the response reads. So ?page=2&expand=tags,category and ?expand=category,tags&page=2 share one entry.

The access scope decides who shares. When the viewset's read access depends on roles alone, every caller with the same roles (and the same superuser and staff flags) shares one entry: Public(), Authenticated(), HasRole(...), and Granted() or Can(...) whose grants all have the scope all, on the viewset and on every related resource the response embeds. Otherwise the entry is the caller's own: an Owned(...) path, a Where(...) rule, a grant scoped own, related: or custom:, an overridden get_queryset, get_access, get_serializer_class or filter_queryset_for_user, or a hand-written serializer with a SerializerMethodField or its own to_representation. Anonymous callers share one entry. The access gate runs before the cache is read, and details are cached only for viewsets whose gate is the Access declaration alone (extra permission_classes would be skipped on a hit).

Invalidation. Each model has a version token and each row an object token, kept in the cache. A write replaces the tokens it touches, so every entry that read them becomes unreachable at once: no key scan, any backend. The models a response reads are its serializer's relations (the optimiser's plan, ?expand= included), the models its read rule crosses (Owned paths, scope paths), Cache(depends_on=[...]), and the table of per-user grants while KARNI_USER_GRANTS is on, so a grant written changes the next response. karni.api.caching.dependencies(ViewSet) lists them for every ?expand= path the viewset allows. Karni sees these writes:

  • save(), delete() and many-to-many changes of any model, in every process (web, Celery worker, management command). Details are invalidated per row.
  • Karni's querysets: update(), delete() (soft and hard_delete()), bulk_create() and bulk_update(), once per call, every row of the model.
  • An import or a content load (karni load), once per import and never for a dry run, and the admin's bulk actions, once per action. with invalidation_batch(): ... does the same for a loop of your own.

A write inside a transaction replaces the tokens at once and again when it commits, so a request that read the old rows in between cannot keep them. Raw SQL and another system's writes send nothing: call karni.api.caching.invalidate(Model) (every row) or invalidate(Model, pk) after them. karni check refuses a cached viewset that reads an external or unmanaged model, or one on another database (karni.E410), unless it declares cache = Cache(ttl=...) (the most it may be stale) or cache = Uncached(reason=...).

Headers. Every cacheable response says how it was served: X-Cache: HIT, MISS or BYPASS. A staff user's request with X-Bypass-Cache: 1 neither reads nor writes the cache. The header is ignored for anyone else. X-Karni-Cache: hit|miss is deprecated and goes in 1.0. Until then it is sent too, with one KarniDeprecationWarning per process, unless KARNI_API_CACHE_LEGACY_HEADER = False.

Per viewset:

class StockViewSet(BaseViewSet):
    model = Stock
    access = Access(read=Authenticated(), write=HasRole("ops"))
    cache = Uncached(reason="levels change every second")   # opt out

class CatalogueViewSet(BaseViewSet):
    model = Product
    access = Access(read=Public(), write=HasRole("ops"))
    cache = Cache(ttl=3600, depends_on=[Price])             # tune

class WishlistViewSet(BaseViewSet):
    model = Product
    access = Access(read=Authenticated(), write=HasRole("ops"))
    serializer_class = ProductWithFavouriteSerializer

    def get_cache_scope(self) -> str:                       # who shares an entry
        return f"user:{self.request.user.pk}"

depends_on names a model whose data the serializer reads without rendering it as a relation (a SerializerMethodField, an aggregate). get_cache_scope is for a response that differs per caller in a way Karni cannot see. Return anything that differs between callers who must not share.

Clearing. karni.api.caching.clear() drops every cached response and clear(Model) one resource's. With a backend that has delete_pattern (django-redis) the entries are deleted. Otherwise the version tokens are replaced and the old entries expire by their TTL. The admin's API cache screen does the same with two buttons, and shows the backend and the flush schedule. For a daily full flush through Celery beat, set KARNI_API_CACHE_FLUSH = "03:30" (in Celery's timezone) or "03:30 Europe/Paris": the schedule karni-flush-api-cache runs karni.tasks.flush_api_cache.

In tests the pytest plugin starts every test with no cached response while KARNI_API_CACHE is on, and so does override_settings turning it on: rows a test wrote roll back, the cache would keep them.

This is the search of one list. One search over every model that opts in, GET /api/search/, is search across models (experimental).

?search= delegates to the provider named by KARNI_SEARCH_PROVIDER:

  • karni.api.search.postgres.PostgresSearchProvider (default): Postgres full-text (SearchVector/SearchRank) OR trigram similarity in a single lazy queryset. Class attrs to tune (subclass + point the setting at yours): similarity_threshold (0.3), rank_threshold, use_trigram (False drops the trigram leg).
  • karni.api.search.simple.SimpleSearchProvider: OR of icontains across search_fields. It works on any database (karni's own test suite uses it on sqlite).

With a SearchField on the model (named in search_fields, or covering every listed field), the PostgreSQL provider matches through its stored, GIN-indexed tsvector instead. Every word is a prefix, all words must match, rows rank by ts_rank, and no trigram leg is added (similarity() cannot use an index). A word is split the way PostgreSQL split the column's text, so a code such as MT-0001 finds that row and no other, and characters such as &, | or ! are only text.

Rank ordering vs ?ordering=: search runs after ordering in the filter pipeline. When the client did not pass an explicit ?ordering=, results are rank-ordered by the provider. Otherwise the requested ordering wins.

Unlike DRF's stock SearchFilter, provider search does not interpret the ^, =, @, $ field prefixes. search_fields are plain field names.

Postgres setup (pg_trgm)

The trigram leg needs the pg_trgm extension and, for speed, a GIN index. karni migrate creates the extension (karni.accounts migration 0004_pg_trgm, a no-op on other databases). pg_trgm is a trusted extension since PostgreSQL 13, so the database owner may create it. If your role may not, create it once as a superuser and migrate again. The migration says so when it is refused. One migration does both, and karni.api.search.postgres re-exports the pieces:

from django.db import migrations
from karni.api.search.postgres import GinTrgmIndex, TrigramExtension

class Migration(migrations.Migration):
    dependencies = [("myapp", "0001_initial")]
    operations = [
        TrigramExtension(),
        migrations.AddIndex(
            model_name="event",
            index=GinTrgmIndex(fields=["title"], name="event_title_trgm"),
        ),
    ]

Postgres-only behaviour is exercised in CI by a job with a Postgres service. Locally the suite runs the simple provider on sqlite.

Custom providers

Subclass karni.api.search.SearchProvider, implement search(*, queryset, query, fields, view=None, …) returning a queryset of the same model, and set KARNI_SEARCH_PROVIDER. Swapping to Elasticsearch / Meilisearch later happens behind this interface with no project code change.

Auto-router

At the first import of karni.api.urls, the factory named by KARNI_API_ROUTER (default karni.api.routers.get_default_router, a zero-argument callable) builds the router and runs autodiscover():

  • Every installed app's viewsets / api.viewsets module is imported. BaseViewSet subclasses with model set and auto_register = True are registered at route or the kebab-plural of the model name (Company → companies, Box → boxes, Day → days). The helper karni.api.routers.pluralize is public.
  • Basenames are "<app_label>-<kebab-model>", unique across apps.
  • Explicit wins: viewsets already registered and prefixes already taken are skipped (debug log). An auto-vs-auto prefix collision logs a warning naming both viewsets. autodiscover() is idempotent.

The setting is consumed once, at first URLconf import. Overriding KARNI_API_ROUTER afterwards (e.g. in a test) is a no-op, so router tests should build fresh KarniRouter instances instead. To pre-register explicit routes:

# myproject/api.py
from karni.api.routers import KarniRouter

def get_router():
    router = KarniRouter()
    router.register("events", MySpecialEventViewSet, basename="myapp-event")
    router.autodiscover()  # everything else, explicit registration wins
    return router
KARNI_API_ROUTER = "myproject.api.get_router"

API versions

Experimental

API versions are in the experimental tier. The settings and karni.api.versions can change in a minor release, with a CHANGELOG entry.

A web app ships with its API, so the two change together. A mobile app does not: the build a user installed last year still calls the API. A version prefix lets the API change for new builds while old ones keep a URL that does not move. Nothing changes until you set a version.

# config/settings.py, above karni_settings(globals())
KARNI_API_VERSION = "v1"        # the current version, mounted at /api/v1/
KARNI_API_UNVERSIONED = "keep"  # what /api/ without a version does
KARNI_API_VERSIONS = {          # more versions, and what to say about them
    "v0": {"deprecated": "2026-06-01", "sunset": "2027-01-31",
           "notes": "https://example.com/api-v0-to-v1"},
}

Each is also an environment variable (KARNI_API_VERSIONS as JSON). A new project's config/urls.py mounts the API with *api_urls(). In an older project replace path("api/", include("karni.api.urls")) with it:

from karni.api.versions import api_urls

urlpatterns = [
    path("api/auth/", include("karni.accounts.urls")),
    *api_urls(),
]

karni check warns (karni.W661) when a version is set and the URLconf does not use api_urls().

Setting Default Meaning
KARNI_API_VERSION "" The current version's name. Lower case letters, digits and -, at most 16 characters. Empty leaves the API unversioned.
KARNI_API_VERSIONS {} Name to options. Keys of an option dict: router, deprecated, sunset, notes. The current version needs no entry.
KARNI_API_UNVERSIONED "keep" "keep": /api/ still serves the current version. "redirect": /api/x/ answers 308 with Location: /api/v1/x/, query string included, and POST stays POST. Every method gets the 308, with or without a CSRF token: the redirect changes nothing, and the view it leads to checks CSRF for a session. "remove": /api/ is a 404.

The options of a version:

  • router: a dotted path to a zero-argument router factory (see the auto-router), so a version can serve other viewsets. Default: the KARNI_API_ROUTER router, shared by every version.
  • deprecated: True, or the day it was deprecated ("2026-06-01").
  • sunset: the day the version goes ("2027-01-31"). Karni never switches a version off on that day. Remove it from KARNI_API_VERSIONS when you do. karni check warns (karni.W660) about a version still mounted after its sunset date.
  • notes: the URL of the migration notes.

/api/auth/, /api/schema/ and /api/docs/ are not versioned.

Deprecation headers

A response from a deprecated version carries the headers below, whatever its status. The middleware karni.api.versions.ApiVersionHeadersMiddleware sends them, and karni_settings() lists it. It is left out of the chain while no version is deprecated.

Deprecation: @1780272000
Sunset: Sun, 31 Jan 2027 00:00:00 GMT
Link: <https://example.com/api-v0-to-v1>; rel="deprecation"; type="text/html"

Deprecation is the structured date of RFC 9745 (true when deprecated has no day), Sunset is RFC 8594's HTTP date, and Link points at notes. A header the view already set is kept. The headers follow the route, not the prefix: a route whose URL has a version keyword is covered.

In views, URLs and tests

DRF's URLPathVersioning is the versioning class, so a view reads request.version. With KARNI_API_VERSION set, a request to /api/ has the current version as request.version. DRF's reverse(name, request=request) adds the version to the URL it builds. Django's reverse("product-list") needs kwargs={"version": "v1"} once KARNI_API_UNVERSIONED is "redirect" or "remove", because there is no unversioned route left. A project with its own REST_FRAMEWORK sets DEFAULT_VERSIONING_CLASS to rest_framework.versioning.URLPathVersioning and DEFAULT_VERSION to the current version.

One document and one client per version

Each version has its own OpenAPI document at /api/<version>/schema/, with Swagger UI at /api/<version>/docs/. /api/schema/ describes the current version. Every document lists x-karni-api-versions (each version with current, deprecated, sunset and notes) and x-karni-api-version, the one it describes. manage.py spectacular --api-version v0 prints one.

karni types writes the schema, types.ts and hooks.ts of the current version as before, then the same three files for each version in frontend/src/api/<version>/. A mobile team takes the types.ts of the version it targets. The staff app talks to the version its createKarniClient baseUrl names.

The staff dashboard

The staff app's home page (the scaffold's frontend/src/pages/home.tsx) is @karni/ui's <Dashboard>. It shows the models that opt in, and nothing else: a shop puts its orders there, a clinic its appointments, a SaaS app its accounts and tickets. A model opts in next to its other class Karni options:

class Order(BaseModel):
    status = StateField(states=["draft", "confirmed", "shipped", "cancelled"], transitions={...})
    due_on = models.DateField()

    class Karni:
        dashboard = True                       # every default below

        dashboard = {                          # or say what to show
            "label": "Orders",                 # the section heading (default: verbose_name_plural)
            "order": 1,                        # position among the sections (default 0)
            "total": True,                     # a count of every row the user may read
            "new_days": 7,                     # a count of rows created in the last 7 days
            "by": "status",                    # a count per value of this field
            "values": ["draft", "confirmed"],  # only these values of `by`
            "counts": {"Due today": {"due_on": "today"}},  # named counts, by list filters
            "recent": 5,                       # the newest rows, in a table
            "columns": ["number", "customer", "status"],
            "date_field": "created_at",        # what "new" and "newest" mean
        }
Key Default What it does
label the model's verbose_name_plural, capitalised The section heading.
order 0 Sections sort by it, then by label.
total True A tile counting every row the user may read.
new_days 7 when the model has created_at, else 0 A tile counting the rows whose date_field is within the last N days.
by the model's first StateField A tile per value of this field: a StateField, a field with choices, or a BooleanField.
values the states that are not terminal (the ones that still need someone), else every choice Which values of by get a tile.
counts {} Named tiles. Each maps a label to the list endpoint's query parameters that count it ({"status": "open"}, {"total__gte": 100}, {"due_on": "today"}). "today", "today-7" and "today+1" are dates relative to the day the page is viewed.
recent 5 How many of the newest rows the section's table shows (0 for none, at most 25).
columns ResourceTable's default columns The table's columns.
date_field created_at when the model has it The date or datetime field behind new_days and the table's ordering.

The server normalizes the declaration (every default filled in) and publishes it as x-karni-dashboard on the model's list operation in the OpenAPI schema. <Dashboard> reads every resource that carries one and renders a Stat tile per count and a ResourceTable of the newest rows. Every number is a list request with page_size=1 and the count's filters, so the row scope, the access rules and the field visibility of the API apply unchanged, and a resource the signed-in user may not list is left out. A count whose filter the list endpoint does not declare says so on its tile instead of showing a wrong number: the filters are the ones ResourceTable offers (a field's name, and __gte / __lte on numbers and dates, see Filtering).

A declaration that cannot work (an unknown key, a field the model does not have, a value by cannot hold, a count without filters) fails karni check with E133 and is left out of the schema. dashboard = False, or no declaration, keeps the model off the page.

On the frontend, <Dashboard> takes resources (which sections, in which order), sections (a function that rewrites the resolved sections before they render), onOpen and onOpenList (a row, or a tile's list with its filters), and slots for every part (Section, Counts, Count, Recent, Empty, Loading, Error). A home page can also compose Stat and ResourceTable by hand.

Home tiles per role (experimental)

<Dashboard> shows one section per model, the same for everyone. GET /api/dashboard/ (karni.tiles) answers the tiles the signed-in person may see, so each role gets its own home, and every installed part adds to it. @karni/ui's <DashboardTiles> draws them.

A tile is a number (stat), a short list (list), a chart (chart) or a component of the app's own (custom). It comes from karni.yaml's dashboard: (an entity's rows, counted or listed through its list endpoint, so the row scope applies) or from code, in <app>/dashboard.py, for figures the server works out:

from karni.tiles import Tile, register


@register(key="shop.revenue", title="Revenue", requires="shop.order:view", size="full")
def revenue(request):
    total = ...  # read the rows the request's user may read
    return Tile.stat_values([("Today", total, "money")], currency="EUR")

A code tile returns its data: stat takes values (label, value, format of money or number, link), list takes columns and rows (each row's link opens it), chart takes kind (bar or line), format and points (label, value). Returning None leaves the tile out.

Who sees a tile: requires (authenticated, * or a permission pattern as in the roles' grants) and, when set, roles. A tile a role does not see is never computed for it. dashboard: places a code tile by its key (its title, order, size and who sees it) or hides it (hidden: true). registerTile(key, Component) draws one tile your way and registerTileKind(kind, Component) a whole kind.

Schema

KarniAutoSchema (the conf default DEFAULT_SCHEMA_CLASS) keeps drf-spectacular's native introspection (choices → enums, null=True → nullable, required from blank/default) and adds:

  • An expand query parameter on list/retrieve (an enum of allowed keys when derivable). In v0.1 the schema documents the unexpanded response shape only.
  • search (contributed by KarniSearchFilter, list ops only, and only when the view actually has search_fields).
  • Vendor extensions for typed frontends: x-karni-resource (router prefix, on list operations of auto-registered viewsets), x-karni-relation ({"resource", "many"} on relation fields whose target has a registered route), x-karni-access on every BaseViewSet operation, and x-karni-auth-mode at the schema root. x-karni-access holds the predicate governing the operation: {"public": true}, {"authenticated": true}, {"role": [...]}, {"owned": "<path>"}, {"where": "<fn>"} (with "matching": {...} for Where(Matching(...))), {"any": [...]}/{"all": [...]}, {"unscoped": "<reason>"}, {"deny": ...}. These are display hints only, and the server enforces. x-karni-actions (experimental) is on the list and retrieve operations of a viewset with row actions, and x-karni-action on each action's operation. x-karni-throttle ("10/hour") is on an operation whose action the viewset's throttle declaration limits, or on a public create, with the rate in force. x-karni-honeypot ("homepage") is on a public create with a honeypot field (rate limits). x-karni-transitions and x-karni-initial are on a StateField's property (lifecycle), and x-karni-dashboard on the list operation of a model that declares Karni.dashboard. x-karni-aggregate is on the aggregate operation of a resource that declares an aggregation (experimental): the groups, values and metrics it takes.
  • x-karni-related (experimental) on the list operation: the model's reverse relations (a reverse fk or many-to-many) whose model has a route, each {"name", "resource", "field", "param", "key", "label"}. name is the relation's name on this model (deals, or Django's deal_set), resource the related rows' router prefix, field their field that points here, param the query parameter their list filters it with (null when the list has no such filter, read from the filterset the list applies), key the field of this model whose value the parameter takes (its primary key), and label the related rows in words. A one-to-one and a hidden relation (related_name="+") are left out. @karni/ui's ResourceDetail builds its related tabs from it. Override KarniAutoSchema.get_karni_related() to drop or relabel an entry.

"x-karni-related": [
  {"name": "events", "resource": "events", "field": "venue", "param": "venue", "key": "id", "label": "Events"}
]
- x-karni-field-groups and x-karni-column-sets (experimental) on the list operation of a model that declares Karni.field_groups or Karni.column_sets: {"layout": "sections" | "tabs", "groups": [{"label", "fields"}]} and {"default": "<set>", "sets": [{"name", "label", "columns"}]}. Each group and set lists only the fields the requester's serializer has, so a field Karni.field_roles hides is never named, and one left empty is dropped. @karni/ui lays out ResourceForm, ResourceDetail and ResourceTable with them (field groups and column sets). Override KarniAutoSchema.get_karni_field_groups() or get_karni_column_sets() to publish others. - A MarkdownField's property carries "format": "markdown" (typed fields). - Operations whose access can admit anonymous callers (Public, Where) list the empty security requirement {}. - SPECTACULAR_SETTINGS["COMPONENT_SPLIT_REQUEST"] = True so file-upload fields keep format: binary on the request side.

Generate a TypeScript client straight off /api/schema/, e.g.:

npx openapi-typescript http://localhost:8000/api/schema/ -o src/api/schema.d.ts

Enum names

Each choice field becomes a shared enum named after the field, such as StatusEnum. When two models have a field of the same name with different choices, Karni names each enum after the model and the field, so Booking.status and Event.status become BookingStatusEnum and EventStatusEnum. drf-spectacular alone would name them EventsBookingStatusEnum or Status469Enum, and that hash changes whenever the choices do, which renames your generated TypeScript types. A field name used for only one set of choices keeps its plain name. One set of choices shared by several models stays one enum named after all of them, such as InvoiceOrderStatusEnum. Two models with the same name in different apps get the app label in front, such as EventsBookingStatusEnum.

The hook karni.api.schema.postprocess_schema_enums does this, and it is the first entry of SPECTACULAR_SETTINGS["POSTPROCESSING_HOOKS"]. Your own ENUM_NAME_OVERRIDES always win. Set them after karni_settings(globals()):

SPECTACULAR_SETTINGS["ENUM_NAME_OVERRIDES"] = {
    "BookingStateEnum": "events.models.Booking.Status",
}

To keep drf-spectacular's own names, put "drf_spectacular.hooks.postprocess_schema_enums" in that list in its place.

Ordering and pagination parameters come from the stock DRF classes (OrderingFilter, and KarniPageNumberPagination with ?page and ?page_size capped at KARNI_MAX_PAGE_SIZE, default 100). An Unpaginated viewset's list is documented as a plain array with no paging parameters.