Skip to content

Declaring an operation

An operation is a spec: a frozen dataclass that says what the operation takes, who may run it, what it acts on and what it returns. There are two.

  • SelectorSpec is a read: a list or a retrieve.
  • ServiceSpec is a write: a service, the row or rows it acts on, and what it returns.

Specs are usually built at module level, at import time. Anything that could need the app registry - reading a Validator's declaration, resolving an annotation - happens on first use instead, so building a spec never does. A declaration no reader could act on is refused where it is written, with ImproperlyConfigured naming the field: a Validator class where an instance belongs, both an instance and a collection selector, a presenter declared on a service and on its output selector, a string where select_related wants a sequence.

Every callable declares what it receives

The service, the selector, extend_queryset, the providers, the preconditions and a pool seed's resolver are all called the same way: with the keywords their signature declares, picked from a pool dispatch builds for the call, and nothing else. A callable that takes **kwargs receives the whole pool but call_context and shapes, which reach a callable only by their names.

Name Holds In the pool of
user The principal Every callable
progress The transport's progress reporter, or null_progress Every callable; the caller's reporter only in the run's pool and its spec's callable affordance conditions'
each validated value, by name What the Validator returned The service
data The Validator's data: the validated values as one mapping, or the instance a DataclassValidator or a PydanticValidator built The service
what the Validator binds, by name A value bound for the call, its Validated.pool The service
instance The row an instance selector resolved The service, its providers
collection The rows a collection selector resolved The service, its providers
each of a selector's reads, by name The checked argument That selector, its kwargs provider
each of a service spec's reads, by name The checked argument The service, its providers
each key a kwargs provider returns The author's value, outranking the caller's The selector or service it is declared on
result The service's return The output selector, which is handed it as instance too
queryset The shaped queryset so far extend_queryset
a registered seed Its resolver's value Every callable
call_context The call's context: the transport's dict, or a fresh one Every callable dispatch resolves that names it, never a **kwargs catch-all; not a seed's resolver or a filter_set
shapes The call's shapes: what the caller sent for the spec's shapes, read-only, empty on a spec declaring none Every callable dispatch resolves that names it but an affordance condition and a write's target selector, never a **kwargs catch-all; not a seed's resolver, a filter_set or the Validator

The fixed names - user, progress, data, instance, collection, result, queryset, call_context and shapes - are reserved: a parameter declared under one is refused, and so is a validated value returned under one, so an argument can never outrank a value dispatch put in the pool itself. A caller naming an argument user is the case that matters. Pool seeds add names of your own, reserved the same way.

A parameter with no default that the call's pool lacks, where a caller could have filled it, is refused before the callable runs, on dispatch and adispatch alike, as InvalidArguments keyed by the parameter with the shape check's own "This field is required.", rather than reaching the callable as a TypeError. That is a read declared optional that the caller left out, whether the selector, its extend_queryset, the service or a precondition takes it, or a Validator parameter the caller left out, which the service takes - unless the spec is partial, whose calls may leave any of those out.

Any other parameter the pool lacks is the declaration's error, and raises as the callable's own TypeError. The argument set is closed, so a name that is none of the selector's reads - or, for the service, none of its Validator's parameters, which is every name when it has no Validator - can never be sent: REJECT refuses it as unknown and IGNORE drops it. A Validator parameter the caller did send, and the Validator did not hand back under that name - a form that pops it in clean(), a pydantic field returned under its own name rather than its alias - has been sent already. Refusing either as a missing argument would ask for a value the caller cannot send or already did, and a client that reads InvalidArguments as its own mistake would send the call again. It is decided at dispatch rather than when the spec is declared, because a registered seed may fill such a parameter, and the seeds are known only then. A transport that knows the seeds of its mount refuses such a spec where it registers it, with check_seeds, as it refuses an optional read over a selector keyword with no default, which a call leaving the read out is refused for, and an array read with no items over a keyword annotated list[int], which would hand it any element a caller sends. It reads a precondition, an affordance condition, the output selector, an extend_queryset, a kwargs or input_data provider and a progress_reporter as well, each against what dispatch hands it: a condition and a progress_reporter are handed only the call's seeds, and a provider the seeds and its seat's reads, never data nor a Validator's value, so one requiring a seed the mount does not register is refused there rather than failing every call. A positional-only parameter with no default is refused on each of them, and an optional read over a keyword with no default on those that are handed the spec's reads, a precondition, an extend_queryset and a provider; only the array check is not run on them.

Four kinds of parameter are never missing: one with a default, **kwargs, *args, and a positional-only one, which dispatch never passes by name. Nothing the output selector declares is refused either: its pool carries no argument, and the service has already run. Where an argument may be left out, give the parameter a default.

Typing a callable

Nothing above reads an annotation, so a service is typed for its author and the type checker rather than for dispatch. Seven Protocols name the shapes dispatch calls: CreateService takes data, UpdateService takes instance and data, and DeleteService takes instance with data optional; ListSelector and RetrieveSelector type a selector's result, and Selector and AsyncSelector describe any selector at all. Every other key of the pool arrives through **extras. implements states the Protocol on the definition, where a type checker such as ty reports a callable that does not conform, and returns the callable unchanged:

@dataclass
class NoteIn:
    title: str


@implements(CreateService[NoteIn, Note])
def create_note(*, data: NoteIn, **extras: Any) -> Note:
    return Note.objects.create(owner=extras["user"], title=data.title)


@implements(DeleteService[NoInput, Note, None])  # reads no input, so no `data`
def delete_note(*, instance: Note, **extras: Any) -> None:
    instance.delete()


create_note_spec = ServiceSpec(
    service=create_note, permissions=[IsSignedIn()], validator=DataclassValidator(NoteIn)
)
delete_note_spec = ServiceSpec(
    service=delete_note, permissions=[IsSignedIn()], instance_selector_spec=the_note
)

NoInput fills the input type of a service that reads none. A delete that does take input declares data with a default of its own, since the Protocol's caller may leave it out.

A read

from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
from typing import Annotated, Any

