User authentication with FastAPI

Dependency injection: getting the user

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

Modified files

storeapi/security.py
--- 
+++ 
@@ -1,7 +1,8 @@
 import datetime
+from typing import Annotated
 import logging

-from fastapi import HTTPException, status
+from fastapi import Depends, HTTPException, status
 from fastapi.security import OAuth2PasswordBearer
 from jose import ExpiredSignatureError, JWTError, jwt
 from passlib.context import CryptContext
@@ -62,7 +63,7 @@
     return user


-async def get_current_user(token: str):
+async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
     try:
         payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
         email = payload.get("sub")
storeapi/routers/post.py
--- 
+++ 
@@ -1,6 +1,7 @@
 import logging
+from typing import Annotated

-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, Depends, HTTPException
 from storeapi.database import comment_table, database, post_table
 from storeapi.models.post import (
     Comment,
@@ -10,7 +11,7 @@
     UserPostWithComments,
 )
 from storeapi.models.user import User
-from storeapi.security import get_current_user, oauth2_scheme
+from storeapi.security import get_current_user

 router = APIRouter()

@@ -28,11 +29,11 @@


 @router.post("/post", response_model=UserPost, status_code=201)
-async def create_post(post: UserPostIn, request: Request):
+async def create_post(
+    post: UserPostIn,
+    current_user: Annotated[User, Depends(get_current_user)],
+):
     logger.info("Creating post")
-    current_user: User = await get_current_user(
-        await oauth2_scheme(request)
-    )  # noqa: F841

     data = post.model_dump()  # previously .dict()
     query = post_table.insert().values(data)
@@ -55,11 +56,10 @@


 @router.post("/comment", response_model=Comment, status_code=201)
-async def create_comment(comment: CommentIn, request: Request):
+async def create_comment(
+    comment: CommentIn, current_user: Annotated[User, Depends(get_current_user)]
+):
     logger.info("Creating comment")
-    current_user: User = await get_current_user(
-        await oauth2_scheme(request)
-    )  # noqa: F841

     post = await find_post(comment.post_id)