Quickstart: FastAPI
This quickstart adds aidy to a FastAPI app. FastAPI keeps serving your API; aidy runs beside it
as its own process (aidy-server serve), and a reverse proxy sends the aidy paths to it. The Python
kit aidy annotates your routes and verifies the assertion aidy sends with every call.
The running example is a cloud console at https://console.example.com with a stop_vm
operation.
1. Install
Section titled “1. Install”pip install "aidy[fastapi]"npm install -g @aidy-dev/cliThe aidy Python package needs Python 3.12 or later. The CLI generates aidy’s signing key.
2. Annotate your routes
Section titled “2. Annotate your routes”op() builds the x-aidy object for FastAPI’s openapi_extra. It takes the keys of the
x-aidy reference in snake case (timeout_seconds becomes
timeoutSeconds), and raises ValueError listing every problem against the schema, so a bad
annotation fails at import.
from fastapi import FastAPI, Requestfrom pydantic import BaseModel
from aidy import Identity, SearchHit, SearchResponse, load_public_keys, opfrom aidy.fastapi import AidyCall, AidyHost
app = FastAPI()
class Vm(BaseModel): id: str name: str status: str
class StopBody(BaseModel): forced: bool = False
@app.get("/api/vm/{vm_id}", openapi_extra=op("get_vm", description="Get a cloud server (VM) by id."))async def get_vm(vm_id: str, request: Request) -> Vm: return load_vm(current_user(request), vm_id)
@app.post( "/api/vm/{vm_id}/stop", openapi_extra=op( "stop_vm", title="Stop server", description="Stop a running cloud server (VM).", effect="update", open="/console/instance/{vm_id}", confirmation={ "title": "Stop server {resource_name}?", "fields": [{"key": "forced", "label": "Force", "values": {"true": "Yes", "false": "No"}}], "lookup": {"path": "/api/vm/{vm_id}", "labelPath": "name"}, }, ),)async def stop_vm(vm_id: str, body: StopBody, request: Request, aidy: AidyCall) -> Vm: if aidy is not None: # a delegated call: record it audit(actor="aidy", run=aidy.rid, approval=aidy.apr) return stop(current_user(request), vm_id, forced=body.forced)stop_vm is a write (effect="update"), so it waits for approval by default. Its body is
flattened: the agent sees one input with vm_id and forced. See
The catalog and Operations and effects.
3. Add identity and search
Section titled “3. Add identity and search”@app.get("/api/me", openapi_extra=op("whoami", role="identity"))async def whoami(request: Request) -> Identity: user = current_user(request) return Identity(subject=user.id, tenant=user.tenant_id, name=user.name, locale="zh-CN")
@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))async def search_vms(q: str, request: Request, limit: int = 10) -> SearchResponse: return SearchResponse( hits=[ SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}") for vm in find_vms(current_user(request), q, limit) ] )The identity operation is a GET with no parameters; exactly one is allowed per catalog. A
search operation is a GET with a required q. See Identity and
Search and knowledge.
4. Generate keys and verify assertions
Section titled “4. Generate keys and verify assertions”aidy keys generate --kid aidy-2026-11 -o aidy-2026-11.private.jwkThe command prints the public JWK for your host’s configuration and writes the private JWK
(aidy’s signing key) to a new 0600 file. Pin the public JWK in FastAPI with AidyHost:
import jsonimport os
def caller(request: Request) -> tuple[str, str | None] | None: """(subject, tenant) of the request's credential, exactly as the UI authenticates it.""" user = current_user(request) return (user.id, user.tenant_id) if user else None
AidyHost( app, keys=load_public_keys([json.loads(os.environ["AIDY_PUBLIC_JWK"])]), audience="https://console.example.com", identity=caller,)A request without Aidy-Assertion passes untouched. With one, AidyHost checks the signature,
lifetime, audience, method, URL, body hash, replay, subject, tenant, operation and approval,
and answers 401 aidy_assertion_invalid on failure. Endpoints receive the claims as an
AidyCall parameter (None for a direct user call).
5. Run aidy-server
Section titled “5. Run aidy-server”aidy-server serve, from the @aidy-dev/server package, runs aidy as its own HTTP service. It
reads its configuration from environment variables:
export AIDY_URL=https://console.example.comexport AIDY_HOST_ORIGIN=https://console.example.comexport AIDY_HOST_BASE_URL=http://api:8000export AIDY_HOST_OPENAPI=/openapi.jsonexport AIDY_SIGNING_KEY="$(cat aidy-2026-11.private.jwk)"export AIDY_SECRET="$(openssl rand -base64 32)"export AIDY_DATABASE_URL=postgres://aidy@db:5432/aidyexport AIDY_MODELS='[{"id":"main","provider":"openai","model":"gpt-4.1-mini","apiKey":"sk-…"}]'export PORT=8787npx @aidy-dev/server serveAIDY_URLis the public URL of this aidy instance, the assertion’siss.AIDY_HOST_ORIGINis your public origin, the assertion’saud; it must equalaudienceinAidyHost.AIDY_HOST_BASE_URLis where aidy reaches FastAPI. It defaults to the origin.AIDY_HOST_OPENAPIis fetched with the user’s credential; FastAPI serves OpenAPI 3.1 at/openapi.json. The default is/api/openapi.json.AIDY_SIGNING_KEYis the private JWK itself, as JSON.AIDY_SECRETis 32 or more bytes and seals model API keys saved in settings.AIDY_DATABASE_URLholds threads, events, approvals and settings:postgres://…orsqlite:<path>.AIDY_MODELSis the default model chain; every entry needs anid.
The same server runs as the Docker image ghcr.io/aidy-dev/aidy-server. Every variable is
listed in Deploy.
6. Reverse-proxy the aidy paths
Section titled “6. Reverse-proxy the aidy paths”aidy serves these paths under your origin. Route them to aidy-server and everything else to
FastAPI:
| Path | Purpose |
|---|---|
/aidy/v0/* |
The HTTP API: threads, runs, catalog, search, settings |
/mcp |
MCP over streamable HTTP |
/skill.md, /llms.txt |
Generated documents |
/.well-known/aidy-keys.json |
aidy’s public keys |
location /aidy/v0/ { proxy_pass http://aidy:8787; proxy_buffering off; }location = /mcp { proxy_pass http://aidy:8787; proxy_buffering off; }location = /skill.md { proxy_pass http://aidy:8787; }location = /llms.txt { proxy_pass http://aidy:8787; }location = /.well-known/aidy-keys.json { proxy_pass http://aidy:8787; }location / { proxy_pass http://api:8000; }Runs stream as server-sent events, so turn off response buffering for /aidy/v0/ and /mcp.
7. Try it
Section titled “7. Try it”curl -H "Authorization: Bearer $TOKEN" https://console.example.com/aidy/v0/catalogcurl -H "Authorization: Bearer $TOKEN" https://console.example.com/skill.md
aidy login https://console.example.comaidy search "gpu"aidy stop-vm --vm-id vm-42aidy stop-vm asks for confirmation on the terminal before the write runs. To spell it
aidy vm stop vm-42, add cli={"command": "vm stop", "args": ["vm_id"]} to op().
For the in-app agent, add the React dock as in step 8 of Quickstart: Hono on Workers.
Next steps
Section titled “Next steps”- FastAPI guide: forms, resolve, chains and deferred tasks.
- Python reference: every function of the kit.
- Delegation: what
AidyHostverifies and why. - Deploy: running
aidy-serverin production.