from django.db.models import QuerySet

from django_service_specs import (
    UNSET,
    DataclassPresenter,
    DataclassValidator,
    FieldMarking,
    Parameter,
    Parameters,
    PermissionCheck,
    SelectorKind,
    SelectorSpec,
    UnsetType,
)
from tests.adapter_app.models import Status
from tests.dispatch_app.models import Note


class IsSignedIn(PermissionCheck):
    def has_permission(self, principal: Any, spec: Any) -> bool:
        return principal.is_authenticated


@dataclass
class NoteRow:
    id: Annotated[int, FieldMarking.handle()]
    title: Annotated[str, FieldMarking.label()]


def notes_of(*, user: Any, search: str = "", ordering: str = "title") -> QuerySet[Note]:
    return Note.objects.filter(owner=user, title__icontains=search).order_by(ordering)


list_notes_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=notes_of,
    permissions=[IsSignedIn()],
    reads=Parameters.of(
        Parameter("search", "string", help="Part of the title, in any case."),
        Parameter("ordering", "string", choices=["title", "-title"], default="title"),
    ),
    select_related=["owner"],
    presenter=DataclassPresenter(NoteRow),
)

kind is SelectorKind.LIST or RETRIEVE. A retrieve returns one row: a queryset is read with .first(), a DoesNotExist raised by a selector written with .get() means the same missing row, and a missing row is reported as not-found unless the spec sets allow_none=True, which makes it the value None - the shape of an optional singleton, or of an upsert's target. On a list, allow_none=True says the selector may return None for "no rows": the result is the empty list, its scope check and preconditions are asked of that empty set as they are of an empty queryset, and the shaping is skipped, since there is nothing to shape. Without it, a list selector's None is passed on as it came, and presenting it fails as the author's error.

A selector may also raise Django's Http404, as get_object_or_404 does. On a retrieve that is the same missing row a DoesNotExist is: not-found, or None under allow_none=True. On a list it is the selector saying "not found", usually of a parent row it looked up before listing that parent's children, and the result is not-found whatever allow_none says. A DoesNotExist escaping a list is different: a list has no missing row, so it is a fault inside the selector and raises. An output selector runs after the write, so a list one raising Http404 raises a RuntimeError chained from it, rather than report a write that happened as not found: a bare Http404 would be answered 404 by Django's handler and by DRF's. Only the selector's own raise is read this way: an Http404 from its extend_queryset passes through.

reads is the selector's whole input. There is no Validator in front of a read, so these Parameters are what the closed argument set and the shape check hold the caller to: an argument the spec does not declare is refused before the selector runs.

shapes sits beside reads, for the arguments that shape what the presenter renders rather than which rows are read: which fields, a query over each row. They are Parameters of their own and part of spec.parameters(), after the reads, so the schema, the closed argument set and the shape check cover them as any argument. No shape is in the selector's pool under its own name, so the selector, its extend_queryset and its filter_set never receive one as an argument: what the caller sent for them reaches the presenter on PresentationContext.shapes, and any callable that names the shapes seed, which holds the same mapping. A selector that eager-loads by the query its presenter renders reads it there. A shape a read or a filter also declares is refused when the spec is built, as is one named for a seed dispatch provides and one the kwargs provider is annotated to fill, since no provider's values reach them. A presenter reading them is shown under shaping each row by the call.

select_related, prefetch_related and annotations are applied to the queryset the selector returns, in that order, then extend_queryset, with the shaped queryset as queryset, and filter_set last. Declaring any of them on a selector that returns something other than a queryset is refused at dispatch.

filter_set is a django-filter FilterSet class, installed with the filter extra. One that declares no filters - its base_filters missing, empty or None - is refused with ImproperlyConfigured when the spec is built, unless it is a django-filter FilterSet class: it declares no Parameters, so it would be handed none of the caller's data and never filter. A duck-typed stand-in taking (data, queryset) declares its filters in base_filters, and a step narrowing the queryset by no argument belongs in extend_queryset. A real FilterSet declaring no filters is accepted, and narrows nothing. Its filters are reads: each is read as a Parameter by filter_set_parameters and joins reads after the author's own, named as django-filter reads it - price_min and price_max for a range - so the schema, the closed argument set and the shape check cover every filter, and a filter named like a read declared differently is refused. Labels are no difference: a read redeclaring a filter with labels of its own, or none, stands as the author wrote it. Every filter is optional. A choice filter's values carry the labels they were declared with as choice_labels, which a schema states as titles; a label that is text, a str or a lazy translation, is kept and any other leaves its value unlabelled, as a bare value is. A lazy translation among them stays lazy until a schema renders it, in the language active then, and hashing a spec renders none. An OrderingFilter's descending label is the exception: django-filter builds it when the filter is declared, so it is fixed in the language active then. A number filter, and each bound of a numeric range, is a decimal string, which its DecimalField reads exactly: read as a float on the way, a key past 2**53 would match its neighbour's row. A JSON number is still taken. Each such decimal is bounded at minimum=-1e50 and maximum=1e50: django-filter's number filter refuses a value past 1e50 and leaves a range's bounds and every negative value open, while an integer column's conversion builds every digit of a value such as "1E+999999999", which holds a worker for minutes. So the shape check refuses either side of the line before the FilterSet is reached. A CSV number filter is an array of the same bounded decimals: Parameter("pks", "array", items="string", format="decimal", minimum=-1e50, maximum=1e50), whose format and bounds describe each element. ?pks=1,2 still splits, since no decimal holds a comma, each value reaches the filter with every digit it was sent with, a fraction included, and one past the line is refused at its index in the list. The schema states each decimal's format ({"type": "string", "format": "decimal"}) and no bound, since JSON Schema applies minimum and maximum to a number instance only.

A selector spec also takes kwargs, preconditions and progress_reporter, which a write declares the same way. Its kwargs provider is called from the base pool and its reads, and on a selector nested in a write scopes the lookup. Its preconditions run on what its selector found, never on a missing row. A nested selector declaring permissions (Unrestricted() included), preconditions or a progress_reporter, or an output selector declaring kwargs, is refused when the write is built: dispatch never runs them, and the spec being dispatched is what authorizes. permissions is required on a spec that is dispatched or registered, so to reuse such a selector spec as a nested one, nest spec.derive(permissions=None).

