Question regarding protected routes, Depends() and decorators.
See original GitHub issueHi.
I am in the process of moving away from using Flask and Sanic for Web APIs for my Python projects, and would like to start using FastAPI instead as it seems more professional and more suitable for larger projects (in my opinion).
So far I like this library better than the two I have used before, except for one thing.
I have been investigating the documentation of FastAPI regarding protected routes, and was wondering if it is possible to protect a route without passing Depends() as a parameter to the protected function? No offense, but in my personal opinion this makes the syntax look dirty compared to using decorators, or protecting routes by context group such as in Laravel (PHP).
My question is therefore, are there any other possible ways to protect routes somewhat like the example below:
USER = Depends(get_user(fake_users_db, username=username))
@app.get("/profile")
async def get_profile(current_user=USER):
return current_user.username
Or is it possible to create a decorator for Depends() that can be used instead (similar to what Flask has)?
The main thing is that I do not want to pass Depends() as a parameter like this:
@app.get("/login_basic")
async def login_basic(auth: BasicAuth = Depends(basic_auth)):
...
I know this is not an issue and is intended to be like this in the project, but this question is asked out of personal preference of code styling/formatting.
Edit: Additional question since I mentioned Laravels way of handling routes. Would it be possible to create something similar to this?
Route::middleware('auth:api', 'throttle:20,1')->group(function() {
Route::get('/usage', 'AbcController@usage')->name('usage-route');
Route::get('/search/{searchQuery}', 'SearchController@search_method')->name('search-route');
});
from AbcController import Usage
from SearchController import Search
app.add_route_group('authRoutes', [
app.add_route("/usage", Usage())
app.add_route("/search/{searchQuery}", Search(...))
])
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
I would recommend using the
dependencies
argument.You can create the decorator, just use
functools.wraps
to not lose the function signature.And you can use the first approach as well, but not in the way you have written, unless
get_user(...)
returns a callable. If does, then you can do the way you want.