What is dependency injection?
Generally speaking, dependency injection is a system able to automatically instantiate objects and the ones they depend on. The responsibility of developers is then to only provide a declaration of how an object should be created, and let the system resolve all the dependency chains and create the actual objects at runtime.
FastAPI allows you to declare the objects and variables you wish to have at hand only by declaring them in the path operation function arguments. Actually, we already used dependency injection in the previous chapters. In the following example, we use the Header
function to retrieve the user-agent
header:
chapter5_what_is_dependency_injection_01.py
from fastapi import FastAPI, Header app = FastAPI() @app.get("/") async def header(user_agent: str = Header(...)): return {"user_agent": user_agent}
https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI/blob...