A write

A ServiceSpec names its service and, at most, one target selector:

  • instance_selector_spec, a RETRIEVE, for a service that acts on one row. It arrives as instance, and a missing row is not-found: the service never runs and the Validator is never asked. With allow_none=True on the selector, a missing row arrives as instance=None instead, which is how an upsert is written.
  • collection_selector_spec, a LIST, for a bulk operation. The rows arrive as collection.
  • Neither, for a create.

output_selector_spec re-reads what the service produced, with its return in the pool as result. It is how a write returns a row with fresh annotations or prefetches, or a list after a bulk change; the relation-write example uses one. Without one, the service's own return is what is presented, and allow_none=True on the spec declares that it may be None, so its output schema admits "null".

atomic=True, the default, runs the service inside transaction.atomic(). metadata holds a project's own per-operation facts, stored as given, for its own checks or audit hooks to read.

reads are the arguments the service, its providers and its preconditions read with no Validator in front of them - the project_pk a create is scoped by - named after a selector spec's. They are checked as a read's are and handed to each callable that declares them, never to the Validator.

shapes are the arguments that shape what the presenter renders, as on a read: never handed to the Validator, a provider, a selector or the service under their own names, and reaching the presenter, whether that is the spec's own or its output selector's. A callable that names the shapes seed is handed them, the output selector included, but not the Validator, an affordance condition, a seed's resolver, a filter_set or the write's target selector, whose lookup is the same on every route and is handed none. A selector nested in a write, its target or its output selector, declaring shapes of its own is refused: the write's call is the one presented, so they are declared on the write.

spec.parameters() is everything the write takes: its target selector's reads, its own, its shapes, then its Validator's parameters. A name two of them declare is refused - two sources claiming one argument is a declaration bug, and a last-wins merge would hide which declaration a transport describes. The selector sees only its own reads, and the Validator only its own parameters.

Partial updates

partial=True declares an update that sends only what changes, as an HTTP PATCH does. Dispatch does not refuse an absent Validator parameter of such a call, at any depth, and tells the Validator through ValidationContext.partial. The spec's reads and its target selector's stay required as declared unless a kwargs provider fills them, or may fill one no provider requires itself, so a partial update still names its row, and a value that is sent is checked as on a whole call. parameters() is unchanged: required still says what a whole update needs. spec_input_schema is what a client reads, so it requires none of the Validator's parameters at any depth, and keeps the reads required as dispatch does.

A Validator returns only the fields the caller sent, or refuses the call. FormValidator binds only the sent fields; DataclassValidator and PydanticValidator cannot, because each builds or validates every field, and say so with supports_partial = False. With those, an update a caller may send in part declares each such field optional, as AuthorPatch below does.

Two declarations are refused with ImproperlyConfigured when the spec is built, rather than on every call:

  • partial=True with no validator. Only a Validator's parameters are relaxed, so with none the declaration changes nothing.
  • partial=True over a Validator whose supports_partial is False, such as the dataclass and pydantic adapters. Every call would be refused. The message names the service and the Validator's class; a partial spec needs a Validator that can bind only what was sent, such as a FormValidator, or one of its own.

Many rows in one call

many=True declares a call carrying a list of rows under one argument, many_argument, "items" unless it names another, for one run of the service over all of them, inside one transaction under atomic:

@dataclass
class NoteIn:  # one row
    title: str


def add_notes(*, user: Any, data: list[NoteIn], archived: bool = False) -> list[Note]:
    return [Note.objects.create(owner=user, title=row.title, archived=archived) for row in data]


add_notes_spec = ServiceSpec(
    service=add_notes,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(NoteIn),  # what each row is
    many=True,  # the rows travel under "items"
    many_min_length=1,  # an empty list is refused rather than run on no rows
    many_max_length=200,  # and so is one past 200, before any row is read
    reads=Parameters.of(Parameter("archived", "boolean")),  # asked once, beside the list
)

Each row is shape-checked and validated by the spec's Validator, which declares what a row is, before the service runs, and every failing row is refused in one InvalidArguments keyed by the row's int index under many_argument, beside the shape check's refusals of the other rows; see the refusal tree. Beside the list the call takes the spec's reads and nothing else, so a value asked once for the whole call - a confirmation - is a read. The service receives the rows' data as a list under data, and their values as a list under many_argument; neither is spread by field.

Dispatch hands the rows to the Validator's validated_many() in one call, each under its index in the caller's list. By default that validates each row on its own through validated(), and refuses a value a row binds, since the service runs once for every row. A Validator whose library validates a list as one - list-level checks, one bound object for the call - overrides it: its refusal is the list's node, each failing row under its index and a message about the whole list under non_field_errors, and what it binds in Validated.pool reaches the service once. A row the shape check refused is not handed to it, so the indices may have gaps.

The list is an array parameter, so it is bounded as one: many_min_length and many_max_length are its min_length and max_length. Neither is declared by default, so an empty list runs the service on no rows, and many_min_length=1 is how a spec refuses one. Where no many_max_length is declared, the SERVICE_SPECS_MAX_ARRAY_LENGTH setting bounds the list, 1000 rows by default, since every row is a Validator run inside one transaction. A list outside either is refused at many_argument as a whole, {"items": ["Ensure this field has no more than 200 elements."]}, before any row is checked, beside the top level's other refusals. Either is refused on a spec that is not many.

A many spec must declare a Validator, and no instance_selector_spec, since a list of rows edits no single row. It may declare a collection_selector_spec: the set its rows edit. Dispatch resolves and scope-checks it as for any spec acting on a collection, and target= stands in for it. The service receives it as collection, and validated_many() as the context's target, so a Validator binding each row to a member of the set can read it. Without one the call resolves no target, and target= is refused. A condition on the row among its affordances is refused either way. With no output selector its result is kind="list", unless the service returned None, and the service must return the rows: a mapping, a str, bytes or anything else that does not iterate is refused as ImproperlyConfigured, naming the service and what it returned. It is the author's error rather than a validation error, since the service has already run and its write stands. With an output selector the return is only what the selector re-reads, so any value is allowed.

