from fastapi import FastAPI, Depends, HTTPException from fastapi.middleware.cors import CORSMiddleware import uvicorn from typing import List from pathlib import Path from app.database import engine, get_db from app import models, schemas, crud from sqlalchemy.orm import Session # Create the database tables models.Base.metadata.create_all(bind=engine) app = FastAPI( title="Todo API", description="A simple Todo API built with FastAPI and SQLite", version="1.0.0" ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/health", tags=["Health"]) async def health_check(): """Health check endpoint""" return {"status": "healthy"} @app.get("/todos", response_model=List[schemas.Todo], tags=["Todos"]) def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): """Get all todos""" todos = crud.get_todos(db, skip=skip, limit=limit) return todos @app.post("/todos", response_model=schemas.Todo, status_code=201, tags=["Todos"]) def create_todo(todo: schemas.TodoCreate, db: Session = Depends(get_db)): """Create a new todo""" return crud.create_todo(db=db, todo=todo) @app.get("/todos/{todo_id}", response_model=schemas.Todo, tags=["Todos"]) def read_todo(todo_id: int, db: Session = Depends(get_db)): """Get a specific todo by id""" db_todo = crud.get_todo(db, todo_id=todo_id) if db_todo is None: raise HTTPException(status_code=404, detail="Todo not found") return db_todo @app.put("/todos/{todo_id}", response_model=schemas.Todo, tags=["Todos"]) def update_todo(todo_id: int, todo: schemas.TodoUpdate, db: Session = Depends(get_db)): """Update a todo""" db_todo = crud.get_todo(db, todo_id=todo_id) if db_todo is None: raise HTTPException(status_code=404, detail="Todo not found") return crud.update_todo(db=db, todo_id=todo_id, todo=todo) @app.delete("/todos/{todo_id}", response_model=schemas.Todo, tags=["Todos"]) def delete_todo(todo_id: int, db: Session = Depends(get_db)): """Delete a todo""" db_todo = crud.get_todo(db, todo_id=todo_id) if db_todo is None: raise HTTPException(status_code=404, detail="Todo not found") return crud.delete_todo(db=db, todo_id=todo_id) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)