Integrations
FastAPI
Integrate KoreShield with FastAPI applications
FastAPI Integration Guide
KoreShield integrates seamlessly with FastAPI applications, allowing you to protect your endpoints with minimal code changes.
Overview
There are two primary ways to integrate KoreShield with FastAPI:
- Middleware approach: Protects all or specific routes automatically.
- Dependency injection: Allows fine-grained control inside route handlers.
Option 1: Dependency Injection (Recommended)
Using dependency injection gives you access to the KoreShield client within your route, allowing you to handle blocked requests gracefully or return custom error responses.
from fastapi import FastAPI, Depends, HTTPException
from koreshield.client import KoreShieldClient
import os
app = FastAPI()
def get_koreshield():
# Configure with your KoreShield Proxy URL
return KoreShieldClient(base_url=os.getenv("KORESHIELD_URL", "http://localhost:8000"))
@app.post("/chat")
async def chat(message: str, ks: KoreShieldClient = Depends(get_koreshield)):
# 1. Guard the input
result = await ks.guard(message)
if not result.is_safe:
# 2. Handle unsafe content
raise HTTPException(
status_code=403,
detail={
"error": "Content blocked",
"reason": result.reason,
"details": result.details
}
)
# 3. Process safe content
return {"response": "Processed successfully"}Option 2: Middleware
(Coming soon) We are working on a standard ASGI middleware package for drop-in protection.
Configuration
Ensure your KoreShield Proxy is running and accessible. By default, the client connects to http://localhost:8000. You can configure this via environment variables or constructor arguments.
| Environment Variable | Description | Default |
|---|---|---|
KORESHIELD_URL | URL of the KoreShield Proxy | http://localhost:8000 |
KORESHIELD_API_KEY | API Key (if auth enabled) | None |