Skip to content

Quickstart - FastAPI

Terminal window
pip install z4j-fastapi z4j-arq # or z4j-taskiq, z4j-celery, ...

From the z4j dashboard, Agents, Mint. The response shows the bearer token and the per-project HMAC secret once. Save both: Z4J_TOKEN and Z4J_HMAC_SECRET. The agent refuses to start without the HMAC secret.

main.py
from fastapi import FastAPI
from z4j_fastapi import z4j_lifespan
# Reads Z4J_BRAIN_URL / Z4J_TOKEN / Z4J_HMAC_SECRET / Z4J_PROJECT_ID
# from the environment. Pass them as kwargs to z4j_lifespan(...) only
# if you want explicit overrides.
app = FastAPI(lifespan=z4j_lifespan())

z4j_lifespan() returns an asynccontextmanager you hand to FastAPI(lifespan=...). The agent starts when FastAPI starts up and stops cleanly when it shuts down.

If you also need an arq Redis pool wired into z4j (so arq events flow into the dashboard), pass it through:

from arq import RedisSettings
app = FastAPI(lifespan=z4j_lifespan(
arq_redis_settings=RedisSettings(host="redis", port=6379),
))

The same kwarg accepts an already-built pool, an SQLAlchemy session factory (for engines that need one), and several adapter-specific handles. See framework: FastAPI for the full list.

4. Manual install (apps that cannot use lifespan)

Section titled “4. Manual install (apps that cannot use lifespan)”
from z4j_fastapi import install_z4j
# Call once at startup; the returned handle drives the agent loop.
runtime = install_z4j()
# Call runtime.stop() in your own shutdown path.

The worker processes also need the agent. Each engine has a dedicated wiring helper:

  • arq: attach_to_worker_settings(WorkerSettings, adapter=ArqEngineAdapter())
  • taskiq: attach_to_broker(broker)
  • Celery: the agent auto-bootstraps via the worker-init signal (no extra wiring needed).

See arq, taskiq, or Celery for the exact pattern.

Run the doctor first; it confirms the agent can reach z4j end-to-end and reports a specific failure if it cannot:

Terminal window
python -m z4j_fastapi doctor

Run as the same user the service runs under. All probes should be [OK].

Then boot your API. Dashboard, Agents — you should see the web process online. Boot your worker — you should see the worker online. Enqueue a task — it appears in Tasks within ~100ms.

See framework: FastAPI.