简体   繁体   中英

pydantic.error_wrappers.ValidationError: FastAPI

I'm making a crud in fastapiI have a user model and I created another one called showuser to only show some specific fields in the query, but when I execute the request I get an error.

I just want my request to show the fields I have in showuser.

my schemas

from pydantic import BaseModel
from typing import Optional
from datetime import datetime

# Create a User model
# Create a class for the user


class User(BaseModel):
    username: str
    password: str
    name: str
    lastname: str
    address: Optional[str] = None
    telephone: Optional[int] = None
    email: str
    creation_user: datetime = datetime.now()

# Create UserId model
# Create a class for the UserId
class UserId(BaseModel):
    id: int

# Create a ShowUser model
# Create a class for the ShowUser
class ShowUser(BaseModel):
    username: str
    name: str
    lastname: str
    email: str
    class Config():
        orm_mode = True

and this is the code from user where I implement the api

@router.get('/{user_id}', response_model=ShowUser)
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        return {"Error": "User not found"}
    return {"User": user}

Terminal Message

pydantic.error_wrappers.ValidationError: 4 validation errors for ShowUser 
response -> username
  field required (type-value_error.missing)
response -> name
  field required (type=value_error.missing) 
response -> lastname
  field required (type=value_error.missing) 
response -> email
  field required (type=value_error.missing)

I think the return value of your get_user function is the issue. Rather than returning {"User": user} , try returning just the user object as shown below:

@router.get('/{user_id}', response_model=ShowUser)
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        return {"Error": "User not found"}
    return user

EDIT: The same error will occur if the database does not contain a User object matching the value of user_id . Rather than returning {"Error": "User not found"} , the best way to handle this very common scenario is to raise an HTTPException with a 404 status code and error message:

@router.get('/{user_id}', response_model=ShowUser)
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=int(HTTPStatus.NOT_FOUND),
            detail=f"No user exists with user.id = {user_id}"
        )
    return user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM