Skip to content

Reference

FastAPI

AlterFastAPI dependency — automatic JWT capture for FastAPI apps.

AlterFastAPI is a FastAPI dependency that requires and captures the user’s Bearer token on every request, then feeds it to the SDK’s identity resolution layer. The result is identity-mode request() without any per-route ContextVar boilerplate. Routes that intentionally support headless callers opt in with Depends(alter.optional).

Requires the fastapi extra:

Terminal window
pip install 'alter-sdk[fastapi]'
from alter_sdk import PendingApproval
from fastapi import FastAPI, Depends
from fastapi.responses import JSONResponse
from alter_sdk.fastapi import AlterFastAPI
alter = AlterFastAPI(api_key="alter_rk_…", caller="chat-api")
app = FastAPI()
@app.post("/chat")
async def chat(vault = Depends(alter)):
resp = await vault.proxy_request(
"GET",
"https://api.provider.example/v1/profile",
provider="provider-id",
)
if isinstance(resp, PendingApproval):
return JSONResponse(status_code=202, content=resp.model_dump(mode="json"))
return resp.body_json()
AlterFastAPI(
api_key: str,
*,
kind: str | None = None,
caller: str | None = None,
**kwargs: Any,
)
ParameterTypeDefaultDescription
api_keystr—Alter API key.
kindstr | NoneNone"app" (build an App), "agent" (build an Agent). When omitted, the key prefix decides — unknown prefixes fail closed.
callerstr | NoneNoneCaller identifier for audit attribution.
**kwargsForwarded to the constructed App / Agent. user_token_getter is reserved by the class.

Raises: AlterSDKError for an unrecognized kind value, or a missing/unknown prefix when kind is not pinned.

PropertyTypeDescription
vaultApp | AgentThe constructed SDK client.
appAppThe underlying App. Raises if constructed with an agent key.
agentAgentThe underlying Agent. Raises if constructed with an app key.

AlterFastAPI is itself callable — FastAPI invokes __call__ on each request. It extracts the Authorization: Bearer <token> via HTTPBearer (FastAPI returns 401 if missing), stores the token in a task-scoped ContextVar, and returns the SDK client.

  • optional(...) — explicit FastAPI dependency for a route that deliberately permits no end-user Bearer token. Use Depends(alter.optional); the dependency clears any prior task-local identity when the header is absent.
  • set_user_token(token: str) -> None — manually set the user token for the current request context. Use this in non-FastAPI paths (e.g. MCP auth callbacks) that need to inject identity.
  • auth_provider(*, base_url: str, providers: dict[str, list[str]] | None = None) — construct an AlterAuthProvider for FastMCP (see MCP). base_url is required (must be https, or a loopback host for local dev).
from fastapi import FastAPI, Depends
from fastapi.responses import JSONResponse
from alter_sdk.fastapi import AlterFastAPI
alter = AlterFastAPI(
api_key=os.environ["ALTER_API_KEY"],
kind="app",
caller="webapp-api",
)
app = FastAPI()
@app.get("/grants")
async def list_grants(vault = Depends(alter)):
page = await vault.list_grants()
# Branch on grant_kind — an operator list also includes managed-secret
# grants, which have no provider_id.
return [
{"id": g.grant_id, "provider": g.provider_id}
for g in page.grants
if g.grant_kind == "oauth"
]
@app.post("/connect")
async def start_connect(vault = Depends(alter)):
session = await vault.create_connect_session(
allowed_providers=["provider-id"],
)
return {"connect_url": session.connect_url}

For a headless operator endpoint, make the exception visible at the route:

@app.get("/health/grants")
async def headless_grants(vault = Depends(alter.optional)):
return await vault.list_grants()
from alter_sdk import PendingApproval
alter = AlterFastAPI(
api_key=os.environ["AGENT_API_KEY"],
kind="agent",
caller="research-agent",
)
@app.post("/agent/run")
async def run(vault = Depends(alter)):
# vault is an Agent; user JWT is bridged automatically
resp = await vault.proxy_request(
"GET",
"https://api.provider.example/v1/resources",
provider="provider-id",
)
if isinstance(resp, PendingApproval):
return JSONResponse(status_code=202, content=resp.model_dump(mode="json"))
return resp.body_json()

auth_provider() produces an AlterAuthProvider whose token-storage callback shares the same vault instance:

from fastmcp import FastMCP
auth = alter.auth_provider(
base_url="https://mcp.example.com",
providers={"provider-id": ["resources:read"]},
)
mcp = FastMCP("Resources", auth=auth)

When this handler returns HTTP 202, render every approval gate link in the authenticated application UI. Each link requires its designated approver to sign in to Alter. Poll approval status and retrieve the executed result through the SDK; do not submit the original provider call again.

Report an issue with this page

Necessary

Required for sign-in, security, authorization, and remembering your choices.

Always active

Analytics

Helps us understand how our website, product, and documentation are used.

Performance diagnostics

Uses performance tracing and privacy-masked session replay to diagnose problems.

Advertising

Shares visits and sign-ups with Meta, Reddit, and X so we can measure which of our ads work.

You can change these choices at any time from Cookie settings.