64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
from fastapi import FastAPI, HTTPException, Depends, Query
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
from datetime import date
|
|
|
|
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)
|
|
async 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])
|
|
async def read_todos(status: Optional[str] = Query(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)
|
|
async 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)
|
|
async def update_todo(todo_id: int, todo_update: TodoCreate, 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")
|
|
|
|
todo.title = todo_update.title
|
|
todo.description = todo_update.description
|
|
todo.due_date = todo_update.due_date
|
|
todo.status = todo_update.status
|
|
|
|
db.commit()
|
|
db.refresh(todo)
|
|
return todo
|
|
|
|
@app.delete("/todos/{todo_id}", status_code=204)
|
|
async def delete_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")
|
|
|
|
db.delete(todo)
|
|
db.commit() |