Creating and using a function dependency
In FastAPI, a dependency can be defined either as a function or as a callable class. In this section, we'll focus on the functions, which are the ones you'll probably work with most of the time.
As we said, a dependency is a way to wrap some logic that will retrieve some sub-values or sub-objects, make something with them, and finally return a value that will be injected into the endpoint calling it.
Let's look at a first example where we define a function dependency to retrieve the pagination
query parameters, skip
and limit
:
chapter5_function_dependency_01.py
async def pagination(skip: int = 0, limit: int = 10) -> Tuple[int, int]: return (skip, limit) @app.get("/items") async def list_items(p: Tuple[int, int] = Depends(pagination)): skip, limit = p return {"skip": skip, "limit": limit}