Investigating Dependency Injection
Since the first chapter, Dependency Injection (DI) has been accountable for building clean and robust FastAPI REST services and was apparent in some of our sample APIs that required BaseModel
, Request
, Response
, and BackgroundTasks
in their processes. Applying DI proves that instantiating some FastAPI classes is not always the ideal approach, since the framework has a built-in container that can provide the objects of these classes for the API services. This method of object management makes FastAPI easy and efficient to use.
FastAPI has a container where the DI policy is applied to instantiate module classes and even functions. We only need to specify and declare these module APIs to the services, middleware, authenticator, data sources, and test cases because the rest of the object assembly, management, and instantiation is now the responsibility of the built-in container.
This chapter will help you to understand how to manage objects needed...