FastAPI Depends Module
A Depends / dependency is a piece of reusable logic that you can attach to your routes (or even entire routers) so you don’t have to repeat the same code everywhere.
This works through the Dependency Injection pattern.
Below are some of the examples to use dependencies:
- Reusable validation checks
- Authentication & Authorization (for example, verifying a token)
- Managing database sessions
GitHub code URL for reference and practice.
Below is just an example to create person.py router inside routers folder and add check as a dependency to validate practice-token and token.
Added empty __init__.py file inside routers folder, indicates this is a Python package.
person.py router
The person.py file contains a dedicated FastAPI router that groups and manages all endpoints related to user operations. By using this router, we keep person-specific logic (such as creating, retrieving, updating, or deleting person) separate from other parts of the application / router, making the project more modular and maintainable.
from fastapi import APIRouter, Depends, Header, HTTPException
# define function to check if practice-token and token header exists in request.
def check_token_header(practice_token: str = Header(...), token : str = Header(...)):
print(practice_token + " = " + token)
if practice_token != "david" and token != "12345":
raise HTTPException(status_code=403, detail="Token Not Found")
# Create router having /token/v1 as prefix
router = APIRouter(
prefix="/token/v1",
tags=["Token"],
dependencies=[Depends(check_token_header)] # Call function check_token_header for validation.
)
# Create a router API endpoint as /person
@router.get("/person")
def getUser():
return {"message" : "practice-token and token are found!"}
Register router
We can register our person router in one single file as practice_router_dependencies.py and include in FastAPI.
from fastapi import FastAPI, APIRouter, Depends, HTTPException
from routers import person
app = FastAPI()
app.include_router(person.router)Use below command to start application:
uvicorn practice_router_dependencies:app --reloadOUTPUT:
It will throw in case of NOT providing header key and value.
API call will raise custom exception in case NOT providing values for practice-token and token.
Post providing practice-token value as david and token value as 12345.
I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.
You can follow me for upcoming blogs follow.
Thank you!
