Dependencies provide reusable logic to API endpoints. They are commonly used for:
- Database sessions
- Authentication
- Permissions
- Other shared functionality
FastAPI provides Depends() to declare a dependency that an endpoint needs.
Code
from fastapi import FastAPI, Depends
app = FastAPI()
def get_current_user():
return {
"id": 1,
"name": "Tarun"
}
@app.get("/profile")
def profile(
user=Depends(get_current_user)
):
return user
Understanding the Code
First, import Depends from FastAPI:
from fastapi import Depends
Then create a reusable dependency:
def get_current_user():
return {
"id": 1,
"name": "Tarun"
}
This function provides the current user’s information.
The dependency is used in the /profile endpoint:
@app.get("/profile")
def profile(
user=Depends(get_current_user)
):
return user
Here, Depends(get_current_user) tells FastAPI to execute get_current_user() and provide its result to the user parameter.
Example Request
GET /profile
Output
{
"id": 1,
"name": "Tarun"
}
Why Use Dependencies?
Dependencies help avoid repeating the same logic across multiple endpoints.
For example, authentication logic can be placed in one dependency:
def get_current_user():
# Authentication logic
return user
Then multiple endpoints can reuse it:
@app.get("/profile")
def profile(user=Depends(get_current_user)):
return user
This makes FastAPI applications easier to organize and maintain.
Summary
FastAPI dependencies provide reusable logic to API endpoints.
The basic pattern is:
def get_current_user():
return {
"id": 1,
"name": "Tarun"
}
@app.get("/profile")
def profile(user=Depends(get_current_user)):
return user
Dependencies are especially useful for database sessions, authentication, and permissions.