How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
FastAPI · Python

Fix TypeError: get_current_user() missing 1 required positional argument: 'db' in FastAPI

This error occurs when a FastAPI dependency function signature does not match what the dependency injection system expects. The DI container cannot resolve a parameter because it is not declared as a Depends() sub-dependency. Fix it by wrapping nested dependencies with Depends() so FastAPI can resolve the full chain automatically.

Reading the Stack Trace

Traceback (most recent call last): File "/app/venv/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi result = await app(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/starlette/routing.py", line 677, in __call__ await route.handle(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/starlette/routing.py", line 275, in handle await self.app(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/fastapi/routing.py", line 234, in app solved_result = await solve_dependencies(request=request, dependant=dependant) File "/app/venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py", line 621, in solve_dependencies solved = await run_in_threadpool(call, **sub_values) File "/app/src/dependencies/auth.py", line 18, in get_current_user user = db.query(User).filter(User.id == token_data.sub).first() TypeError: get_current_user() missing 1 required positional argument: 'db'

Here's what each line means:

Common Causes

1. Missing Depends() wrapper on sub-dependency

The db parameter in get_current_user is a plain type hint instead of being wrapped with Depends(get_db), so FastAPI does not know how to provide it.

from sqlalchemy.orm import Session
from app.database import get_db

def get_current_user(token: str = Depends(oauth2_scheme), db: Session):
    token_data = decode_token(token)
    user = db.query(User).filter(User.id == token_data.sub).first()
    if not user:
        raise HTTPException(status_code=401)
    return user

2. Incorrect dependency ordering

Dependencies are declared in the wrong order, causing FastAPI to treat a Depends parameter as a regular positional argument.

def get_current_user(db: Session, token: str = Depends(oauth2_scheme)):
    # db has no default and no Depends(), so Python treats it as positional
    token_data = decode_token(token)
    return db.query(User).filter(User.id == token_data.sub).first()

3. Using dependency as a regular function call

The endpoint calls the dependency directly instead of letting FastAPI inject it via Depends().

@app.get("/users/me")
async def read_current_user():
    user = get_current_user()  # Called directly, not injected
    return user

The Fix

Wrap the db parameter with Depends(get_db) so FastAPI's dependency injection system knows how to resolve the database session. Every sub-dependency must be declared with Depends() for the DI chain to work.

Before (broken)
from sqlalchemy.orm import Session
from fastapi import Depends
from app.database import get_db

def get_current_user(token: str = Depends(oauth2_scheme), db: Session):
    token_data = decode_token(token)
    user = db.query(User).filter(User.id == token_data.sub).first()
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return user
After (fixed)
from sqlalchemy.orm import Session
from fastapi import Depends
from app.database import get_db

def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_db),
):
    token_data = decode_token(token)
    user = db.query(User).filter(User.id == token_data.sub).first()
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return user

Testing the Fix

import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch, MagicMock
from app.main import app

client = TestClient(app)


def test_get_current_user_returns_user():
    with patch("app.dependencies.auth.decode_token") as mock_decode:
        mock_decode.return_value = MagicMock(sub=1)
        response = client.get(
            "/users/me",
            headers={"Authorization": "Bearer valid-token"},
        )
        assert response.status_code == 200


def test_get_current_user_invalid_token():
    response = client.get(
        "/users/me",
        headers={"Authorization": "Bearer invalid-token"},
    )
    assert response.status_code == 401


def test_get_current_user_no_auth_header():
    response = client.get("/users/me")
    assert response.status_code in (401, 403)

Run your tests:

pytest tests/test_auth.py -v

Pushing Through CI/CD

git checkout -b fix/fastapi-dependency-injection,git add src/dependencies/auth.py tests/test_auth.py,git commit -m "fix: wrap db param with Depends(get_db) in get_current_user",git push origin fix/fastapi-dependency-injection

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: testdb
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pytest --tb=short -q
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/testdb

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the full test suite locally to confirm the dependency chain resolves.
  2. Open a pull request with the Depends(get_db) fix.
  3. Wait for CI checks including database integration tests to pass.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify the endpoint works in staging.

Frequently Asked Questions

BugStack resolves the full dependency injection chain, runs your test suite against a real database, and verifies that all endpoints using the dependency return correct responses before marking it safe.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review the dependency changes before merging.

Yes. FastAPI supports arbitrarily deep dependency chains. Each function in the chain just needs its own parameters wrapped in Depends() so the injector can resolve them recursively.

Yes, by default FastAPI calls each dependency once per request and reuses the result. If you need a fresh instance each time, set use_cache=False in the Depends() call.