Sub-dependencies
FastAPI provides robust support for handling dependencies in your application. Among these features, a powerful one is 'Sub-dependencies'. This mechanism allows a dependency to have other dependencies.
Understanding Sub-dependencies
To understand the concept of sub-dependencies, let's take an example. Suppose you have two dependencies: get_db
to get a database connection, and get_current_user
to get the current user. The get_current_user
function needs the database connection to verify the user's data.
In FastAPI, you can directly use get_db
as a parameter in get_current_user
, making get_db
a sub-dependency of get_current_user
.
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
db = connect_to_db()
try:
yield db
finally:
db.close()
def get_current_user(db = Depends(get_db)):
user = get_user_from_db(db)
return user
In the above code, get_db
is a sub-dependency of get_current_user
.
Using Sub-dependencies in Path Operations
You can use these nested dependencies directly in your path operation functions.
@app.get("/users/me")
async def read_user_me(current_user = Depends(get_current_user)):
return current_user
Here, when a request is made to /users/me
, FastAPI will:
- Call the
get_db
function first because it's a sub-dependency ofget_current_user
. - It will then call
get_current_user
, passing the result ofget_db
as thedb
parameter.
Sub-dependencies with Several Dependencies
A sub-dependency can have several dependencies. Let's imagine that for get_current_user
, we also need another dependency, get_token
.
def get_token():
token = get_token_from_request()
return token
def get_current_user(db = Depends(get_db), token = Depends(get_token)):
user = get_user_from_db(db, token)
return user
In this case, FastAPI will automatically resolve the dependencies and sub-dependencies in the correct order.
Conclusion
Sub-dependencies are a powerful feature in FastAPI for managing complex scenarios where a dependency relies on other dependencies. They help in structuring your code better, making it more readable and maintainable. Try to leverage this feature in your applications to get the most out of FastAPI.
This covers the basics of sub-dependencies in FastAPI, which should provide a good foundation for beginners.