Automated Action 0976677a4c Build Todo application with FastAPI and SQLite
- Set up project structure with FastAPI and SQLAlchemy
- Create Todo model, schemas, and CRUD operations
- Add API endpoints for todo operations (create, read, update, delete)
- Set up Alembic for database migrations
- Add health check endpoint
- Update README with detailed instructions

generated with BackendIM... (backend.im)
2025-05-13 12:38:16 +00:00

60 lines
2.2 KiB
Python

import uvicorn
from fastapi import FastAPI, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pathlib import Path
from typing import List, Optional
from app import models, schemas, crud
from app.database import SessionLocal, engine, init_db
app = FastAPI(title="Todo Application API",
description="A simple Todo application API built with FastAPI and SQLAlchemy",
version="1.0.0")
# Initialize database
init_db()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/health", status_code=status.HTTP_200_OK)
def health_check():
return {"status": "healthy"}
@app.post("/todos/", response_model=schemas.Todo, status_code=status.HTTP_201_CREATED)
def create_todo(todo: schemas.TodoCreate, db: Session = Depends(get_db)):
return crud.create_todo(db=db, todo=todo)
@app.get("/todos/", response_model=List[schemas.Todo])
def read_todos(skip: int = 0, limit: int = 100, completed: Optional[bool] = None, db: Session = Depends(get_db)):
return crud.get_todos(db=db, skip=skip, limit=limit, completed=completed)
@app.get("/todos/{todo_id}", response_model=schemas.Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
db_todo = crud.get_todo(db=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)
def update_todo(todo_id: int, todo: schemas.TodoUpdate, db: Session = Depends(get_db)):
db_todo = crud.get_todo(db=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}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
db_todo = crud.get_todo(db=db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
crud.delete_todo(db=db, todo_id=todo_id)
return None
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)