[Python] JWT token error: input should be a valid string

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to follow Sanjeev’s tutorial on python API developement (https://www.youtube.com/watch?v=0sOvCWFmrtA 1). 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 id Input should be a valid string [type=string_type, input_value=14, input_type=int]”

    I'm pretty sure I've followed along with the tutorial and that the token is a string, so I don't know where it's going wrong. I’ll try to provide all the relevant code, but if you’re missing something, please let me know.

    From schemas.py:

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


    From oauth2.py:

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

    oauth2_scheme = OAuth2PasswordBearer(tokenUrl='login')


    SECRET_KEY = "b8b33abbff04e43b4a43aed2ab1cc44e962d236caee378dcccce9dc46a3a5592"
    ALGORITHM = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES = 30


    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):
    try:
    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 post.py:

    @router.post("/", 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)):
    print(user_id)
    new_post = models.Post(**post.model_dump())
    db.add(new_post)
    db.commit()
    db.refresh(new_post)
    return new_post


    I've tried to add ': str' behind several values, but it doesn't change the outcome.

    Continue reading...

Compartilhe esta Página