A service returning rows

returns_many=True declares that the service's own return is a list of rows, each presented by the spec's presenter: the output half of many, for a service that takes one set of arguments and hands back rows. The input is left alone, so the call's arguments are declared as they would be without it:

def archive_all(*, user: Any) -> list[Note]:
    notes = list(Note.objects.filter(owner=user, archived=False))
    for note in notes:
        note.archived = True
        note.save(update_fields=["archived"])
    return notes


archive_all_spec = ServiceSpec(
    service=archive_all,
    permissions=[IsSignedIn()],
    presenter=DataclassPresenter(NoteRow),  # what each row is
    returns_many=True,  # the service hands back rows: each is presented
)

Dispatch reports a return that is not None as kind="list", and present renders it row by row. Its output schema is an array of the presenter's item, never paged: the rows are what the service returned, all of them, and a transport that pages a list pages by the spec rather than by the result's kind (see serving a page). A None return stays one value, presented as None, as a many service's is, so allow_none still decides whether the schema admits "null". A return that is not a set of rows (a single mapping or model row, a str or bytes, anything that does not iterate) is refused as ImproperlyConfigured naming the service, after the service has run and its write stands: return the rows, or drop returns_many to present one value.

It is refused when the spec is built beside an output_selector_spec, whose kind decides what is presented, and beside many, which presents its return as a list already.

Providers and preconditions

Four declarations put the author's code between the checks and the run. Each is called with the keywords it declares, like any other callable here, and is sync-only: an async def one is refused when the spec is built.

  • kwargs returns extra pool entries, merged after the caller's arguments, so a key it answers is the author's value whatever the caller sent - a tenant, a scope. A value of UNSET declines a key the provider is annotated as able to decline (or any key of an untyped provider) and leaves the caller's in place; a key it is annotated to fill is the server's, so the caller's value for it is checked and then dropped.
  • input_data, on a write alone, returns values merged over the caller's arguments before the Validator sees them, so a server-owned field - an owner, a status - is the author's. A Validator field it fills or may fill is not demanded of the caller, and dispatch refuses a required one the provider leaves out before the Validator runs. A value the caller sends for a field the provider is annotated to fill is dropped, not used in its place. The Validator is what consumes it, and the service is handed none of it directly, so a spec that declares input_data with no Validator is refused with ImproperlyConfigured when it is built: declare a Validator, or use kwargs for a value the service reads.
  • preconditions are raise-to-abort rules, in declaration order, after the affordances and before the service, outside its transaction. What the first to raise raises reaches the caller as it is. One answering with a coroutine or an async generator is refused with ImproperlyConfigured rather than read as a pass.
  • progress_reporter returns a ProgressReporter the run reports to beside the transport's - a task record, an audit trail - called only for a run that takes progress, once its keywords are bound: on the run's first report, or before the await of an async def run. A call refused before its run never calls it; a selector spec's selector is its run, so one refused at its object check, its scope check or a precondition may already have. Nothing but the run reports to it: a selector spec's extend_queryset, its preconditions and the affordance conditions answered for its rows read progress from the pool, the transport's reporter, as a service spec's conditions do.

Both providers are called from the base pool, the reads and the resolved target, and never see the Validator's values. A provider returning a name dispatch seeds itself is refused, so a provider can outrank an argument and never a seed.

A provider annotated to return a TypedDict says which keys it fills before it runs, and provider_keys reads them: filled, and declinable for a key whose value admits UnsetType. A key a provider fills or may decline, and every key an untyped provider's values reach, is not demanded of the caller: dispatch checks it once the provider has answered, after the class-level permission check and, for a Validator field, before the Validator runs, and refuses a required one nobody filled, a declined one included. The exception is a read a provider takes by name with no default, as pk in kwargs=lambda *, pk: {...}: a provider is handed the caller's reads and the seeds, never another provider's answer, so only the caller can supply it, and dispatch demands it of the caller however a provider may fill it. bind_arguments runs no provider, so it leaves that check to the Validator. So a permission check reading such a key from its arguments uses .get. The caller's value for a filled key is dropped, and for a declinable one it stands beneath the provider's answer. The provider's values reach these: a selector's kwargs fills that selector's reads, a service spec's kwargs its reads, and input_data its Validator's fields. A provider annotated to fill a parameter declared anywhere else - input_data naming a read, kwargs naming a Validator field or the target selector's read - is refused with ImproperlyConfigured when the spec is built or, for a Validator field, when parameters() is assembled. So is one annotated to fill a many spec's list, the many_argument, or to possibly fill it: no provider reaches it, and a Validator field of the same name does not exempt the key.

A call leaving out a read its own provider requires, though that provider may fill it, is refused with InvalidArguments before the provider runs:

def project_scope(*, project: str) -> dict[str, Any]:
    return {"project": project.strip().lower()}


def file_in_project(*, project: str) -> str:
    return project


file_in_project_spec = ServiceSpec(
    service=file_in_project,
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("project", "string", required=True)),
    kwargs=project_scope,
)
# A call leaving `project` out is refused as InvalidArguments, before the
# provider runs, though the provider's keys are otherwise not asked of the caller.

project_scope is untyped, so it may fill any key. It is handed the caller's reads and never another provider's answer, so project can only come from the caller.

server_owned_keys gathers what every provider of a spec fills, with the seeds' names, and provider_reached every parameter a provider fills or may fill, less a read a provider requires itself, which the shape check relaxes. None of them is a parameter dispatch demands, so a transport building an input schema of its own subtracts the set from what parameters() lists:

class Owned(TypedDict):  # the keys the provider fills, readable before it runs
    owner_id: int


def the_owner(*, user: Any) -> Owned:
    return {"owner_id": user.pk}


@dataclass
class NoteCreate:
    title: str
    owner_id: int


