Last active
June 22, 2023 14:21
-
-
Save brandon-braner/b9332a01fe8746c6eeb3025fc868bdcd to your computer and use it in GitHub Desktop.
FastAPI Depdency Injection Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI, Depends | |
from myservice import UserService, User, UserCreate | |
app = FastAPI() | |
class UserService: | |
def create_user(self): | |
return 'doing something that creates user' | |
def user_service() -> UserService: | |
return UserService() | |
@app.post("/user-create-with-dep-inj") | |
async def create_user(user_service: UserService = Depends(user_service)): | |
""" | |
This is the prefered method as you are injecting something that knows how to create an instance of user service. | |
""" | |
return user_service.create_user() | |
@app.post("/user-create-without-dep-inj") | |
async def create_user(): | |
""" | |
This is a bad implementation as you have a hard depdency on UserService, | |
this makes testing harder and replacement of it harder in the future | |
as well this method now requires to know how to create an instance of UserService. If | |
user service had other depdencies it needed you would need to use those in this route as well. | |
""" | |
user_service = UserService() | |
user_service.create_user() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment