π¦ ClawHub
FastAPI
by @ivangdavila
Build fast, production-ready Python APIs with type hints, validation, and async support.
TERMINAL
clawhub install fastapiπ About This Skill
name: FastAPI description: Build fast, production-ready Python APIs with type hints, validation, and async support. metadata: {"clawdbot":{"emoji":"β‘","requires":{"bins":["python3"]},"os":["linux","darwin","win32"]}}
FastAPI Patterns
Async Traps
run_in_executortime.sleep() in async endpoints blocks everything β use await asyncio.sleep() insteadProcessPoolExecutor or background workersPydantic Validation
items: list = [] shares the same list across requests β use Field(default_factory=list)Optional[str] doesn't make a field optional in the request β add = None or use Field(default=None)model_validate() not parse_obj(), and model_dump() not .dict() β v1 methods are deprecatedAnnotated[str, Field(min_length=1)] for reusable validated types instead of repeating constraintsDependency Injection
lru_cache on expensive dependencies or cache in app.state for singletonsDepends() without an argument reuses the type hint as the dependency β clean but can confuse readersyield dependencies for cleanup (DB sessions, file handles) β code after yield runs even if the endpoint raisesLifespan and Startup
@app.on_event("startup") is deprecated β use lifespan async context managerapp.state during lifespan, not as global variablesfrom contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app):
app.state.db = await create_pool()
yield
await app.state.db.close()
app = FastAPI(lifespan=lifespan)
Request/Response
dict from endpoints, not Pydantic models directly β FastAPI handles serialization and it's fasterstatus_code=201 on POST endpoints returning created resources β 200 is the default but semantically wrongResponse with media_type="text/plain" for non-JSON responses β returning a string still gets JSON-encoded otherwiseresponse_model_exclude_unset=True to omit None fields from response β cleaner API outputError Handling
raise HTTPException(status_code=404) β don't return Response objects for errors, it bypasses middleware@app.exception_handler(CustomError) β but remember they don't catch HTTPExceptiondetail= for user-facing messages, log the actual error separately β don't leak stack tracesBackground Tasks
BackgroundTasks runs after the response is sent but still in the same process β not suitable for long-running jobsSecurity
OAuth2PasswordBearer is for documentation only β it doesn't validate tokens, you must implement that in the dependencyDepends(get_current_user) in path operation, not in router β dependencies on routers affect all routes including health checksTesting
TestClient runs sync even for async endpoints β use httpx.AsyncClient with ASGITransport for true async testingapp.dependency_overrides[get_db] = mock_db β cleaner than monkeypatchingTestClient context manager ensures lifespan runs β without with TestClient(app) as client: startup/shutdown hooks don't fire