def create_note(*, data: NoteCreate) -> Note:
    return Note.objects.create(title=data.title, owner_id=data.owner_id)


create_note_spec = ServiceSpec(
    service=create_note,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(NoteCreate),
    # Merged over the caller's arguments before the Validator sees them, so
    # the owner is the signed-in user whatever the caller sends.
    input_data=the_owner,
)
# server_owned_keys(create_note_spec) names "owner_id": a transport's schema
# need not ask for it, and dispatch does not demand it of the caller.

On a many spec, the keys an input_data provider fills are fields inside each row, merged over every row, so subtracting the set from the top-level parameters() - the list and the reads - removes nothing: they belong out of the list's items instead. spec_caller_input_schema does both: the schema a transport advertises, less what the server fills at the top and in each row, with what a provider may fill left out of required at each level. The list stays offered and required, as dispatch demands it of the caller, which is why no provider may be annotated to fill it.

Parameters

Parameter is one thing an operation takes, and every transport describes itself from it rather than from whichever validation library the spec happens to use: a JSON Schema, argv options, the closed argument set and the shape check are all derived from the same declaration.

  • type is a JSON type: string, integer, number, boolean, array or object. JSON's own, because that is what crosses every wire the kernel serves: a JSON-RPC call, a queue row, and argv once it has been read. The one other type is file, a Django File: what a multipart body carries beside its fields, and what a Python caller hands a command or a task. No JSON caller can send one, and it declares no choices. any declares no type, as an unannotated argument does: a key that may be 3 or "abc". The value is handed on as it arrived, with no coercion, so a query string's "3" stays the string "3", and the schema states no "type" for it. It takes no choices, format, fields, items or bound, and an array's items never name it: an array with no items takes any element already.
  • format is decimal, date-time, date or uuid, on a string: a value JSON cannot carry, which travels as a string for the Validator to decode. A uuid is an identifier's: the shape check refuses a string that spells none - "null", "undefined", the parameter's own name - with "Enter a valid UUID.", read as models.UUIDField.to_python reads one, so a lookup on a UUID column is never handed a value it would raise Django's ValidationError for. That includes a value padded with whitespace, which forms.UUIDField would strip first and the model field refuses. A UUID that parses reaches the callable in its canonical spelling, str(uuid.UUID(value)) - lowercase and hyphenated, whether it was sent braced, as a urn:uuid:, without hyphens or in upper case - and still as a string, never a uuid.UUID. Declared choices are held in that spelling too, with the keys of their choice_labels, so a listed id matches its value sent in any spelling and the schema advertises the canonical one. A choice that spells no UUID is kept as listed. Two spellings of one id are then one choice: the first keeps its place and its label, a later one is dropped, and the schema lists the id once. Only a choice the format rewrites is collapsed; any other repeat stays as listed. An OutputField's choices are held and collapsed the same way, the first display winning, so its schema and the display a row is spoken with are keyed by the spelling str() gives a model's UUID; an output value is not canonicalised, so a row presenting another spelling passes through unspoken. On an array it describes each element, as choices do, and is decimal on items="string" alone: a number element is read as a float on the way and loses a fraction's digits past a float's precision, where a decimal string is handed on as it was sent.
  • items is an array's element: a JSON type name for a flat list, or the Parameters of the object each row is. fields is the same for an object. Nesting is what lets a write declare its rows, so a malformed row is refused by the declaration rather than reaching a constructor.
  • choices, nullable and required mean what they say. choices on an array constrains each element.
  • minimum and maximum bound a number, inclusively: an integer, a number or a decimal string, refused in the words Django's MinValueValidator and MaxValueValidator use. Each is an int or a finite float, and a bound on any other type is refused where it is written. A decimal string is compared as the decimal it spells, by its exponent, so "1E+999999999" is refused without building the integer it names. The schema states both as "minimum" and "maximum" on an integer or a number, and on a decimal string neither, because JSON Schema applies them to a number instance only: a validating client would ignore them, and the shape check enforces them either way. On an array they bound each element, as its format describes each: an array of integer or number, or of decimal strings, takes them, and an element past one is refused at its index. The list's own count is min_length and max_length's, so an array may carry both pairs, and the schema states the element's on "items". No integer is bounded unless it says so, and one a selector or a service hands the database past its column's range is the database's to answer. On SQLite, past 64 bits, an __in lookup and a write raise the driver's OverflowError on every Django version, and so does any lookup on Django 4.2; from 5.0 an exact or a comparison lookup is answered without the query, as no rows or every row. Bound an integer that reaches a column unchecked, as a key a selector looks rows up by does. Four lookups the kernel makes itself with a key a caller sent answer such a key as one no row holds, on every version: the forms adapter's model choice field and a ModelForm's integer column (the forms adapter), a relation write's scoped match (relations) and resolve_principal. A FilterSet's filters are held to what any driver binds: where a filter's path ends on an integer column - its own, a foreign key's, or the key of the row a many-to-many or a reverse foreign key reaches - and its lookup reads the value as the column's - exact, gt, gte, lt, lte, in and range, a RangeFilter's bounds and a CSV filter's elements included - a number past a signed 64-bit integer is refused before the query, as max_value or min_value at the argument that carried it, on every version (the codes a refusal carries). A number inside 64 bits is answered whatever range the column states, so gte=-1 on a PositiveIntegerField is every row on every version, as an exact -1 is none. A model choice filter's key past the range of the column its rows are matched on is no choice, refused as invalid_choice in its form field's words. A filter with a method, a lookup that reads its value as text, such as contains, a path through a transform or to an annotation, a relation over more than one column, and an object that is not a django-filter FilterSet are left to the database, as above. A number filter on a decimal or float column takes any number inside 1e50, except on Django 4.2.0 and 4.2.1, where a decimal past the column's max_digits raises in Django's own decimal handling, which this does not change.
  • min_length and max_length bound how many elements an array takes, inclusively, each a non-negative int, and are refused on any other type. An array that declares no max_length is still bounded, by the SERVICE_SPECS_MAX_ARRAY_LENGTH setting, 1000 by default; see how long a list may be. The schema states them as "minItems" and "maxItems".
  • choice_labels names the choices for a reader, as a mapping of a choice to its label or as Django's pairs. The labels constrain nothing; the schema states each as a choice's title. A label may be a lazy translation.
  • items_nullable is the element's own nullability, as list[int | None] declares it: whether a null may stand where an element would. It is independent of nullable, which is the array's, and it needs items, since an undeclared element admits anything already.
  • default is UNSET when none is declared, so a default of None stays a real default. It is reported, not applied: whether an omitted argument arrives as its default is the validating library's behaviour.
  • reflected says the parameter was read off a callable's signature by an adapter rather than written by an author. It matters only on a read: a reflected read named like a registered pool seed is filled by the seed rather than refused. It takes part in equality and hashing, and no schema carries it.
  • json_schema_extra carries the JSON Schema keywords no field of a Parameter spells - a pattern, a string's maxLength, uniqueItems - as a mapping of keyword to value, added to the parameter's schema node. It is how an adapter whose library declares more than a Parameter carries keeps it on every route. A keyword a field states is refused, naming the field to declare it on, whether or not this parameter sets that field; so is a value JSON cannot carry. It is held as a copy of its own, and it is advertised, not enforced: the shape check never reads it.

