✨ Improve error messages for incorrect Depends() usage
#14281
+191
−5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Improve error messages for incorrect Depends() usage
Description
This PR improves the developer experience when
Depends()is used incorrectly by providing clear, actionable error messages instead of cryptic TypeErrors from deep in the stack.Problem
When new FastAPI users misuse the
Depends()function, they encounter confusing error messages like:TypeError: 'dict' object is not callableAttributeError: 'Depends' object has no attribute...These errors come from Starlette or Pydantic internals and don't clearly explain what went wrong or how to fix it.
Solution
Added validation in the
Depends.__init__()method to catch common mistakes early and provide helpful error messages.Common mistakes now caught:
1. Calling the dependency function:
2. Nesting Depends() calls:
3. Passing non-callable values:
Changes
Modified
fastapi/params.py:Depends.__init__()Depends()callsAdded
tests/test_depends_validation.py:Example Error Messages
Before:
After:
Benefits
fastapi/params.pyTesting
tests/test_depends_validation.py)Checklist
Related Issues
This addresses a common pain point for new users learning FastAPI's dependency injection system. Related discussions:
Depends()errors in community channelsThis enhancement aligns with FastAPI's philosophy of excellent developer experience and will help onboard new users more smoothly.