Google News
logo
FastAPI - Interview Questions
What is dependency injection in FastAPI?
Dependency injection in FastAPI is a mechanism that allows you to declare and manage the dependencies required by your route functions or other parts of your application. Dependencies are components or services that your application relies on, such as database connections, authentication services, or external API clients. FastAPI's dependency injection system helps organize and handle these dependencies in a clean and modular way.

Here's how dependency injection works in FastAPI :

Dependency Declaration : You declare dependencies using Python functions, which FastAPI refers to as "dependency functions." These functions can be asynchronous (async def) or synchronous (def), depending on the nature of the dependency.
from fastapi import Depends, FastAPI

app = FastAPI()

def get_db():
    # Function to get a database connection
    # ...

def get_current_user(token: str = Depends(get_token)):
    # Function to get the current user based on the token
    # ...

@app.get("/items/")
async def read_items(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    # Route function that depends on the database and current user
    # ...?
Dependency Injection in Route Functions : In the example above, the read_items route function has dependencies on a database connection (db) and the current user (current_user). FastAPI automatically injects these dependencies into the function when it is called.

Dependency Resolvers : FastAPI uses dependency resolvers to resolve and inject dependencies into route functions. Dependency resolvers are responsible for obtaining the required dependency instances before executing the route function.

Order of Execution : Dependencies are executed in the order they are declared in the function signature. FastAPI ensures that dependencies with shared sub-dependencies are only executed once, and their results are reused.

Reusable Components : By using dependency injection, you can create reusable components for common functionality. For example, you can define a get_db dependency that provides a database session, and then use it in multiple route functions.

Automatic Validation of Dependencies : FastAPI automatically validates and handles the dependencies based on the type hints provided in the dependency functions. If a required dependency cannot be resolved, FastAPI will raise an exception and return an error response.
Advertisement