Any other bound - a length, a Validator field's max_value - is the Validator's alone, and a json_schema_extra stating one advertises what the Validator enforces. A Parameter's bounds are for the line a caller must not cross before any Validator runs.

Parameters is an ordered set of them. Parameters.of(a, b) builds one, + joins two, and a name declared twice is refused either way.

The Validator

A Validator turns JSON-like arguments into the values a service receives. The contract is two methods, and two more methods, an attribute and a property with defaults:

  • parameters() declares what it takes, as Parameters. It must never query, because a transport describes a spec before any call. A Validator that describes itself by the call it is asked for - a serializer whose fields read the transport's request - opts in by declaring parameters(self, *, call_context=None): every ask inside a call then hands it the call's context, the same dict its ValidationContext carries, and every ask outside one hands it None - at registration, for a schema handed no context, and for every other reader describing the spec before a call - so the declaration must hold without it. A transport describing a spec may instead hand a stamped dict with no call under way, where request and view are None, so it must hold without those too. Opted in or not, it never queries. A Validator declaring no keyword is asked as before, as is one whose parameters takes only **kwargs, or is a functools.wraps wrapper that does not name the keyword itself: the method's own signature decides. A transport that asks a Validator itself during a call asks it as dispatch does, through validator_parameters with the call's dict, so a Validator that opted in is handed it there too. The helpers a transport calls during a call take the same call_context=: apply_server_arguments, check_requested_input and server_owned_keys. So do those a transport describes a spec with: spec_caller_input_schema, spec_input_schema and provider_reached, so a field declared to one transport is offered there; handed none, they read the declaration made to no call. Those that only check a spec - check_server_arguments, check_seeds, seed_named_parameters, unreceived_fields - are describe-time, and read the declaration it makes to no call wherever they are called, a transport's check of a binding against one call's seeds included. ServiceSpec.parameters() and SelectorSpec.parameters() take the same keyword, which a selector spec ignores, so a subclass overriding either must accept call_context, which dispatch now passes: an override written parameters(self) raises TypeError under dispatch and when a schema is read.
  • validate(arguments, context) returns the validated values keyed by name, or raises InvalidArguments. It receives only the arguments its own parameters() declare, already through the shape check, and a ValidationContext carrying the principal and the resolved target. It may query - a uniqueness check does - and the target is there so that an update's check can exclude the row being updated. The context also says whether the call is partial, and carries the call's resolved seeds as ambient: user, progress and every seed registered through PoolSeeds, such as an HTTP adapter's request, for a library whose validation reads what its caller registered. It is read-only at its top level; its values are the call's own live objects, which a Validator must not mutate. resolved carries the target under the pool name the service receives it by - {"instance": row}, {"collection": rows}, or empty for a create - so a callable the Validator resolves through the pool names it as a selector or a service does.
  • validated(arguments, context) is what dispatch calls: a Validated carrying the values the service is spread with, the call's data, and a pool of any other value bound for the call, such as the bound object a library validated through. The default wraps validate(), with the values as data and nothing bound, so a Validator overrides it only where its data is not that mapping. A bound value named after a seed, a validated value or a parameter is refused.
  • validated_many(rows, context, *, many_argument) is what dispatch calls on a many spec instead: the rows by index, and a Validated whose values hold the rows' values under many_argument alone. The default is validated() on each row.
  • supports_partial says whether validate() can honour a partial call by returning only what was sent. It is True by default. A Validator that builds every field sets it False, and a partial spec over it is then refused when the spec is built. A class sets it as a class attribute; an adapter whose answer depends on what it was built over sets it on the instance in __init__, and the spec reads the instance.
  • unsendable names the fields the Validator requires that its parameters() leaves out, as a frozenset of names. No caller can send such a field, since a transport offers only what parameters() declares, so a transport can read it where it registers a spec and refuse the spec there rather than on every call. It is empty by default, and stays empty on the dataclass, form and pydantic adapters, which declare every field they require. An adapter whose library can require a field it does not declare overrides it with a property, which may read what the instance was built over. Unlike supports_partial, the default is a property with no setter, so an instance of a class that inherits it, or overrides it with a property, cannot assign it. A plain class attribute also answers a reader, but the type checker does not hold its type to frozenset[str], and an instance can then assign it.

Three things a newcomer may look for are absent on purpose:

  • It is nominal. An adapter subclasses Validator, and subclassing is the opt-in. A structural check on a method name would let stock classes through by accident: an is_valid method matches a Django form, a validate method matches a pydantic model class, and neither was written to this contract.
  • There is no instance or many argument. The row a call acts on is target resolution, and many rows are the spec's many, handed to validated_many(). partial arrives in the context, because it is the spec's statement about the call, not the Validator's.
  • It is sync-only. It may query, so the async entry point runs it in Django's thread-sensitive executor; a validate, validated or validated_many declared async def is refused when the spec is built.

