How to Fix Dependency Injection Error in FastAPI Quickly
FastAPI usually happen when a dependency function is missing required parameters or is not declared properly with Depends. To fix it, ensure your dependency functions accept the correct parameters and are used with Depends in your path operation functions or other dependencies.Why This Happens
Dependency injection errors in FastAPI occur when the framework cannot resolve the dependencies you declared. This often happens if you forget to use Depends to declare a dependency or if the dependency function requires parameters that FastAPI cannot provide automatically.
from fastapi import FastAPI app = FastAPI() def get_user(token: str): return {"user": token} @app.get("/items/") def read_items(user=get_user): # Missing Depends here return user
The Fix
Use Depends to tell FastAPI that a parameter is a dependency. Also, if your dependency needs parameters like token, you should get them from the request (e.g., headers) using FastAPI's parameter types.
from fastapi import FastAPI, Depends, Header, HTTPException app = FastAPI() def get_user(token: str = Header(...)): if token != "secret-token": raise HTTPException(status_code=400, detail="Invalid token") return {"user": token} @app.get("/items/") def read_items(user=Depends(get_user)): return user
Prevention
Always declare dependencies with Depends in your path operation functions or other dependencies. Make sure dependency functions only require parameters FastAPI can provide, like request parts (headers, query, body). Use type hints and default values to guide FastAPI. Use linting tools or IDEs that highlight missing Depends usage.
Related Errors
Other common errors include:
- Missing required parameters: Dependency functions require parameters that FastAPI cannot supply.
- Incorrect parameter types: Using types FastAPI does not recognize for injection.
- Forgetting to import Depends: Leading to runtime errors.
Quick fixes: check your imports, use Depends, and ensure parameters are from request parts.