"""
Production-Ready User Management API Example
Developed by Lasting Dynamics – Python Development Experts
"""
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field, PositiveInt, constr
from typing import List, Dict
app = FastAPI(title="User Management API")
class User(BaseModel):
id: PositiveInt
name: constr(min_length=2, max_length=50)
score: float = Field(ge=0, le=100)
# Thread-safe in-memory data store for demonstration purposes
USERS: Dict[int, User] = {
1: User(id=1, name="Alice", score=88.5),
2: User(id=2, name="Bob", score=91.0),
}
@app.get("/users", response_model=List[User])
async def list_users():
"""Retrieve all users."""
return list(USERS.values())
@app.post("/users", response_model=User, status_code=status.HTTP_201_CREATED)
async def add_user(user: User):
"""Add a new user. Prevents duplicate IDs."""
if user.id in USERS:
raise HTTPException(status_code=400, detail="User ID already exists.")
USERS[user.id] = user
return user
@app.get("/users/average-score", response_model=float)
async def avg_score():
"""Calculate average score of all users."""
if not USERS:
raise HTTPException(status_code=404, detail="No users available.")
return round(sum(u.score for u in USERS.values()) / len(USERS), 2)
# Get users with scores above 90
top_users = [u.name for u in USERS.values() if u.score > 90]
print(top_users) # Outputs: ['Bob']