@@ -596,6 +596,54 @@ async def get_user_post(
596
596
return post
597
597
```
598
598
599
+ ###### Dependencies can include route parameters
600
+
601
+ - Sometimes a dependency requires additional variables to run it's logic.
602
+ - As an example we can imagine an app that has users and projects:
603
+ - To determine if a user has permission to access a project we need both:
604
+ - The user id
605
+ - The project id
606
+ - The user id could be determined via another dependency.
607
+ - However, the project id must be passed in by the user.
608
+
609
+ ``` python
610
+ # logic.py (where dependencies are located)
611
+
612
+ from app.auth.osm import AuthUser, login_required # imported dependency
613
+
614
+ async def validator (
615
+ project_id : int , # The route parameter
616
+ db : Session = Depends(get_db),
617
+ user_data : AuthUser = Depends(login_required), # from imported dependency
618
+ ) -> AuthUser:
619
+ user_id = await get_uid(user_data)
620
+
621
+ match = (
622
+ db.query(DbUserRoles).filter_by(user_id = user_id, project_id = project_id).first()
623
+ )
624
+
625
+ if not match:
626
+ raise HTTPException(status_code = 403 , detail = " User has no access to project" )
627
+
628
+ if match.role.value < ProjectRole.VALIDATOR .value:
629
+ raise HTTPException(
630
+ status_code = 403 , detail = " User is not a validator for this project"
631
+ )
632
+
633
+ return user_data
634
+
635
+ # routes.py (endpoints)
636
+ @router.get (" /get_validator/" )
637
+ async def validator (
638
+ db : Session = Depends(database.get_db),
639
+ user : AuthUser = Depends(validator),
640
+ ):
641
+ return user
642
+ ```
643
+
644
+ When the user calls the ` /get_validator ` endpoint, they will need to provide the
645
+ parameter ` project_id ` , as it is present in the ` validator ` sub dependency.
646
+
599
647
##### 5. Always Use Typing
600
648
601
649
- FastAPI relies on Typing heavily for it's functionality.
0 commit comments