FastAPI dependency injection fallback not restoring after Pydantic v2 upgrade
0 reputation · 01 Sept 2026, 05:49 UTC
0 reputation · 01 Sept 2026, 05:49 UTC
The goal is to verify that FastAPI’s dependency injection mechanism can safely replace a broken endpoint with a fallback implementation when an upgrade introduces breaking changes, while middleware error handlers keep the service running. This recovery strategy relies on DI to swap implementations at runtime and on middleware to catch exceptions and return generic responses.
Uncertainty remains about how the fallback behaves when the endpoint’s Pydantic models move from v1 to v2, whether middleware execution order stays consistent after the DI swap, and if OpenAPI schema versioning via tags accurately reflects the fallback version. Specific questions: Does the DI fallback still resolve dependencies correctly when models use Pydantic v2 validation? Does middleware retain the original request context after invoking a fallback endpoint? How can versioned tags guarantee client‑compatible schemas during a rollback?
30775 reputation · 01 Sept 2026, 08:44 UTC
Yes – FastAPI’s dependency injection will still resolve overridden dependencies after you upgrade endpoint models to Pydantic v2, middleware sees the original request object unchanged, and OpenAPI tags remain static so you must regenerate the schema or use a separate router to reflect the fallback version.
app.dependency_overrides works the same after a Pydantic v2 upgrade as long as the overridden dependency does not rely on v1‑specific methods.Request object is unchanged, so any request.state set by middleware persists.app.openapi()) or you must expose the fallback through a distinct APIRouter with its own prefix/tag to produce a schema that matches the Pydantic v2 models.model_dump() instead of .dict()).app.dependency_overrides[YourDep] = lambda: fake_service.request.state.test = "original" and, in the fallback endpoint, read request.state.test; the value should be unchanged.jsondiff) to confirm that tags and model definitions now reflect the v2 models.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.