-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnota_4.py
More file actions
316 lines (265 loc) · 9.43 KB
/
Copy pathnota_4.py
File metadata and controls
316 lines (265 loc) · 9.43 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
nota_4.py - Complete User Management API (Full CRUD)
This file demonstrates:
- Complete CRUD operations: Create, Read, Update, Delete
- Pydantic models for data validation
- All HTTP methods: GET, POST, PUT, DELETE
- Comprehensive error handling
- Working with JSON files as a database
- Router integration (includes fun router from note_5)
- Response models and status codes
Run with: uvicorn nota_4:app --reload
or: fastapi dev nota_4.py
"""
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
import json
from typing import Optional
from note_5 import router as fun_router # Import the fun router from note_5.py
app = FastAPI(
title="Complete User Management API",
description="Full CRUD operations for user management with fun extras",
version="2.0.0"
)
# Include the fun router from note_5
app.include_router(fun_router)
# ---------- Configuration ----------
JSON_PATH = "json/json_for_pydantic.json"
HTML_PATH = "html/html_prueba.html"
# ---------- Pydantic models ----------
class User(BaseModel):
"""User model with validation"""
id: int = Field(..., description="Unique user identifier", gt=0)
username: str = Field(..., min_length=3, max_length=50, description="Username")
email: str = Field(..., description="User email address")
age: Optional[int] = Field(None, ge=0, le=150, description="User age")
is_active: bool = Field(True, description="Whether user is active")
roles: Optional[list[str]] = Field(None, description="User roles")
model_config = {
"json_schema_extra": {
"examples": [
{
"id": 1,
"username": "johndoe",
"email": "john@example.com",
"age": 30,
"is_active": True,
"roles": ["user", "admin"]
}
]
}
}
# ---------- Helper functions ----------
def read_users_data() -> dict:
"""Read users from JSON file"""
try:
with open(JSON_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Database file not found: {JSON_PATH}"
)
except json.JSONDecodeError:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Database file contains invalid JSON"
)
def write_users_data(data: dict) -> None:
"""Write users to JSON file"""
try:
with open(JSON_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to write to database: {str(e)}"
)
# ---------- HTML endpoint ----------
@app.get("/", response_class=HTMLResponse)
async def root() -> str:
"""
Serve the main HTML page.
"""
try:
with open(HTML_PATH, "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="HTML file not found"
)
# ---------- GET all users ----------
@app.get("/users", response_model=dict)
async def get_users():
"""
Retrieve all users from the database.
- **Returns**: Dictionary containing all users
"""
return read_users_data()
# ---------- GET single user by ID ----------
@app.get("/users/{id_requested}", response_model=User)
async def get_user(id_requested: int):
"""
Retrieve a specific user by ID.
- **id_requested**: The ID of the user to retrieve
- **Returns**: User object if found
- **Raises**: 404 if user not found
"""
data = read_users_data()
for user in data["users"]:
if user["id"] == id_requested:
return User(**user)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with ID {id_requested} not found"
)
# ---------- POST create new user ----------
@app.post(
"/users",
response_model=User,
status_code=status.HTTP_201_CREATED
)
async def create_user(new_user: User):
"""
Create a new user.
- **new_user**: User data (validated by Pydantic)
- **Returns**: The created user
- **Raises**: 400 if ID or email already exists
"""
data = read_users_data()
# Check for duplicate id or email
for user in data["users"]:
if user["id"] == new_user.id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"User with ID {new_user.id} already exists"
)
if user["email"].lower() == new_user.email.lower():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"User with email {new_user.email} already exists"
)
# Add new user
data["users"].append(new_user.model_dump())
write_users_data(data)
return new_user
# ---------- PUT update user ----------
@app.put("/users/{id_requested}", response_model=User)
async def update_user(id_requested: int, updated_user: User):
"""
Update a user completely (PUT - replaces entire user).
- **id_requested**: The ID of the user to update
- **updated_user**: Complete new user data
- **Returns**: The updated user
- **Raises**: 404 if user not found, 400 if ID mismatch or email conflict
"""
data = read_users_data()
# Verify ID consistency
if updated_user.id != id_requested:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"ID in path ({id_requested}) doesn't match ID in body ({updated_user.id})"
)
# Find user index
user_index = None
for index, user in enumerate(data["users"]):
if user["id"] == id_requested:
user_index = index
break
if user_index is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with ID {id_requested} not found"
)
# Check for email conflicts (excluding current user)
for index, user in enumerate(data["users"]):
if index != user_index and user["email"].lower() == updated_user.email.lower():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Email {updated_user.email} is already used by another user"
)
# Update user
data["users"][user_index] = updated_user.model_dump()
write_users_data(data)
return updated_user
# ---------- DELETE user by ID ----------
@app.delete("/users/{id_requested}", status_code=status.HTTP_200_OK)
async def delete_user(id_requested: int):
"""
Delete a user by ID.
- **id_requested**: The ID of the user to delete
- **Returns**: Confirmation message with deleted user info
- **Raises**: 404 if user not found
"""
data = read_users_data()
# Find and delete user
for index, user in enumerate(data["users"]):
if user["id"] == id_requested:
deleted_user = data["users"].pop(index)
write_users_data(data)
return {
"message": "User successfully deleted",
"deleted_user": {
"id": deleted_user["id"],
"username": deleted_user["username"],
"email": deleted_user["email"]
}
}
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with ID {id_requested} not found"
)
# ---------- Health check ----------
@app.get("/health")
async def health_check():
"""
Health check endpoint.
"""
data = read_users_data()
return {
"status": "healthy",
"service": "Complete User Management API",
"version": "2.0.0",
"users_count": len(data.get("users", []))
}
# ---------- Get API statistics ----------
@app.get("/stats")
async def get_stats():
"""
Get API statistics.
"""
data = read_users_data()
users = data.get("users", [])
active_users = sum(1 for user in users if user.get("is_active", False))
inactive_users = len(users) - active_users
return {
"total_users": len(users),
"active_users": active_users,
"inactive_users": inactive_users,
"endpoints": {
"GET": ["/users", "/users/{id}", "/health", "/stats", "/fun/*"],
"POST": ["/users"],
"PUT": ["/users/{id}"],
"DELETE": ["/users/{id}"]
}
}
# ---------- Main ----------
if __name__ == "__main__":
print("Complete User Management API - Full CRUD")
print("=" * 50)
print("To run this app, use:")
print(" uvicorn nota_4:app --reload")
print(" or")
print(" fastapi dev nota_4.py")
print("\nAvailable endpoints:")
print(" GET / - HTML page")
print(" GET /users - List all users")
print(" GET /users/{id} - Get user by ID")
print(" POST /users - Create new user")
print(" PUT /users/{id} - Update user")
print(" DELETE /users/{id} - Delete user")
print(" GET /health - Health check")
print(" GET /stats - API statistics")
print(" GET /fun/* - Fun endpoints (from note_5)")