70 lines
2.0 KiB
Python
70 lines
2.0 KiB
Python
from typing import List
|
|
from fastapi import FastAPI, Depends, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import get_db, engine
|
|
from app.db.base import Base
|
|
from app import crud, schemas
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
app = FastAPI(
|
|
title="Todo App API",
|
|
description="A simple Todo application API",
|
|
version="1.0.0",
|
|
openapi_url="/openapi.json",
|
|
)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.get("/")
|
|
def read_root():
|
|
return {"title": "Todo App API", "documentation": "/docs", "health": "/health"}
|
|
|
|
|
|
@app.get("/health")
|
|
def health_check():
|
|
return {"status": "healthy", "service": "Todo App API"}
|
|
|
|
|
|
@app.get("/todos/", response_model=List[schemas.Todo])
|
|
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
todos = crud.get_todos(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@app.post("/todos/", response_model=schemas.Todo)
|
|
def create_todo(todo: schemas.TodoCreate, db: Session = Depends(get_db)):
|
|
return crud.create_todo(db=db, todo=todo)
|
|
|
|
|
|
@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, 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.update_todo(db, todo_id=todo_id, todo_update=todo)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@app.delete("/todos/{todo_id}")
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
if not crud.delete_todo(db, todo_id=todo_id):
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return {"message": "Todo deleted successfully"}
|