FastAPI
The FastAPI packages add Datum's server side to your own FastAPI application:
- Form definitions, served by id.
- Submissions, validated by the same program the page runs.
- The form and builder assets.
- PDF render, fill, sign and verify.
- An RFC 3161 timestamp server.
You include a router for each capability. A router adds a route only when its setting is on (the management router's health routes aside), and who may call it is your own FastAPI dependencies, never a Datum policy. The FastAPI packages are tested on Linux. The server hosts page compares the hosts.
First run
This section takes the form from Getting started to a FastAPI application that receives its submission. Follow it from top to bottom. It needs nothing from the rest of the page.
You need:
- Python 3.12 or newer, and uv.
- Node 22 or newer, npm and git, to build the packages. They are not published to PyPI yet. The build downloads the sandbox runtime once.
Build the browser files. Run the commands of Files you host in a clone of the repository, then build the conformance suite, whose files the next step copies:
sh(cd packages/conformance-suite && npm install) npm run conformance-suite:buildBuild the packages' files, from the root of the clone:
shnpm run fastapi:assetsIt writes the programs, the browser files and the sandbox runtime into the member folders under
integrations/. It may note that the settings schema was skipped; the application does not need it.fastapi/ packages Make a folder for the application beside the clone, named
intakehere, and putpyproject.in it. The sixtoml pathsources point at the built members;uv syncinstalls them with thesubmissionsextra:toml[project] name = "intake" version = "0.1.0" requires-python = ">=3.12" dependencies = ["argusvane-datum-fastapi[submissions]", "uvicorn"] [tool.uv] package = false [tool.uv.sources] argusvane-datum-fastapi = { path = "../datum/integrations/fastapi/packages/argusvane-datum-fastapi" } argusvane-datum-core = { path = "../datum/integrations/fastapi/packages/argusvane-datum-core" } argusvane-datum-programs = { path = "../datum/integrations/fastapi/packages/argusvane-datum-programs" } argusvane-datum-sandbox = { path = "../datum/integrations/fastapi/packages/argusvane-datum-sandbox" } argusvane-datum-sandbox-wasmtime = { path = "../datum/integrations/fastapi/packages/argusvane-datum-sandbox-wasmtime" } argusvane-datum-qjs-wasm = { path = "../datum/integrations/fastapi/packages/argusvane-datum-qjs-wasm" }shcd intake && uv syncPut the form where the host reads it. Save the form the page uses (
forms/in Getting started, idcontact. json contact, version1.) as0. 0 datum/in the application folder. That is the default offorms/ contact. json datum.,forms. locations ["datum/, read from the folder the server starts in. The file'sforms/*.json"] idis its key. Another place isDATUM_.FORMS__LOCATIONS='["path/*.json"]' Write the application,
app.:py pythonfrom uuid import uuid4 from fastapi import FastAPI from datum_core.submissions import AcceptedSubmission, SubmissionReceipt from datum_fastapi import Datum, DatumSettings, routers def keep(accepted: AcceptedSubmission) -> SubmissionReceipt: print("received", accepted.form_key, dict(accepted.values)) return SubmissionReceipt(id=str(uuid4()), reference=accepted.digest[:8].upper()) datum = Datum(config=DatumSettings().to_config(), handler=keep) app = FastAPI() app.include_router(routers.submissions(datum))The handler stores the accepted submission and answers its receipt: the
referenceis what the form's confirmation shows. Here it prints the answers. A real handler stores them once per(form_, because a retried attempt may reach it twice. Including a router also starts Datum, through the application's lifespan: with lifespans off, every Datum route butkey, version, submission_ key) /livezanswers 503server.. Addunavailable routers.to serve the form's definition (its setting isforms(datum) datum.), andweb. api. endpoints. definition openapi_totags=DATUM_ OPENAPI_ TAGS Fastto group the routes in the OpenAPI document. Without a handler the host logs the form and the receipt id, stores nothing and warns once (API(...) datum.).W003 Switch the route on and run. Every route is off until its setting is on. The submissions switch is all this story needs: it also loads the form files.
shexport DATUM_WEB__API__ENDPOINTS__SUBMISSIONS=true uv run uvicorn app:appThe start takes a few seconds while the sandbox compiles. It ends with
Application startup complete.and twodatum.notices, which say that the throttle and the receipts are kept in this process's memory. To see the routes that are on, addW004 logging.tobasic Config(level=logging. INFO) app.: the log then holdspy Datum routes on: submissions.Send a submission. In a second terminal, post the body a page sends: the envelope as
document, and the key of the submit attempt.shcurl -s -X POST localhost:8000/api/submissions -H 'content-type: application/json' -d '{ "document": { "versionContext": { "form": { "id": "contact", "version": "1.0.0" } }, "submission": { "locale": "en", "values": { "fullName": "Ada Lovelace", "email": "ada@example.com", "topic": "question", "message": "Hello" } } }, "submissionKey": "first-run-1" }'The reply is 200, and the server prints
received contact {...}:json{"id":"9a60a8d1-967f-4680-afcf-f2fc63e81980","reference":"81396661","status":"accepted","digest":"813966615705ced43fc2ab4c6d752fd703fbf171f7af0157651bab2a321f56b6","handled":false}Send the same command again and
handledistrue: the same key gets the first receipt, and the handler is not called again.Send answers the form refuses. Change
fulltoName ""and the key tofirst-run-2. The sandbox judges the answers against the form's own copy and the reply is 422, which a page puts on the field withset:Errors json{"errors":[{"field":"fullName","code":"required"}]}Open the page through the application. The page from Send it to a server posts this body to this route: both are this host's defaults. A browser lets a page read a reply only from its own origin, so serve the site folder of Getting started from the application. Add this at the end of
app., after the routers, and run it again:py pythonfrom fastapi.staticfiles import StaticFiles app.mount("/", StaticFiles(directory="../my-site", html=True))Open
localhost:8000in a browser, fill the form in and press Send. The form shows "Your form was submitted" with the reference the handler answered, and the server prints the answers.
Two things to keep in mind from here:
- The
idandversionin the page's form must be the ones the host holds, so the page and the host read the same file. - A page that stays on another origin needs CORS configured in your application: the host adds no CORS headers, and a preflight to the route answers 405.
Extras and packages
The application above asks for the submissions extra. Python 3.12 or newer, asyncio. Add the extras you need:
| Extra | Adds |
|---|---|
submissions | The programs, the sandbox engine (argusvane-datum-sandbox-wasmtime) and the throttle |
ui | submissions, plus the form and builder browser assets |
pdf | submissions, the PDF libraries and the PDF browser assets |
timestamp | The RFC 3161 server and client |
revocation | Offline revocation checking for the PDF trust policy |
testing | The test helpers and an HTTP client for Test |
all | Every extra but testing |
The packages:
argusvane-datum-sandboxdoes all the work of running the programs, for any Python framework: see Python sandbox library.argusvane-datum-coreis the framework-free core over it and imports no web framework.argusvane-datum-fastapiadds the routers.argusvane-datum-sandbox-wasmtimeis the engine: wasmtime, which ships native libraries for 64-bit Linux (glibc and musl), macOS and Windows on x86_64 and arm64.argusvane-datum-programs, the two asset distributions and the WASM runtime distribution carry the built programs, the browser files and the sandbox module.
Every argusvane-datum-* distribution must be at one version:
- The extras pin each distribution to the exact version of
argusvane-datum-fastapi, so installing through an extra keeps them together. - At start the host compares the build id of
argusvane-datum-corewith that of each resource distribution installed:argusvane-datum-programs,argusvane-datum-assets-ui,argusvane-datum-assets-pdfandargusvane-datum-qjs-wasm(the WASM runtime distribution). It refuses to start on a mix, naming each one's build.
Switching routers on
Every endpoint is off by default. Settings are read from three sources:
- Environment variables:
DATUM_plus the dotted name in capitals,__between levels. - A TOML file named by
DATUM_.CONFIG_ FILE - Keyword arguments to
Datum.Settings
export DATUM_WEB__API__ENDPOINTS__SUBMISSIONS=true
export DATUM_WEB__API__ENDPOINTS__VALIDATE=true
export DATUM_WEB__API__ENDPOINTS__DEFINITION=true
export DATUM_WEB__ASSETS__ENABLED=true
export DATUM_BUILDER__ENABLED=true
export DATUM_TSA__ENABLED=trueThe first source that names a setting wins, in this order:
- Keyword arguments to
Datum.Settings - Environment variables.
- The TOML file.
datum. turns the warning about an unknown DATUM_* variable into a refusal to start.
Common settings
Every setting, with its default and bounds, is on FastAPI settings. The ones met most often:
datum., defaultweb. api. max_ body_ size 1.Mi B datum..web. api. problem_ details datum., defaultruntime. validation. time_ limit 5 s, andmemory, default32.Mi B datum..host. time_ zone datum., defaultweb. throttle. limit 60per60 sfor one key, anddatum., defaultweb. throttle. address_ limit 600, for one address before the body is read.
A value that cannot work stops the start and names the setting, and an unknown DATUM_* variable is warned about. python -m datum_ writes the JSON Schema of every setting. The routes, bodies and codes behind these switches are on the wire.
Routers and endpoints
| Factory | Endpoints | Setting |
|---|---|---|
routers. | GET /api/, GET /api/, GET /api/ | datum., .data_ |
routers. | POST /api/, POST /api/ | .submissions, .validate |
routers. | POST /api/, POST /api/ | .test, .inspect |
routers. | host., datum-host. and the bundles under /datum/ | datum. |
routers. | POST /api/, PUT /api/, PUT /api/ | datum. |
routers. | POST /api/, /api/, /api/, /api/, GET /api/ | .pdf, .fill, .sign, .verify, .certificate |
routers. | POST /tsa, GET /tsa/, GET /tsa/ | datum. |
routers. | GET /livez, /readyz, /health, /info, and POST /recheck | datum. for /recheck |
The check route
- Request. It takes
{ document, scope }(andpagefor a page check).Id scopeis required, and a bare envelope is 400bad_.document - Answer. 200
{ accepted, errors }, withnotesfor warnings only when there are any. An error or a note has amessagewhen the sandbox or a validator gave one, and none otherwise.
A run that fails gives no verdict. The check route, POST /api/, the dry run, the PDF routes and POST /api/ all answer it 503 with the run's code and no Retry-After, because the same run fails the same way. The codes are:
wasm.execution_ error outcome_too_ large definition., for a registered form nested too deeptoo Deep
A definition posted to inspect that is nested too deep is the caller's: 422. Only a busy sandbox, 503 server., carries Retry-After. The wire reference has the whole contract.
The dry run
The dry run answers one flat report, the same on every Datum host. The wire reference lists its members. It has no accepted member and no nested report: read outcome, and the run's time is sandbox..
Factory arguments
- Every factory takes
prefix=, and every one buttsatakesdependencies=. - The factories that run work for the caller or write (
authoring,builder,pdf,management) requiredependencies, so an unprotected router readsdependencies=[]in your source. - At start the log lists the routes that are on, and warns (
datum.) about a router included with every switch off.W001 datum.makes every router add nothing but the management router's health routes.enabled=false
Hooks and stores
Everything you plug in is a keyword of Datum(...). A hook is a plain callable, sync or async, and a sequence keeps the order you give it.
| Keyword | Purpose |
|---|---|
handler | Stores the accepted submission and returns the receipt |
pre_ | Refuse before the sandbox runs: (Incoming |
validators | Host-side validation after the sandbox, with errors and warnings |
rules_, context_, host_ | Add host rules, context entries, or per-form run settings |
host_ | Works out the values a form's host. names read, from the request (see below) |
definition_ | Adjust the public copy of a form on its way to a filler |
builder_, builder_ | Adjust or judge a definition before it is stored |
pdf_, pdf_ | Adjust a PDF request, or judge the PDF before it leaves |
form_, snapshot_, translation_, idempotency_ | Where forms, versions, translations and receipts live |
data_ | Providers for option lists |
throttle | Your own rate limiter, in place of the one built from datum. |
pdf_, timestamper | The seal key and where seals get their timestamps |
signature_ | Checks a signed submission's signature (the passkey routes are not served, so a signed wrapper answers 503 signing. by default) |
timestamp_, tsa_, tsa_, tsa_, tsa_, tsa_, tsa_ | The timestamp server's policy hooks, signing key, serial numbers, issue log, clients, clock and the transport of the client |
pdf_, sandbox_, pdf_ | Wrap the PDF program or the sandbox; decide which anchors make a signer trusted |
pre_ | Maps a pre-check's refusal to a status (403 and 429 by default) |
runtime, sandbox, engine_ | Replace the sandbox runtime or the engine's settings, for tests and special hosts |
error_, run_, listeners, now, withheld_ | Extra error answers, the guest's run log, event listeners, the clock, assets the page glue must not serve |
- Customizers run in order, each over what the one before left, and the first refusal stops the rest.
- Validators all run, so every error is reported at once.
- A refusal is
Hook:Refused Error forbiddenanswers 403,conflict409 andinvalid422, with a body oferrors.
Events
Events follow the effect and never veto it:
Submission,Validated Event Submission,Rejected Event Submission,Throttled Event Submission,Redelivered Event JourneyChecked Event FormDefinition Saved Event Pdf,Rendered Event PdfVerified Event Timestamp,Issued Event TimestampRefused Event Datum,Runtime Ready Event SandboxRun Interrupted Event
Stores
The stores that ship are in memory.
- The start warns (
datum.) when a per-process store is in use.W004 - The start fails (
datum.) when the builder is on with in-memory stores and more than one worker.E002 - The timestamp server refuses to start with in-memory serials unless
datum.acknowledges a single instance.tsa. allow_ memory_ stores
The store protocols are the seam: implement one over your database and hold it to its contract with the classes in datum_.
The host context
A rule can read a fact about the visit, such as host.. The server judges those rules only with values it works out itself. It never reads them from the request body. Give Datum one host_ provider. It takes the form key and the call's context, and answers a JSON object or None. Read the person from the context's principal, which your principal dependency answers from the request:
from fastapi import Request
from datum_fastapi import Datum
def current_user(request: Request) -> object | None:
return getattr(request.state, "user", None)
def host_context(form_key: str, context) -> dict[str, str] | None:
user = context.principal
return {"role": user.role} if user is not None else None
datum = Datum(principal=current_user, host_context=host_context)What the provider answers decides how host. rules are judged:
- No provider, or
None. Every rule that readshost.is left unjudged, as before. - An object, even an empty one. Every such rule is judged, and a name it does not hold has no value.
- A raise, or something that is not a JSON object within the sandbox's bounds (64 levels deep). This is a fault in your application: the call answers 503
server.and nothing is judged.unavailable
Where it applies:
- The provider is asked for the check route, submissions, the dry run and the PDF routes.
- A retried submission keeps its first verdict and asks nothing.
- The handler sees the same values as
Accepted, and a PDF is drawn with them.Submission. host_ context
Values from the host shows the formulas.
Builder and drafts
datum. adds POST /api/, PUT /api/ and PUT /api/, and the author's copy at GET /api/, which only routers. serves.
- Access. Protect the router with
dependencies=. - Checks. The sandbox kernel checks a save, and it is refused with 409
form.when it builds on an out-of-date version. The bodies and codes are on the wire.outdated - Stores. With in-memory stores and more than one worker the start refuses a builder (
datum.).E002
The router does not serve draft routes. A server: draft store calls four routes you write yourself: see Drafts.
Serving the form from the host
datum. serves host., the page glue datum-host. and the bundles under their build id. Server hosts shows the page code and lists every Datum method.
Sealing PDFs
The seal needs a key. Put it in files and name them.
export DATUM_PDF__SEAL__ENABLED=true
export DATUM_PDF__SIGNING__TYPE=PKCS12
export DATUM_PDF__SIGNING__PKCS12_FILE=/etc/datum/seal.p12
export DATUM_PDF__SIGNING__PKCS12_PASSWORD=...| Setting | Does |
|---|---|
datum., .layouts, .certify, .reason, .location, .visible | Turn the seal on, limit it to some layouts, and set what the signature says. Without a key the start warns (datum.). |
datum., .pkcs12_, .pkcs12_, .key_, .cert_, .key_ | The key: a PKCS#12 file, or a PEM key and a certificate chain. Or pass your own pdf_. |
datum. | Ask for a token over each seal. With no timestamp source the start warns (datum.). |
datum., .retired_ | Anchors the verify route builds a chain to, and the certificates the seal key replaced. |
datum. | Seal the PDFs of posted, unstored answers with the real key. Off, they keep a test seal. |
Where the seal gets its timestamps, a server you name or the host's own, is on Timestamp server. Every setting is on FastAPI settings.
Access control
Datum ships no access policy. Pass your own FastAPI dependencies, and they run before Datum's own checks, so a refused caller meets your 401 or 403 first.
from fastapi import Depends
app.include_router(routers.builder(datum, dependencies=[Depends(require_author)]))
app.include_router(routers.management(datum, dependencies=[Depends(require_operator)]))- 403 body.
Fastgives your 403 the catalog'sAPI(exception_ handlers=access_ errors(datum)) access.body.denied - Caller and language.
Datum(principal=..., locale=...)take dependencies that name the caller and the language for the hooks. - Proxy. Behind a proxy let the ASGI server decide
request.(uvicorn'sclient --proxy-headers), because the throttle never readsX-Forwarded-Foritself. - CSRF. FastAPI has no CSRF protection of its own and Datum adds none, but the JSON endpoints accept
application/only.json - Server-secret rules. The definition with its server-secret rules is reachable only through
routers..builder
Testing
- Starlette's
Testas a context manager runs the lifespan, so Datum starts once for the block.Client - Share one app across a module's tests, because the runtime compiles its sandbox module on start.
- Install the
testingextra. - To test without the sandbox, pass
runtime=orsandbox=toDatum.
datum_ has contract classes that hold a store of your own to its protocol. To check a running deployment against the wire contract, run datum-host-check from the conformance suite.
Health and logs
- Requests are named in the logs by the
X-Request-IDheader, or the trace id. - The management router's
/healthreports the runtime and the stores, and/readyzreads the runtime alone. - Datum's own checks log under
datum.with stable ids;checks datum.silences a notice or a warning by id (never an error). FastAPI settings lists every id, its cause and what to do about it.silenced_ checks
What is not served
- No passkey routes. A form cannot require a passkey signature here, and
Datumis refused in the page unless you pass anHost. passkeys() endpoint. - No SQL store. The stores that ship are in memory.
To run more than one worker, see Server hosts.
Supported versions
- Python. 3.12 and later.
- FastAPI. 0.133 or newer, with Starlette 1.x.
- wasmtime-py. Held to one tested major at a time.
Every setting is on FastAPI settings, and every route on The wire.