-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyapi.py
More file actions
99 lines (82 loc) · 3.01 KB
/
Copy pathmyapi.py
File metadata and controls
99 lines (82 loc) · 3.01 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
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(title = "Integration")
#database setup
engine = create_engine("sqlite:///users.db", connect_args = {"check_same_thread": False})
SessionLocal = sessionmaker(autocommit = False, autoflush=False, bind = engine)
Base = declarative_base()
#db model
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False)
email = Column(String(100), unique=True, nullable=False)
role = Column(String(100), nullable=False)
Base.metadata.create_all(bind=engine) #model speaks to enginer
#pydantic models
class UserCreate(BaseModel):
name: str
email: str
role: str
class UserResponse(BaseModel):
id: int
name: str
email: str
role: str
class Config:
from_attributes = True
def get_db():
try:
yield SessionLocal()
finally:
SessionLocal().close()
get_db()
@app.get("/")
def root():
return {"message": "Hello World!"}
@app.get("/users/{user_id}", response_model=UserResponse)
def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.post("/users/", response_model=UserResponse)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
if db.query(User).filter(User.email == user.email).first():
raise HTTPException(status_code=400, detail="Email already registered")
new_user = User(**user.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
#update user
@app.put("/users/{user_id}", response_model=UserResponse)
def update_user(user_id:int, user: UserCreate, db:Session = Depends(get_db)):
existing_user = db.query(User).filter(User.id == user_id).first()
if not existing_user:
raise HTTPException(status_code=404, detail="User not found")
if db.query(User).filter(User.email == user.email, User.id != user_id).first():
raise HTTPException(status_code=400, detail="Email already registered")
for feild, value in user.dict().items():
setattr(existing_user, feild, value)
db.commit()
db.refresh(existing_user)
return existing_user
#delete
@app.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
db.delete(user)
db.commit()
return {"detail": "User deleted successfully"}
#get all user
@app.get("/users/", response_model=List[UserResponse])
def get_all_users(db: Session = Depends(get_db)):
users = db.query(User).all()
return users