From 5a056b7e1a643c4e2d2a46e694e9a45b71c80cf9 Mon Sep 17 00:00:00 2001 From: dahbar Date: Fri, 20 Oct 2023 20:07:16 +0200 Subject: [PATCH] Added small API functionality --- main.py | 46 ++++++++++++++++++++++++++++++++++++++++++---- models/todo.py | 6 ++++++ 2 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 models/todo.py diff --git a/main.py b/main.py index 7055f22..70ce30a 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,48 @@ from typing import Union -from fastapi import FastAPI +from fastapi import FastAPI, HTTPException +from models.todo import Todo app = FastAPI() +todos = [] + + @app.get("/") async def read_root(): - return { - "Hello": "World" - } + return {"Hello": "World"} + + +@app.post("/todo/") +async def create_todo(todo: Todo): + todos.append(todo) + return todo + + +@app.get("/todos/") +async def get_todos(): + return todos + + +@app.get("/todo/{todo_title}/") +async def get_todo(todo_title: str): + for todo in todos: + if todo.title == todo_title: + return todo + raise HTTPException(status_code=404) + + +@app.put("/todos/{todo_title}/") +async def update_todo(todo_title: str, new_todo: Todo): + for todo in todos: + if todo.title == todo_title: + todo.title = new_todo.title + todo.description = new_todo.description + return todo + raise HTTPException(status_code=404, detail="Todo not found") + + +@app.delete("/todos/{todo_title}/") +async def delete_todo(todo_title: str): + global todos + todos = [todo for todo in todos if todo.title != todo_title] + return {"message": "Todo deleted successfully"} diff --git a/models/todo.py b/models/todo.py new file mode 100644 index 0000000..09ded2e --- /dev/null +++ b/models/todo.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel + + +class Todo(BaseModel): + title: str + description: str = None