Where to put depends/ dependendies for authentication in Fastapi?

Viewed 3372

I've seen two different methods of using depends in Fastapi authentication:

Method 1:

@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
    return user

and method 2:

@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
    return user

What is the difference between method 1 and method 2 and which is better for securing an API i.e. requiring authentication?

2 Answers

As @Omer Alkin correctly noted, a dependency needs to be specified in the path operation parameter list when we want to use its return value (user or token or smth.). Here's an example from the documentation:

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)
    return user


@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

If the return value of dependency is not important to us or it is not returned, but only a side effect is important, for example, the dependency throws an exception, then we can specify the dependency in the path operation decorator.

In this case, we can also execute the dependency (do authentication) immediately for a group of operations, using APIRouter:


async def get_token_header(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")

router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)

It should also be noted that you can reuse the same dependency in the path operation or its sub dependencies, as FastAPI implements the cache policy by default:

If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.

In some cases you don't really need the return value of a dependency inside your path operation function. Or the dependency doesn't return a value. But you still need it to be executed/solved. For those cases, instead of declaring a path operation function parameter with Depends, you can add a list of dependencies to the path operation decorator.

More detail and tips can be found in here: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/

Related