Nyraxis AI

FastAPI

Evaluate request bodies with Nyraxis middleware before processing in FastAPI.

Setup

pip install fastapi uvicorn nyraxis
export NYRAXIS_API_KEY="your-api-key"
export NYRAXIS_PROJECT_ID="your-project-id"

Code Example

from fastapi import FastAPI, Request, Depends, HTTPException
from nyraxis import Nyraxis

app = FastAPI()
nx = Nyraxis()

@app.middleware("http")
async def nyraxis_middleware(request: Request, call_next):
    if request.method == "POST":
        body = await request.json()
        message = body.get("message", "")
        if message:
            result = nx.evaluate(message)
            if result.blocked:
                raise HTTPException(status_code=403, detail="Blocked by policy")
    return await call_next(request)

# Alternative: dependency injection pattern
async def guard_input(request: Request):
    body = await request.json()
    result = nx.evaluate(body.get("message", ""))
    if result.blocked:
        raise HTTPException(status_code=403, detail="Blocked by policy")
    return body

@app.post("/chat")
async def chat(body: dict = Depends(guard_input)):
    # Process the safe message
    return {"response": "Processed: " + body["message"]}

What Gets Protected

  • All POST request bodies are evaluated before reaching route handlers
  • Blocked messages return a 403 response immediately
  • Dependency injection pattern allows per-route granular control
  • Both middleware and dependency patterns can be combined

On this page