You can download this code by clicking the button below.
This code is now available for download.
This function generates a specified number of random user data using FastAPI's Pydantic library, including user ID, name, age, and email address.
Technology Stack : FastAPI, Pydantic
Code Type : Generate random user data
Code Difficulty : Intermediate
def random_user_data(num_users):
from random import randint, choice
from pydantic import BaseModel, Field
class User(BaseModel):
id: int = Field(..., alias='_id')
name: str = Field(..., min_length=2, max_length=50)
age: int = Field(..., ge=0, le=120)
email: str = Field(..., regex=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
users = [User(
id=randint(1, 1000),
name=f"User{randint(1, 1000)}",
age=randint(18, 70),
email=f"user{randint(1, 1000)}@example.com"
) for _ in range(num_users)]
return users