The dataclass adapter

DataclassValidator is the reference adapter: what any adapter owes the kernel, with nothing but the standard library and Django. It reads a dataclass's fields and annotations into Parameters, and builds the instance from the arguments, nested dataclasses included. The call's data is the instance it built, so a service declaring data receives an AuthorIn and one declaring the fields by name receives them as before. It cannot validate a partial call, so a partial spec over it is refused when the spec is built.

@dataclass
class BookIn:
    title: str
    price: Decimal
    status: Status = Status.DRAFT
    published_on: date | None = None
    pk: int | None = None  # present for a row that exists, absent for a new one


@dataclass
class AuthorIn:
    name: str
    books: list[BookIn] = field(default_factory=list)


@dataclass
class AuthorPatch:  # every field may be left out, and then holds UNSET
    name: str | UnsetType = UNSET
    books: list[BookIn] | UnsetType = UNSET


# A spec takes a Validator instance: the adapter, wrapping the declaration.
author_validator = DataclassValidator(AuthorIn)
Annotation Declares
str, int, float, bool Their JSON types. float also takes an integer; nothing else crosses types, so true is not an int. Through dispatch, the shape check hands an int field a whole float such as 2.0 as 2. An integer past a float's range is refused as no number, "Enter a number.", since no finite float stands for it.
Decimal, datetime, date A string with the format it decodes from. A decimal also takes a JSON number, and an integer exactly, whatever its digits.
X \| None Nullable. Inside a list, list[X \| None], the element is: items_nullable.
Literal[...], an Enum (Django's TextChoices and IntegerChoices included) Choices. An Enum decodes to the member. A Django Choices enum's labels are its choice_labels; a plain Enum's member names and a Literal label nothing.
list[X] An array. list[SomeDataclass] is an array of rows, each declared as nested Parameters. list[Decimal] declares the decimal format for each element, so each is read as a decimal is, a JSON number included, and ?prices=1.5,2.25 is two of them; a list of dates or date-times is an array of strings, since an element takes no other format. A list declares no length, so the SERVICE_SPECS_MAX_ARRAY_LENGTH setting bounds it. A homogeneous tuple[X, ...] is the same array, decoded into a tuple; a fixed-length tuple[A, B] is refused.
a dataclass An object, with its fields as nested Parameters.
dict[str, X], for any X above An object with no declared fields, as the pydantic adapter declares one, since Parameters cannot say "every value is an X". Each value is decoded as X and refused under its own key: {"scores": {"rigour": ["Expected an integer."]}}. Only a str key, since a JSON object has no other.
X \| UnsetType The argument may be left out, and the field then holds UNSET.

A field with a default or a default_factory is optional; one with neither is required. An annotation outside the table is refused, naming the field. A dict[str, X] field is declared and refused as the table says, and only a dict: a Mapping[str, X] or a tuple[str, X] is outside the table, though its first argument is str:

@dataclass
class ReviewIn:
    title: str
    scores: dict[str, int]  # any criterion, each an integer


def record_review(*, data: ReviewIn) -> ReviewIn:
    return data


record_review_spec = ServiceSpec(
    service=record_review,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(ReviewIn),
)
# `scores` is declared as an object with no fields; each value is decoded as an
# int and refused under its own key: {"scores": {"rigour": ["Expected an integer."]}}.

What DataclassValidator(AuthorIn) declares, then: name, a required string, and books, an optional array whose rows take a required title, a required price (a string in the decimal format), a status with the choices draft and published and the default draft, a nullable published_on in the date format, and a nullable integer pk. Its validate() returns the books as BookIn instances, which is what the relation writes read a row from.

Two rules on that example are easy to miss:

  • A row that updates must declare its key. A relation write matches an incoming row to an existing one by primary key, so BookIn declares pk: int | None = None: present for a book that exists, absent for a new one. Without it no incoming row matches, and every update replaces every row. Nothing fails when that happens, which is why it is said here.
  • An update's fields should be omittable. AuthorIn.books defaults to an empty list, which is right for a create and wrong for an update: an author updated without books would arrive with books=[] and lose them all. AuthorPatch declares every field X | UnsetType = UNSET, so a field the caller left out arrives as UNSET, and the mutation helpers leave it alone.

The mutation helpers drop UNSET themselves, so a partial input goes to them as it is. Code that reads one itself has two helpers. is_supplied is value is not UNSET as a type checker reads it: UNSET is a value, so the identity check narrows nothing, and is_supplied(patch.title) narrows str | UnsetType to str. supplied_fields returns the fields of a dataclass instance or a mapping that are not UNSET, None kept. It is shallow: a nested input, a list of rows or a model instance is returned as the caller's own object.

@dataclass
class NoteQuery:  # every filter may be left out, and then holds UNSET
    title: str | UnsetType = UNSET
    archived: bool | UnsetType = UNSET


def matching_notes(*, user: Any, query: NoteQuery) -> QuerySet[Note]:
    # Only the filters the caller sent: one left out filters nothing.
    return Note.objects.filter(owner=user, **supplied_fields(query))


def heading(query: NoteQuery) -> str:
    if is_supplied(query.title):
        return query.title.upper()  # narrowed to ``str``
    return "All notes"

An offset-less date-time is made aware in the current time zone when USE_TZ is on, as Django's forms do, so a date-time means the same instant whichever library validated it. Every failure is reported at once, as one InvalidArguments tree; Arguments and refusals describes it.

Output and the Presenter

A Presenter turns one value an operation produced into JSON-like data. It is the output-side counterpart of the Validator:

  • output() declares the result as an Output, an ordered tuple of OutputField. It never queries. The declaration is what a reader that never renders needs: an agent tool's output schema, a command's table header when there are no rows, a confirmation page. An HTML transport hands the row to a template and never renders it, and still reads the declaration.
  • present(value) renders one value. Dispatch's present hands a list's items over one at a time unless the Presenter batches them (below), so a Presenter never has to guess whether it was given a row or a collection. It may query, and it is sync-only: an async def present is refused when the spec is built.
  • presented(value, context) is what dispatch's present calls: the value, and the call's PresentationContext, carrying its principal, the target a service spec resolved, and its resolved seeds as ambient, read-only at its top level, its values the call's own live objects, not to be mutated. It also carries what the caller sent for the spec's shapes, as shapes, and the call's context as call_context, the one dict the stages of a call share (the call's context). The default is present(value), so only a Presenter whose library renders under a context - a field defaulting to the current user, a link built from a request a transport registered as a seed - overrides it. Dispatch carries the context on the DispatchResult as context; a result built by hand has none, and is presented with None.
  • presented_rows(values, context) is what dispatch's present calls for a list: every row at once, as a tuple, with the one context they all share. The default is presented(value, context) for each row, so only a Presenter that batches something over its rows overrides it (presenting a page in one call).

