Using dependencies
FastAPI is a highly efficient framework that allows us to build APIs in Python with impressive speed and accuracy. One of the key features of FastAPI is its dependency injection system, which is both easy to use and incredibly powerful. In this article, we'll delve into the world of FastAPI dependencies and learn how to effectively use them in our applications.
Introduction to Dependencies
In FastAPI, a 'dependency' is simply a Python function that gets called before the route function. Dependencies can return data that is then passed into a route handler function, which can be used for various purposes like data validation, authentication, database queries, etc.
Here's a simple example of a dependency:
from fastapi import Depends, FastAPI
def get_db():
db = "database_connection"
return db
app = FastAPI()
@app.get("/items/")
async def read_items(db=Depends(get_db)):
return {"db": db}
In the above example, get_db
is our dependency. It gets called before read_items
and its return value is passed into read_items
as the db
parameter.
Using Depends
The Depends
function is a special function provided by FastAPI to declare dependencies. It can be used in the parameters of a path operation function.
Let's understand the Depends
function with an example:
from fastapi import Depends, FastAPI
def common_parameters(q: str = None, page: int = 1):
return {"q": q, "page": page}
app = FastAPI()
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
In the above example, the common_parameters
function is a dependency for the read_items
path operation function. The Depends
function declares common_parameters
as a dependency.
Sub-dependencies
FastAPI supports sub-dependencies as well. These are dependencies that have dependencies of their own. Here's an example:
from fastapi import Depends, FastAPI
def query(q: str = "default"):
return q
def common_parameters(q: str = Depends(query), page: int = 1):
return {"q": q, "page": page}
app = FastAPI()
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
In this example, query
is a sub-dependency of common_parameters
.
Classes as Dependencies
FastAPI also allows you to use classes as dependencies. Here's how you can do it:
from fastapi import Depends, FastAPI
class CommonParameters:
def __init__(self, q: str = "default", page: int = 1):
self.q = q
self.page = page
app = FastAPI()
@app.get("/items/")
async def read_items(commons: CommonParameters = Depends(CommonParameters)):
return {"q": commons.q, "page": commons.page}
In this example, CommonParameters
is a class that is used as a dependency.
Conclusion
With FastAPI, dependencies can be used to manage shared logic across multiple routes, allowing for cleaner, more maintainable code. By using dependencies, we can ensure that our functions stay DRY (Don't Repeat Yourself), which is a key principle in software development. Remember, dependencies are just functions or classes, and they can do anything that a regular function or class can do.