FastAPI User Data Endpoint

  • Share this:

Code introduction


This function creates a FastAPI application, defines a User model, stores some random user data, and provides an API endpoint to retrieve a list of users.


Technology Stack : FastAPI, Pydantic, random

Code Type : FastAPI Web Service

Code Difficulty : Intermediate


                
                    
def random_user_data():
    import random
    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel, Field

    app = FastAPI()

    class User(BaseModel):
        id: int
        name: str = Field(..., min_length=1)
        age: int = Field(..., ge=0)

    users = [
        User(id=random.randint(1, 100), name=f"User_{i}", age=random.randint(18, 60))
        for i in range(5)
    ]

    @app.get("/users", response_model=list[User])
    def get_users():
        return users

    return app