간단한 CRUD 애플리케이션 개발

심준석·2024년 5월 2일
0

FastAPI

목록 보기
7/11

기존 아이템을 변경 혹은 삭제하는 라우트

UPDATE 라우트의 요청 바디용 모델

class TodoItem(BaseModel):
    item: str

    class Config:
        schema_extra = {
            "example": {
            "item": "Read the next chapter of the book."
            }
        }

todo 변경을 위해 todo.py에 추가

from model import Todo, TodoItem

...

@todo_router.put("/todo/{todo_id}")
async def update_todo(todo_data: TodoItem, todo_id: int = Path(..., title="The ID of the todo to be updated")) -> dict:
    for todo in todo_list:
        if todo.id == todo_id:
            todo.item = todo_data.item
            return {
                "message" : "Todo updated successfully"
            }
    
    return {
        "message" : "Todo with supplied ID doesn't exist"
    }
    

새로 추가한 라우트를 테스트하자.

curl -X 'POST' \
'http://127.0.0.1:8000/todo' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"id":1, "item":"Example Schema!"}'

잘 적용된거같다.

이제 PUT 요청을 보대서 추가한 아이템을 수정해보자

curl -X 'PUT' \
'http://127.0.0.1:8000/todo/1' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"item":"Read the next chapter of the book"}'

PUT 요청에 의해 UPDATE 라우트가 정상 작동했다.

DELETE 라우트의 요청 바디용 모델

@todo_router.delete("/todo/{todo_id}")
async def delete_single_todo(todo_id: int) -> dict:
    for index in range(len(todo_list)):
        todo = todo_list[index]
        if todo_id == todo_id:
            todo_list.pop(index)
            return {
                "message" : "Todo deleted successfully"
            }
    return {
        "message" : "Todo with supplied ID doesn't exist"
    }

@todo_router.delete("/todo")
async def delete_all_todo() -> dict:
    todo_list.clear()
    return {
        "message" : "Todo deleted successfully"
    }

이제 테스트 해보자.

먼저 신규 todo 아이템을 넣어주자

curl -X 'POST' \
'http://127.0.0.1:8000/todo' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"id":1, "item":"Example Schema!"}'

이제 DELETE 시켜보자.

curl -X 'DELETE' \
'http://127.0.0.1:8000/todo/1' \
-H 'accept: application/json'

삭제됐다!

profile
Developer & Publisher 심준석 입니다.

0개의 댓글