FastAPI CRUD操作

2024/02/21に公開

FastAPI CRUD操作

FastAPI CRUD操作について紹介していきます。CRUD操作ができるようになればその言語に対する基礎的な操作は行えるようになります。

CRUD操作とは

英語 意味
C Create(作成) post
R Read(読む) get
U Update(更新) put
D Delete(削除) delete

エンジニアとして必要となる基本的な操作をCRUD操作と言います。作成・読む・更新・削除の4つです。

Create(作成) post

from fastapi import APIRouter, Path, Query, HTTPException
# fastapiの基盤として使用されているstarletteのstatusを使用する。外部から入れる必要ない。fastapiはデフォルトで200だけど、それ以外のステータスコードを使う場合はstarletteのstatusを使用する
from starlette import status
from cruds import item as item_crud
from schema import ItemCreate, ItemUpdate, ItemResponse

@router.get("", response_model=list[ItemResponse], status_code=status.HTTP_200_OK)
async def find_all():
    return item_crud.find_all()


# パスパラメーター
# gt=0は0より大きいという制約
# Path()はデフォルト値として扱われるため、それ以降の引数はデフォルト値を持つ必要がある
@router.get("/{id}", response_model=ItemResponse, status_code=status.HTTP_200_OK)
async def find_by_id(id: int = Path(gt=0)):
    found_item = item_crud.find_by_id(id)
    if not found_item:
        raise HTTPException(status_code=404, detail="Item not found")
    return found_item


# クエリパラメーター
@router.get("/", response_model=ItemResponse, status_code=status.HTTP_200_OK)
async def find_by_name(name: str = Query(min_length=2, max_length=10)):
    item_name = item_crud.find_by_name(name)
    if not item_name:
        raise HTTPException(status_code=404, detail="Item not found")
    return item_name

Read(読む) get

from fastapi import APIRouter, Path, Query, HTTPException
# fastapiの基盤として使用されているstarletteのstatusを使用する。外部から入れる必要ない。fastapiはデフォルトで200だけど、それ以外のステータスコードを使う場合はstarletteのstatusを使用する
from starlette import status
from cruds import item as item_crud
from schema import ItemCreate, ItemUpdate, ItemResponse

# リクエストボディ
# postはリクエストボディで送信する
@router.post("", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create(item_create: ItemCreate):
    return item_crud.create(item_create)

Update(更新) put

@router.put("/{id}", response_model=ItemResponse, status_code=status.HTTP_200_OK)
# async def update(id: int, item_update=Body()):
async def update(item_update: ItemUpdate, id: int = Path(gt=0)):
    update_item = item_crud.update(id, item_update)
    if not update_item:
        raise HTTPException(status_code=404, detail="Item not found")
    return update_item

Delete(削除) delete


@router.delete("/{id}", response_model=ItemResponse, status_code=status.HTTP_200_OK)
async def delete(id: int = Path(gt=0)):
    delete_item = item_crud.find_by_id(id)
    if not delete_item:
        raise HTTPException(status_code=404, detail="Item not found")
    return delete_item

Discussion