Python API Development - Sanjeev tutorial

Hi all,

I’m trying to follow Sanjeev’s tutorial on python API developement ( Until 7,5 hours I didn’t get any trouble, but now I’m trying to create a new post in postman, using a JWT token as authentication. When I try to do this, I get this error:
“pydantic_core._pydantic_core.ValidationError: 1 validation error for TokenData
Input should be a valid string [type=string_type, input_value=14, input_type=int]”

I’ll try to provide all the relevant code, but if you’re missing something, please let me know.


class TokenData(BaseModel):
    id: Optional[str]


from jose import JWTError, jwt
from datetime import datetime, timedelta
from . import schemas
from fastapi import Depends, status, HTTPException
from import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl='login')

SECRET_KEY = "b8b33abbff04e43b4a43aed2ab1cc44e962d236caee378dcccce9dc46a3a5592"

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

    return encoded_jwt

def verify_access_token(token: str, credentials_exception):
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        id: str = payload.get("user_id")
        if id is None:
            raise credentials_exception
        token_data = schemas.TokenData(id=id)
    except JWTError:
        raise credentials_exception
    return token_data

def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f'Could not validate credentials', headers={'WWW-Authenticate': 'bearer'})
    return verify_access_token(token, credentials_exception)

From"/", status_code=status.HTTP_201_CREATED, response_model=schemas.Post)
def create_post(post: schemas.PostCreate, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)):
    new_post = models.Post(**post.model_dump())
    return new_post

All the indentions seem to get lost when I paste it here, but I hope it’s not a problem. Thank you very much for your help!

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

print("Thanks! I'll keep that in mind!")