Can I directly call another route from a route? #7913
-
First check
DescriptionIs it possible to call another route by using all usual FastAPI functionality? Example: If I query If requesting above This is a constructed problem, but I stumbled upon it and wondered. A solution is certainly to create a separate non-route function that does the business logic of |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
|
You can call the route functions directly, but if you do so, you lose the dependency injection. In particular, if the functions have default values of a type like As you noted, the easiest way to accomplish this might be to separate the shared business logic into a reusable function. There are other patterns you could use, such as a class-based dependency, that might enable you to refactor the code in a way you find more reusable, but it would probably require a larger refactor than would be ideal. But right now I'm not sure there is currently a good way to accomplish the pattern you would like to use here directly. (It's not an unreasonable request, but I'm not sure how much complexity would need to be added to the dependency injection logic to make it possible. My guess is it would be more than it's probably worth, sadly.) |
Beta Was this translation helpful? Give feedback.
-
|
Ok thank you for clarification, that is what I suspected. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help here @dmontagu ! 🍰 🙇♂️ Thanks @sschiessl-bcp for reporting back and closing the issue 👍 |
Beta Was this translation helpful? Give feedback.
-
|
this is one of the main reasons i don't use dependency injection. class-based and object inheritance, and creating decorators instead of majic injections, leads to me to more reusable code. kindof disappointed that fastapi doesn't work a little harder to be compatible with class/object based systems. worse... if you have a Request object as a parameter... you can't trivially construct that and pass that to another route. |
Beta Was this translation helpful? Give feedback.
You can call the route functions directly, but if you do so, you lose the dependency injection. In particular, if the functions have default values of a type like
Query(...)orDepends(dependency_func), you have to provide values, as the "defaults" are not actually valid, and are not substituted based on the request unless called by FastAPI.As you noted, the easiest way to accomplish this might be to separate the shared business logic into a reusable function.
There are other patterns you could use, such as a class-based dependency, that might enable you to refactor the code in a way you find more reusable, but it would probably require a larger refactor than would be ideal. But right n…