AskReference
ExplanationIntermediate

What is the purpose of the FastAPI Depends() function in dependency injection?

Depends() tells FastAPI that an argument's value should come from a dependency function, and FastAPI calls that function automatically at request time and passes its return value into your path function. It lets you declare single-path, grouped, or app-wide dependencies without calling the dependency yourself when defining the endpoint.

In FastAPI's dependency injection, Depends() is a helper function used in a path function's argument list. Its purpose is to delay the call of a dependency function until the moment it is needed, when the endpoint actually runs. Instead of setting user = user_dep or user = user_dep(), you write user: dict = Depends(user_dep), and FastAPI evaluates user_dep() and injects the returned dict. Depends() can also appear in path decorator dependencies=[Depends(depfunc)] when the dependency only needs to run and does not return a value, as well as in APIRouter(... dependencies=[Depends(depfunc)]) and FastAPI(dependencies=[Depends(depfunc)]) for wider scope. This gives FastAPI the ability to validate inputs, convert formats, and document the API automatically.

Key points

  • Depends() is a FastAPI helper that marks an argument as coming from a dependency function.
  • FastAPI calls the dependency function automatically when the endpoint runs, not when it is defined.
  • The return value of the dependency is injected into the path function's argument.
  • Depends() can be used in path functions, path decorators, routers, and the top-level app to control dependency scope.
  • It enables automatic data validation, format conversion, and API documentation for custom dependencies.
Source:FastAPI: Modern Python Web Development· Dependencies· p. 95–100

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook