-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
84 lines (67 loc) · 2.49 KB
/
Copy pathmain.py
File metadata and controls
84 lines (67 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from typing import Dict, Optional
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, EmailStr, constr
app = FastAPI(title="User Directory API")
class User(BaseModel):
id: int
name: constr(strip_whitespace=True, min_length=1)
email: EmailStr
phone: constr(strip_whitespace=True, min_length=7, max_length=20)
class PublicUser(BaseModel):
name: str
email: EmailStr
phone: str
class InfoIn(BaseModel):
name: constr(strip_whitespace=True, min_length=1)
email: EmailStr
class InfoOut(BaseModel):
name: str
email: EmailStr
# In-memory "database"
USERS: Dict[int, User] = {
1: User(id=1, name="Alice Johnson", email="alice@example.com", phone="+1-555-0100"),
2: User(id=2, name="Bob Singh", email="bob@example.com", phone="+91-98765-43210"),
3: User(id=3, name="Charlie Kumar", email="charlie@example.com", phone="+44 20 7946 0958"),
}
@app.get("/users/{user_id}", response_model=PublicUser)
def get_user_by_id(user_id: int):
user = USERS.get(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return PublicUser(name=user.name, email=user.email, phone=user.phone)
@app.get("/info", response_model=PublicUser)
def get_info_by_email(email: EmailStr = Query(..., description="Email to lookup")):
for user in USERS.values():
if user.email.lower() == email.lower():
return PublicUser(name=user.name, email=user.email, phone=user.phone)
raise HTTPException(status_code=404, detail="User not found")
@app.post("/info", response_model=PublicUser)
def post_info(payload: InfoIn):
"""Add a new user with the given name and email.
Returns HTTP 400 if the email already exists.
"""
# Check for duplicate email
email_lower = payload.email.lower()
for user in USERS.values():
if user.email.lower() == email_lower:
raise HTTPException(
status_code=400,
detail="A user with this email already exists"
)
# Generate new ID (max + 1)
new_id = max(USERS.keys(), default=0) + 1
# Create new user with a default phone number
new_user = User(
id=new_id,
name=payload.name,
email=payload.email,
phone="+1-555-0000" # Default phone
)
# Add to our "database"
USERS[new_id] = new_user
# Return public view
return PublicUser(
name=new_user.name,
email=new_user.email,
phone=new_user.phone
)