You can download this code by clicking the button below.
This code is now available for download.
This code creates a FastAPI application to retrieve user data. It uses Pydantic to define data models and leverages FastAPI's dependency injection system to fetch data.
Technology Stack : FastAPI, Pydantic
Code Type : The type of code
Code Difficulty :
def random_user_data():
import random
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
from typing import Optional
class User(BaseModel):
id: int
name: str
age: int
email: EmailStr
is_active: bool
app = FastAPI()
# Dummy data
users = [
User(id=1, name="Alice", age=30, email="alice@example.com", is_active=True),
User(id=2, name="Bob", age=25, email="bob@example.com", is_active=False),
User(id=3, name="Charlie", age=35, email="charlie@example.com", is_active=True)
]
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
user = next((user for user in users if user.id == user_id), None)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
return app