85 lines
2.5 KiB
Python
85 lines
2.5 KiB
Python
from fastapi import FastAPI, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.utils import create_access_token
|
|
from . import schemas, crud
|
|
from .database import SessionLocal, engine, Base
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
# Dependency
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@app.get("/check-health")
|
|
def health_check():
|
|
return {"Health": "Super Healthy!"}
|
|
|
|
|
|
@app.post("/items/", response_model=schemas.Item)
|
|
def create_item(item: schemas.Item, db: Session = Depends(get_db)):
|
|
return crud.create_item(db, item)
|
|
|
|
|
|
@app.get("/items/", response_model=list[schemas.Item])
|
|
def read_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
|
|
return crud.get_items(db, skip, limit)
|
|
|
|
|
|
@app.get("/items/{item_id}", response_model=schemas.Item)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = crud.get_item(db, item_id)
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
|
|
@app.delete("/items/{item_id}", response_model=schemas.Item)
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
item = crud.delete_item(db, item_id)
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
|
|
# Users
|
|
|
|
|
|
@app.post("/login", response_model=schemas.Token)
|
|
def user_login(
|
|
form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
|
|
):
|
|
user = crud.authenticate_user(db, form_data.username, form_data.password)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
access_token = create_access_token(data={"sub": user.username})
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
|
|
@app.post("/register", response_model=schemas.UserOut)
|
|
def register_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
|
|
if crud.get_user_by_username(db, user.username):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Username already registered",
|
|
)
|
|
if crud.get_user_by_email(db, user.email):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Account with that email already registered",
|
|
)
|
|
return crud.create_user(db, user)
|