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, ...

Get Building Python Microservices with FastAPI now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.