Skip to content

Conversation

@tImIhAcK
Copy link

@tImIhAcK tImIhAcK commented Nov 1, 2025

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 callable
  • AttributeError: '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:

# ❌ Wrong
@app.get("/")
def route(user = Depends(get_user())):
    pass

# ✓ Correct
@app.get("/")
def route(user = Depends(get_user)):
    pass

2. Nesting Depends() calls:

# ❌ Wrong
@app.get("/")
def route(val = Depends(Depends(get_value))):
    pass

3. Passing non-callable values:

# ❌ Wrong
@app.get("/")
def route(val = Depends("not_a_function")):
    pass

Changes

Modified fastapi/params.py:

  • Added validation logic in Depends.__init__()
  • Checks for nested Depends() calls
  • Checks if dependency is callable
  • Provides specific error messages with examples

Added tests/test_depends_validation.py:

  • Tests for all error cases (nested Depends, called functions, non-callables)
  • Tests for correct usage still working
  • Tests for error message quality and helpfulness
  • Tests for callable classes and edge cases

Example Error Messages

Before:

TypeError: 'dict' object is not callable

After:

TypeError: Depends() expects a callable (function or class), but received dict.

It looks like you may have called the dependency function instead of passing it.
✓ Correct: Depends(my_function)
✗ Wrong: Depends(my_function())

Benefits

  • Fails fast - Catches errors at route definition time, not runtime
  • Clear guidance - Shows exactly what's wrong and how to fix it
  • Minimal change - Only modifies one method in fastapi/params.py
  • No breaking changes - Correct usage is completely unaffected
  • Well tested - Comprehensive test coverage for all scenarios
  • Improves DX - Significantly better experience for new users

Testing

  • Added comprehensive test coverage (tests/test_depends_validation.py)
  • All existing tests pass
  • Manual testing confirms improved error messages
  • Code formatted with Black and isort
  • Type checking passes

Checklist

  • Clear, actionable error messages with examples
  • Catches errors at route definition time (early)
  • Maintains backward compatibility (correct usage unaffected)
  • Includes helpful examples in error messages (✓/✗ format)
  • Comprehensive test coverage (8 test cases)
  • Follows FastAPI code style and conventions

Related Issues

This addresses a common pain point for new users learning FastAPI's dependency injection system. Related discussions:

  • Users encountering cryptic Depends() errors in community channels
  • Multiple Stack Overflow questions about these error messages

This enhancement aligns with FastAPI's philosophy of excellent developer experience and will help onboard new users more smoothly.

tImIhAcK and others added 5 commits November 1, 2025 13:30
- Add validation in Depends.__init__ to catch common mistakes early
- Provide clear, actionable error messages for:
  - Nested Depends() calls: Depends(Depends(...))
  - Called functions: Depends(func()) instead of Depends(func)
  - Non-callable arguments: Depends('string') or Depends(123)
- Include helpful hints in error messages (✓/✗ examples)
- Add comprehensive test coverage for validation logic

Fixes: Cryptic TypeError messages when Depends() is misused
Helps: New users understand and fix dependency injection errors quickly
"\n✓ Correct: Depends(my_function)"
"\n✗ Wrong: Depends(my_function())"
)
elif callable(dependency):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This condition can't be True since we are in the if not callable(dependency): branch

@YuriiMotov YuriiMotov changed the title Improve error messages for incorrect Depends() usage ✨ Improve error messages for incorrect Depends() usage Nov 3, 2025
@YuriiMotov YuriiMotov added feature New feature or request waiting labels Nov 3, 2025
Copy link
Member

@svlandeg svlandeg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @tImIhAcK, was this PR vibe coded?

@github-actions github-actions bot removed the waiting label Nov 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants