-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
128 lines (110 loc) · 3.86 KB
/
main.py
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
from fastapi import FastAPI, HTTPException, Depends
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from app.database import engine, get_db
from app.models import Base, User
from app.schema import *
from sqlalchemy.exc import IntegrityError
from app.exceptions import validation_exception_handler
app = FastAPI(swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"})
# Register the custom exception handler
app.add_exception_handler(RequestValidationError, validation_exception_handler)
# Create the database tables if they don't exist
Base.metadata.create_all(bind=engine)
@app.get('/')
def get_home():
"""
Home endpoint to check the API status.
Returns a welcome message.
"""
return {"status": "OK", "message": "Welcome to Home Page"}
@app.get('/users/')
def get_all_users(db: Session = Depends(get_db)):
"""
Endpoint to retrieve all users.
Returns a list of users.
"""
try:
users = db.query(User).all()
user_responses = [UserRead.from_orm(user) for user in users]
return JSONResponse(content={"users": [user.dict() for user in user_responses]})
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error: {str(e)}")
@app.post('/users/')
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
"""
Endpoint to create a new user.
Accepts user details and returns a success message.
"""
try:
db_user = User(name=user.name, email=user.email,
password=user.password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return JSONResponse(content={"status": "ok"})
except IntegrityError:
db.rollback()
return JSONResponse(
status_code=200,
content={"status": "NOT_OK",
"message": "Email already registered"},
)
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error: {str(e)}")
@app.put('/users/{user_id}')
def update_user_by_id(
user_id: int,
user: UserUpdate,
db: Session = Depends(get_db),
):
"""
Update User By ID
This endpoint allows updating a user's details by their ID.
Parameters:
- user_id: int - The ID of the user to update
- user: UserUpdate - The new details for the user
- db: Session - The database session (injected by FastAPI's Depends)
Returns:
- JSONResponse with status and message
"""
try:
db_user = db.query(User).filter(User.id == user_id).first()
if not db_user:
return JSONResponse(
status_code=200,
content={"status": "NOT_OK", "message": "User Not Found"},
)
db_user.name = user.name
db_user.email = user.email
db_user.password = user.password
db.commit()
return JSONResponse(
status_code=200,
content={"status": "OK", "message": "User updated successfully"},
)
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error: {str(e)}")
@app.delete("/users/{user_id}")
def delete_user_by_id(user_id: int, db: Session = Depends(get_db), ):
try:
db_user = db.query(User).filter(User.id == user_id).first()
if not db_user:
return JSONResponse(
status_code=200,
content={"status": "NOT_OK", "message": "User Not Found"},
)
db.delete(db_user)
db.commit()
return JSONResponse(
status_code=200,
content={"status": "OK",
"message": "User Account Deleted successfully"},
)
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=f"Error: {str(e)}")