Skip to content

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.

Terminal window
pip install "aidy[fastapi]"
npm install -g @aidy-dev/cli

The aidy Python package needs Python 3.12 or later. The CLI generates aidy’s signing key.

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.

app.py
from fastapi import FastAPI, Request
from pydantic import BaseModel
from aidy import Identity, SearchHit, SearchResponse, load_public_keys, op
from 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.

@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.

Terminal window
aidy keys generate --kid aidy-2026-11 -o aidy-2026-11.private.jwk

The 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 json
import 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).

aidy-server serve, from the @aidy-dev/server package, runs aidy as its own HTTP service. It reads its configuration from environment variables:

Terminal window
export AIDY_URL=https://console.example.com
export AIDY_HOST_ORIGIN=https://console.example.com
export AIDY_HOST_BASE_URL=http://api:8000
export AIDY_HOST_OPENAPI=/openapi.json
export AIDY_SIGNING_KEY="$(cat aidy-2026-11.private.jwk)"
export AIDY_SECRET="$(openssl rand -base64 32)"
export AIDY_DATABASE_URL=postgres://aidy@db:5432/aidy
export AIDY_MODELS='[{"id":"main","provider":"openai","model":"gpt-4.1-mini","apiKey":"sk-…"}]'
export PORT=8787
npx @aidy-dev/server serve
  • AIDY_URL is the public URL of this aidy instance, the assertion’s iss.
  • AIDY_HOST_ORIGIN is your public origin, the assertion’s aud; it must equal audience in AidyHost.
  • AIDY_HOST_BASE_URL is where aidy reaches FastAPI. It defaults to the origin.
  • AIDY_HOST_OPENAPI is fetched with the user’s credential; FastAPI serves OpenAPI 3.1 at /openapi.json. The default is /api/openapi.json.
  • AIDY_SIGNING_KEY is the private JWK itself, as JSON.
  • AIDY_SECRET is 32 or more bytes and seals model API keys saved in settings.
  • AIDY_DATABASE_URL holds threads, events, approvals and settings: postgres://… or sqlite:<path>.
  • AIDY_MODELS is the default model chain; every entry needs an id.

The same server runs as the Docker image ghcr.io/aidy-dev/aidy-server. Every variable is listed in Deploy.

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.

Terminal window
curl -H "Authorization: Bearer $TOKEN" https://console.example.com/aidy/v0/catalog
curl -H "Authorization: Bearer $TOKEN" https://console.example.com/skill.md
aidy login https://console.example.com
aidy search "gpu"
aidy stop-vm --vm-id vm-42

aidy 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.