-
Example Codedef get_db_connection():
conn = pymssql.connect(
server=settings.server,
user=settings.user,
password=settings.password,
database=settings.database,
port=settings.port,
as_dict=True,
)
try:
yield conn
finally:
conn.close()
router = APIRouter(
prefix="/project",
tags=["project"],
dependencies=[Depends(get_db_connection)],
responses={418: {"description": "Project status API."}},
)
@router.get("/count/{status}")
def projects_count(
status: str, conn: pymssql.Connection = Depends(get_db_connection)
) -> dict:
try:
if status.upper() == "ALL":
status = None
return aq.get_project_count(conn, status=status)
except:
raise HTTPException(404, "Unable to get project count")DescriptionThere are several endpoints in the router. And all of them have the parameter conn. Can I avoid declaring this parameter at each router by declaring it as the dependency at APIRouter? And how to access the dependency declared at APIRouter in a route? Operating SystemLinux Operating System DetailsNo response FastAPI Version0.66.0 Python Version3.9.6 Additional ContextWhen I did google search for the same, the following is what I get: Is there a simpler solution? |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 14 replies
-
|
The way you have specified dependencies in APIRouter as below is correct (Reference: Dependency in APIRouter ) : This can be taken even one more level up to declaring FastAPI app if it's needed for all the Routers (Reference: Dependency in FastAPI ) With that, I think accessing the dependency as below should work considering you are specifying the dependency in the router (It worked for my sample code).
however I am not sure if there is a more elegant way to access the Router/App level dependencies in endpoints. |
Beta Was this translation helpful? Give feedback.
-
|
I also have this question. Additionally.. Is there any benefit to including |
Beta Was this translation helpful? Give feedback.
-
|
Any ideas how to reduce redundancy in the declaration of router dependencies? I want to access my settings dependency, usually declared as a global dependency, inside my router endpoints. |
Beta Was this translation helpful? Give feedback.
-
router = APIRouter(
prefix="/il_oedometer/casagrande",
tags=["/il_oedometer/casagrande"],
dependencies=[Depends(deps.get_casagrande_service)],
)
logger = logging.getLogger(__name__)
casagrandeService = deps.get_casagrande_service()I actually did it like this so the casagrandeService is callable in all functions. But came here to figure out if this was a good way to tackle this or not. (Probably not) |
Beta Was this translation helpful? Give feedback.
-
|
I'm guessing no one figured this out and we have to put dependencies on each. and. every. endpoint. Maybe I can convince someone to "Depend" all the routes and I can make it middleware. |
Beta Was this translation helpful? Give feedback.
-
|
what is the point of |
Beta Was this translation helpful? Give feedback.
-
|
edit: fix format maybe adding a dict_dependencies and pass that as a default param to endpoints. for example: |
Beta Was this translation helpful? Give feedback.
Re:
I think the solution looks like this:
Two things:
dependencies=[Depends(get_db)]fromAPIRouterand instead declared annotatedSessionwith the dep.db: Session = Depends(get_db)on every route handler.Imo seems counter intuitive, but I think the magic was that
SessionbeingAnnotatedmakes FastAPI inject it to the route handler.