You can download this code by clicking the button below.
This code is now available for download.
This function uses Pydantic's BaseModel to validate user data. It accepts a dictionary containing the user's name and age, and then attempts to convert it to a User model. If the data is valid, it returns the validated user object; if the data is invalid, it returns error information.
Technology Stack : Pydantic
Code Type : Pydantic Validation Function
Code Difficulty : Intermediate
from pydantic import BaseModel, ValidationError
class User(BaseModel):
name: str
age: int
def validate_user(user_data):
try:
user = User(**user_data)
return {"status": "valid", "user": user}
except ValidationError as e:
return {"status": "invalid", "errors": e.errors()}
# JSON Explanation