An OutputField's type is one of the JSON types, or any for a value whose JSON type is open, such as a computed field or a JSON column: its schema is {} rather than a claim that it is a string. An OutputField carries what a reader needs beyond a name and a type: a label, choices as value-and-display pairs (a table shows the display, a schema states it), always_present for a key that some rows omit, and a FieldMarking saying who the field is for. Its json_schema_extra carries JSON Schema keywords no field of it spells, as on a Parameter, refusing those its fields state. It describes what the presenter renders and constrains nothing. The FieldAudience is CONTENT by default, LABEL for the field that names the record, HANDLE for an opaque identifier that is passed to other tools and never read out to a person, and HIDDEN for plumbing. A marking may also carry a ValueFormatter, which renders the field's value for that audience, a date-time in the active time zone say, and states the JSON type it produces (see formatting a value). The kernel carries the marking on the declaration and applies it only for a caller that names an audience, through present_for_audience; present, and so every HTTP response, serves every field. See paging and projection.

DataclassPresenter declares the output as a dataclass and reads each field off the value by attribute, so the value is usually a model row and is never converted into the dataclass first. A nested dataclass field is read the same way, and a list field may be a related manager, read through .all() so a prefetch is used. A Decimal is rendered as its string, a date or date-time in ISO 8601, an Enum as its value. A marking is declared in the field's annotation, as NoteRow does above: Annotated[int, FieldMarking.handle()].

A read's presenter is its own presenter. A write's is its own, or its output selector's when it declares none, and declaring both is refused. A presenter on an instance or collection selector is never read, because the service consumes those rows rather than returning them.

Presenting a page in one call

A Presenter that looks something up for each row - a count, a related record from another store, a permission answered per row - would otherwise ask once per row. presented_rows hands it every row being presented, so it asks once:

class BooksWithEditions(Presenter):
    """Each book with its number of editions, counted once for every row presented."""

    def output(self) -> Output:
        return Output(
            (
                OutputField("id", "integer"),
                OutputField("title", "string"),
                OutputField("editions", "integer"),
            )
        )

    def present(self, value: Book) -> dict[str, Any]:
        return self.presented(value, None)

    def presented(self, value: Book, context: PresentationContext | None) -> dict[str, Any]:
        return self.presented_rows((value,), context)[0]

    def presented_rows(
        self, values: Sequence[Book], context: PresentationContext | None
    ) -> list[dict[str, Any]]:
        counts = dict(
            Edition.objects.filter(book__in=values)
            .order_by()
            .values_list("book")
            .annotate(Count("pk"))
        )
        # One presented value per row, in the order the rows were given.
        return [
            {"id": book.pk, "title": book.title, "editions": counts.get(book.pk, 0)}
            for book in values
        ]


def catalogue(*, user: Any) -> QuerySet[Book]:
    return Book.objects.order_by("title")


books_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=catalogue,
    permissions=[IsSignedIn()],
    presenter=BooksWithEditions(),
)

The rows are the ones being presented and no others. A transport serving one page slices the result before presenting it, so presented_rows receives the page's rows rather than the whole catalogue, and the lookup is one query whichever page size the caller asked for:

def first_page(user: Any, limit: int) -> list[dict[str, Any]]:
    result = dispatch(books_spec, principal=user, arguments={})
    page = paginate_output(result.value, limit=limit)
    return present(books_spec, replace(result, value=page.items))

Return a list with one presented value per row, in the order the rows were given. A selector spec's affordances are added to each presented row by its position, so present refuses an answer that is not a list, or whose length differs from the rows', with ImproperlyConfigured, whether or not the spec declares any. A single value, such as a retrieve's, still goes through presented; the example's presented hands it to presented_rows as a batch of one, with the call's context, so both render the same fields.

A variant of a spec

A spec is frozen, so a variant of one is a new spec. derive(**changes) returns it: the same class, with the named fields replaced and every other one equal to the base's. A field is the base's very object unless the constructor rebuilds it, as it rebuilds a read's reads when the read has a filter_set.

# The same listing for the command line, which offers a search and no choice
# of ordering: ``reads=`` is the variant's whole ``reads``, so ``ordering`` is
# no longer an argument and the selector's own default answers for it.
search_only = list_notes_spec.derive(
    reads=Parameters.of(Parameter("search", "string", help="Part of the title, in any case.")),
)

The variant is built through the constructor, so every check a fresh declaration passes runs again on it, the combinations included: a change that is valid alone and refused beside the fields it keeps raises ImproperlyConfigured, as writing the variant out in full would. The base is never changed.

A field is replaced, never extended. reads= is the variant's whole reads, as search_only shows, so keeping the base's and adding one is said in so many words: reads=base.reads + Parameters.of(...).

A read's filter_set filters are the filter set's rather than the author's, so they follow whichever reads the variant declares, once, and a variant with filter_set=None keeps only the author's own.

A name that is not one of the spec's own fields is refused with TypeError: a misspelling, a method such as parameters, or a private field the constructor writes for itself.

A variant is another spec, by identity, so a Grant minted for the base does not cover it. To serve a variant in place of the base, hand the transport a registry that holds it: see replacing an entry.