fastapi
- Repo stars 0
- Author repo skills-registry
FastAPI Conventions
Route Handlers Are Thin
Validate input, call a service, return output. No business logic.
router = APIRouter(prefix="/sessions", tags=["sessions"])
@router.post("", status_code=201, response_model=SessionResponse)
async def create_session(
body: CreateSessionRequest,
service: SessionService = Depends(get_session_service),
) -> SessionResponse:
return await service.create(body.topic)
Dependency Injection
All dependencies in app/core/dependencies.py. Never instantiate services inside route handlers.
@lru_cache
def get_settings() -> Settings:
return Settings()
async def get_session_service(
pool: asyncpg.Pool = Depends(get_db_pool),
settings: Settings = Depends(get_settings),
) -> SessionService:
return SessionService(pool=pool, settings=settings)
Lifespan for Startup and Shutdown
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.db_pool = await asyncpg.create_pool(settings.database_url)
yield
await app.state.db_pool.close()
app = FastAPI(lifespan=lifespan)
Do not use the deprecated @app.on_event("startup").
Response Model
Always declare response_model=SomePydanticModel. Never return raw dicts.
Middleware Order
Register in this order (FastAPI processes in reverse registration order):
- Correlation ID middleware (outermost)
- CORS middleware
- Rate limiting middleware
- Request logging middleware (innermost)
Global Exception Handlers
Register domain-to-HTTP mappings once in app/core/middleware.py:
@app.exception_handler(SessionNotFoundError)
async def handler(request: Request, exc: SessionNotFoundError):
return JSONResponse(status_code=404, content={"code": "session_not_found", "message": str(exc)})
Exception Hierarchy
Define in app/core/exceptions.py:
class AppError(Exception):
"""Base exception for all application errors."""
class SessionNotFoundError(AppError): ...
class ReasoningValidationError(AppError):
def __init__(self, reason: str) -> None:
self.reason = reason
super().__init__(reason)
class InvalidEventTypeError(ReasoningValidationError): ...
- Services raise domain exceptions; global handlers map them to HTTP — never per-route
- Never raise
HTTPExceptioninside a service layer - Never swallow exceptions silently with bare
except:
<!-- tomevault:4.0:skill_md:2026-05-22 -->Source: cheneeheng/agent-skills — distributed by TomeVault.
- Fluxly category
- AI
- Author-declared agents
- No explicit declaration found; this is not inferred or tested compatibility
- Static check
- 88 / 100 · heuristic scan, not runtime safety proof
- Author / version / license
- @tomevault-io · no license declared
- Fluxly token estimate
- Lean
- Fluxly setup estimate
- Plug-and-play
- External API key
- No requirement detected
- Detected OS requirements
- Unspecified
- Runtime requirements
- Python
- Detected file/system behavior
-
- Read-only
- Write / modify
- Detected network behavior
- Local-only
- Install commands
- None (reference only)
Profile is derived at build time from SKILL.md and install vectors. Subject to drift from author intent.
Heads up: 未限定 allowed-tools,默认拥有全部工具权限。
The current SKILL.md does not define a fixed output example. Validate input, call a service, return output. No business logic.
All dependencies in app/core/dependencies.py. Never instantiate services inside route handlers.
Do not use the deprecated @app.onevent("startup").
Always declare responsemodel=SomePydanticModel. Never return raw dicts.
Register in this order (FastAPI processes in reverse registration order): Correlation ID middleware (outermost) CORS middleware
Register domain-to-HTTP mappings once in app/core/middleware.py:
# FastAPI Conventions
## Route Handlers Are Thin
Validate input, call a service, return output. No business logic.
```python
router = APIRouter(prefix="/sessions", tags=["sessions"])
@router.post("", status_code=201, response_model=SessionResponse)
async def create_session(
body: CreateSessionRequest,
service: SessionService = Depends(get_session_service),
) -> SessionResponse:
return await service.create(body.topic)
```
## Dependency Injection
All dependencies in `app/core/dependencies.py`. Never instantiate services inside route handlers.
```python
@lru_cache
def get_settings() -> Settings:
return Settings()
async def get_session_service(
pool: asyncpg.Pool = Depends(get_db_pool),
settings: Settings = Depends(get_settings),
) -> SessionService:
return SessionService(pool=pool, settings=settings)
```
## Lifespan for Startup and Shutdown
```python
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.db_pool = await asyncpg.create_pool(settings.database_url)
yield
await app.state.db_pool.close()
app = FastAPI(lifespan=lifespan)
```
Do not use the deprecated `@app.on_event("startup")`.
## Response Model
Always declare `response_model=SomePydanticModel`. Never return raw dicts.
## Middleware Order
Register in this order (FastAPI processes in reverse registration order):
1. Correlation ID middleware (outermost)
2. CORS middleware
3. Rate limiting middleware
4. Request logging middleware (innermost)
## Global Exception Handlers
Register domain-to-HTTP mappings once in `app/core/middleware.py`:
```python
@app.exception_handler(SessionNotFoundError)
async def handler(request: Request, exc: SessionNotFoundError):
… Author text anchors workflow facts; Fluxly only indexes current sections, terms, files, and commands.
sections -> Route Handlers Are Thin → Dependency Injection → Lifespan for Startup and Shutdown → Response Model → Middleware Order → Global Exception Handlers
terms -> Validate input, call a service, return output. · All dependencies in app/core/dependencies.py. · Do not use the deprecated @app.onevent("startup"). · Always declare responsemodel=SomePydanticModel. · 1. Correlation ID middleware (outermost) 2. · class SessionNotFoundError(AppError): ... · --- > Source: [cheneeheng/agent-skills](https://github.com/cheneeheng/agent-skills) — distributed by [TomeVault](https://tomevault.io).
files/cmd -> app/core/dependencies.py · @app.onevent("startup") · responsemodel=SomePydanticModel · app/core/middleware.py · app/core/exceptions.py · HTTPException · except:
body sha256 -> 8e4e8239c5c0
Decide Fit First
Design Intent
How To Use It
Boundaries And Review