dependency-injectionfastapi

What's the point of using Dependency Injection in FastAPI when you can just use default parameters?


I don't understand the point of Dependency Injection when using FastAPI, like take a look at this code

utils/getInfo.py

def getInfo():
    from app import UserModel
    from app import PostModel
    from app import CommentModel
    from app import Session
    class Models:
        User = UserModel
        Post = PostModel
        Comment = CommentModel
    return (Session, Models)

router/somerouter.py

from controllers.somecontroller import route

@router.post("/someroute")
async def handleRoute():
    return await route()

controllers/somecontroller.py

from utils.getInfo import getInfo

async def route(databaseInfo: tuple = getInfo):
    Session, Models = getInfo
    return {"msg": "Route"}

Where does dependency injection come into this to make it easier? How is it better? I see a lot of code example of FastAPI use it. So before I make the entire API use this approach I want to know if I should switch and why. Because the current setup works.


Solution

  • From the docs:

    With the Dependency Injection system, you can also tell FastAPI that your path operation function also "depends" on something else that should be executed before your path operation function, and FastAPI will take care of executing it and "injecting" the results.

    Using your setup, you would only get the results of route() function once you're inside the handleRoute(). Whereas with Dependency Injection, you have access to them before you get into handleRoute().

    A example being Authentication & Authorisation. You want this to be executed before you're inside your handleRoute(). Using your setup, you'd only hit authentication/Authorisation at the end.