58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
from fastapi import FastAPI, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from models import Todo, SessionLocal
|
|
from schemas import TodoCreate, TodoResponse
|
|
|
|
app = FastAPI()
|
|
|
|
# Dependency to get database session
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
@app.post("/todos", response_model=TodoResponse, status_code=201)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
db_todo = Todo(**todo.model_dump())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@app.get("/todos", response_model=List[TodoResponse])
|
|
def read_todos(status: Optional[str] = None, db: Session = Depends(get_db)):
|
|
if status:
|
|
todos = db.query(Todo).filter(Todo.status == status).all()
|
|
else:
|
|
todos = db.query(Todo).all()
|
|
return todos
|
|
|
|
@app.get("/todos/{todo_id}", response_model=TodoResponse)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return todo
|
|
|
|
@app.put("/todos/{todo_id}", response_model=TodoResponse)
|
|
def update_todo(todo_id: int, todo: TodoCreate, db: Session = Depends(get_db)):
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if not db_todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
for key, value in todo.model_dump().items():
|
|
setattr(db_todo, key, value)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@app.delete("/todos/{todo_id}", status_code=204)
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if not db_todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
db.delete(db_todo)
|
|
db.commit() |