FastAPI Integration¶
-
Deep Integration
Inject in endpoint handlers, middleware, decorators, and other request-path hooks.
-
Zero Runtime Overhead
Inject dependencies with zero runtime overhead using Class-Based Handlers.
-
Background Tasks
Inject dependencies into scheduled background callbacks via
WireupTask. -
Framework-Agnostic
Share your service layer with CLI tools, background workers, and other frameworks.
Migrating from FastAPI Depends?
Evaluating Wireup for your FastAPI project? Check out the migration page which includes common pain points with FastAPI Depends and how to solve them with Wireup as well as a low-friction migration path:
Quick Start¶
This is the shortest path to a working FastAPI endpoint with Wireup injection.
main.py
Best practice is to call from fastapi import FastAPI
import wireup
import wireup.integration.fastapi
from wireup import Injected, injectable
# 1. Define services
@injectable
class GreeterService:
def greet(self, name: str) -> str:
return f"Hello, {name}!"
# 2. Create container
container = wireup.create_async_container(injectables=[GreeterService])
app = FastAPI()
# 3. Use Injected[T] in routes for Wireup injection
@app.get("/")
async def greet(greeter: Injected[GreeterService]):
return {"message": greeter.greet("World")}
# 4. Initialize Wireup integration
wireup.integration.fastapi.setup(container, app)
setup(...) after routes are added.
Run the server with:
fastapi dev main.py
Detailed Guides¶
- Inject in Routes: HTTP/WebSocket handler injection and config value injection in route signatures.
- Request and WebSocket Context in Services: inject
fastapi.Requestandfastapi.WebSocketinto Wireup services. - Class-Based Handlers: zero per-request constructor resolution and
WireupRouteoptimizations. - Request Lifecycle Patterns: middleware/decorator patterns and request-time helpers.
- Background Tasks: inject dependencies into scheduled callbacks with
WireupTask. - FastAPI Testing:
TestClientlifespan usage, overrides, and request-lifecycle test patterns. - Troubleshooting: common setup/runtime errors and fast fixes.