Skip to content

Instantly share code, notes, and snippets.

@KristinaB
Created August 12, 2023 11:52
Show Gist options
  • Save KristinaB/14393c05f4cf258d71cfe199e3e35a3d to your computer and use it in GitHub Desktop.
Save KristinaB/14393c05f4cf258d71cfe199e3e35a3d to your computer and use it in GitHub Desktop.
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
from sqlalchemy import create_engine, Boolean, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('sqlite:///:memory:')
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
class Todo(Base):
__tablename__ = 'todos'
id = Column(Integer, primary_key=True)
task = Column(String(50))
done = Column(Boolean)
Base.metadata.create_all(bind=engine)
class TodoModel(BaseModel):
id: Optional[int]
task: str
done: bool
app = FastAPI()
@app.get("/todos/")
async def read_todos():
todos = Todo.query.all()
return todos
@app.post("/todos/", response_model=TodoModel)
async def create_todo(todo: TodoModel):
todo_obj = Todo(task=todo.task, done=todo.done)
db_session.add(todo_obj)
db_session.commit()
return todo_obj
@app.put("/todos/{todo_id}", response_model=TodoModel)
async def update_todo(todo_id: int, todo: TodoModel):
todo_obj = Todo.query.get(todo_id)
if todo_obj is None:
return {"error": "Todo not found"}
todo_obj.task = todo.task
todo_obj.done = todo.done
db_session.commit()
return todo_obj
@app.delete("/todos/{todo_id}")
async def delete_todo(todo_id: int):
todo_obj = Todo.query.get(todo_id)
if todo_obj is None:
return {"error": "Todo not found"}
db_session.delete(todo_obj)
db_session.commit()
return {"message": "Todo deleted"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment