Is there any way for a FastAPI "dependency" to interpret Path parameters?
I have a lot of functions of the form:
@app.post("/item/{item_id}/process", response_class=ProcessResponse)
async def process_item(item_id: UUID, session: UserSession = Depends(security.user_session)) -> ProcessResponse:
item = await get_item(client_id=session.client_id, item_id=item_id)
await item.process()
Over and over, I need to pass in [multiple] arguments to fetch the required item before doing something with it. This is very repetitive and makes the code very verbose. What I'd really like to do is pass the item in as an argument to the method.
Ideally I'd like to make get_item a dependency or embed it somehow in the router. This would dramatically reduce the repetitive logic and excessively verbose function arguments. The problem is that some critical arguments are passed by the client in the Path.
Is it possible to pass Path arguments into a dependency or perhaps execute the dependency in the router and pass the result?
Depends(item_for_client_from_path)and havingitem_for_client_from_pathdepend on `item_for_client_from_path(item_id=Path(), session=Depends(security.user_session)); i.e. you make dependencies that abstract away those subdependencies that you use each time. Does that match what you're looking for?Path(). I'm new(ish) to FastAPI so I most likely missed something obvious. As in the example above I need to extract a part of the path which may not be in an entirely uniform position. For some functions there may be other items before/item/{item_id}/.../foo/bar/item/{item_id}/.item_idin both locations it'll work as you expect. I'll try to make an example when I have time