FastAPI User Object Generator

  • Share this:

Code introduction


This function uses the FastAPI framework to create a simple API for generating a user object. The user object contains name, age, and email. If the name or age is not provided, a 400 error will be raised.


Technology Stack : FastAPI, Pydantic

Code Type : API

Code Difficulty : Intermediate


                
                    
def random_user_generator(name, age):
    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel, EmailStr

    app = FastAPI()

    class User(BaseModel):
        name: str
        age: int
        email: EmailStr

    def generate_user(name: str, age: int) -> User:
        if not name or not age:
            raise HTTPException(status_code=400, detail="Name and age must be provided")
        return User(name=name, age=age, email=f"{name.lower()}@example.com")

    return generate_user(name, age)