Eliminate Repeated Auth and Pagination Code with FastAPI Dependency Injection
This article shows how FastAPI's dependency injection can centralize authentication, permission checks, database connection lifecycles, and pagination logic, removing duplicated code across endpoints by defining reusable dependencies, sub‑dependencies, and yield‑based resources, with concrete code examples and test results.
1. What is Dependency Injection
Dependency injection means a function declares what it "needs" and FastAPI automatically provides it.
from fastapi import Depends
def get_current_user(token: str = Depends(verify_token)):
return token
@app.get("/profile")
def profile(user: str = Depends(get_current_user)):
return {"user": user}The profile endpoint receives a user argument without manually parsing the request; Depends(verify_token) tells FastAPI to supply the value.
2. Authentication Dependency
A typical token verification function:
from fastapi import Header, HTTPException
def verify_token(authorization: Annotated[str | None, Header()] = None):
if not authorization:
raise HTTPException(status_code=401, detail="Not authenticated")
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid scheme")
return authorization[7:] # return the parsed token Header()extracts a value from the HTTP header, similar to Query() and Path(). Any endpoint that needs authentication simply adds Depends(verify_token) to its signature.
@app.get("/posts/me")
def get_my_posts(token: str = Depends(verify_token)):
return {"token": token}3. Sub‑Dependencies: Verification Chain
For two‑step validation—first authenticate, then check super‑user rights—a sub‑dependency is defined:
def require_superuser(current_user: Annotated[str, Depends(verify_token)]):
"""Sub‑dependency: verify token then ensure superuser"""
if "admin" not in current_user:
raise HTTPException(status_code=403, detail="Superuser required")
return current_user
@app.get("/admin/dashboard")
def admin_dashboard(user: str = Depends(require_superuser)):
return {"can_access": True}When admin_dashboard is called, FastAPI first runs verify_token, then require_superuser.
4. Yield Dependency: Lifecycle Management
Typical usage for a database connection:
def get_db():
db = connect_to_database() # connection established
yield db # pass the connection to the route
db.close() # cleanup after request endsThe code before yield prepares the resource; the code after yield cleans it up, guaranteed to run whether the request succeeds or raises an exception.
5. Pagination Dependency: Reducing Repetition
Instead of writing skip and limit parameters in every list endpoint, a shared dependency is created:
def get_pagination(
skip: int = Query(default=0, ge=0),
limit: int = Query(default=10, ge=1, le=100),
):
return {"skip": skip, "limit": limit}
@app.get("/posts")
def list_posts(p: dict = Depends(get_pagination)):
return {"skip": p["skip"], "limit": p["limit"], "posts": [...]}All list endpoints now share the same pagination logic; changing the rules requires editing only this function.
6. What Was Done on Day 5
Defined verify_token authentication dependency.
Defined require_superuser sub‑dependency (verification chain).
Defined get_db yield dependency for connection lifecycle.
Defined get_pagination pagination dependency.
Added four new endpoints that use these dependencies.
Created eight new test cases, bringing the total to 37 passing tests.
7. Next Steps
Day 6 will cover error handling and middleware—global exception handling to unify response formats, and using middleware for logging and CORS.
8. Related Links
Official FastAPI documentation (Chinese): https://fastapi.tiangolo.com/zh/tutorial/dependencies/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
