Simple TodoList API using FastAPI 🥰
Mon Sep 16 2024 09:29:46 GMT+0000 (Coordinated Universal Time)
Saved by
@freepythoncode
##python
#coding
#python
#programming
#todolist
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from uuid import UUID, uuid4
class Task(BaseModel):
id : UUID = Field(default_factory = uuid4)
name : str
description : str
done: bool = False
tasks_db = []
def find_task(_id):
for idx, task in enumerate(tasks_db):
if task.id == _id:
return idx, task
app = FastAPI()
@app.get('/')
def index():
return {'msg': 'hello, world'}
# Add new task to database
@app.put('/add_task')
def add_task(task : Task):
tasks_db.append(task)
return {'msg': 'Task created', 'task': task}
# Get all tasks from database
@app.get('/tasks')
def get_tasks():
return {'tasks': tasks_db}
# Get one task by id
@app.get('/task/{_id}')
def get_task(_id: UUID):
task = find_task(_id)[1]
if task:
return {'task': task}
return HTTPException(status_code = 404, detail = 'This task is not found :(')
# Update task by id
@app.put('/update_task/{_id}')
def update_task(_id : UUID, updatedtask : Task):
task = find_task(_id)
if task:
task_idx = task[0]
tasks_db[task_idx] = updatedtask
return {'msg': 'Task updated', 'task': updatedtask}
return HTTPException(status_code = 404, detail = 'This task is not found :(')
# Delete task
@app.delete('/delete_task/{_id}')
def delete_task(_id : UUID):
task = find_task(_id)[1]
tasks_db.remove(task)
return {'msg': f'task {task.name} deleted ;)'}
content_copyCOPY
Comments