Frameworks
FastAPI
Async Python routes with Pydantic request and response models.
About 5 minutes hands-on
What this guide does not cover
- Assumes a working FastAPI app. Does not cover deployment, ASGI server tuning, or dependency injection patterns.
- Background-task guarding is not shown; a rejected result must still reach the caller.
Step 1: Install
Terminal
pip install "soter[fastapi]"Step 2: Quickstart (one-line route)
The fastest way to add AI security to your FastAPI app:
Python
1from fastapi import FastAPI
2from soter import Soter
3from soter.fastapi import create_chat_route
4
5app = FastAPI()
6guard = Soter() # reads SOTER_API_KEY from environment
7
8def my_llm_call(prompt: str) -> str:
9 return f"Response to: {prompt}"
10
11# One-line guarded chat route — input guard → LLM → output guard
12app.add_api_route(
13 "/chat",
14 create_chat_route(guard, call_llm=my_llm_call),
15 methods=["POST"],
16)Step 3: Manual guarding (more control)
Use protect_chat for manual control:
Python
1from fastapi import FastAPI
2from pydantic import BaseModel
3from soter import Soter
4
5app = FastAPI()
6guard = Soter()
7
8class ChatRequest(BaseModel):
9 message: str
10
11@app.post("/chat")
12def chat(req: ChatRequest):
13 # Manual: input guard → LLM → output guard
14 result = guard.protect_chat(
15 message=req.message,
16 call_llm=lambda safe_message: my_llm_call(safe_message),
17 )
18 return result.to_dict()Step 4: Async support
Use AsyncSoter for async endpoints (requires httpx):
Python
from soter import AsyncSoter # requires httpx
guard = AsyncSoter()
@app.post("/chat")
async def chat(req: ChatRequest):
result = await guard.protect_chat(
message=req.message,
call_llm=my_llm_call,
)
return result.to_dict()