PUT と DELETE の操作

FastAPI入門

Matt Eckerle

Software and Data Engineering Leader

PUT と DELETE の比較

PUT の操作

  • 従来の用途: 既存オブジェクトを更新

  • パラメータはクエリ文字列とリクエストボディで送信

  • アプリやフレームワークが必要

    • 例: cURL, requests
api = "http://moviereviews.co/reviews/1"
body = {"text": "A fantastic movie!"}
response = requests.put(api, json=body)

DELETE の操作

  • 従来の用途: 既存オブジェクトを削除

  • パラメータはクエリ文字列とリクエストボディで送信

  • アプリやフレームワークが必要

    • 例: cURL, requests
api = "http://moviereviews.co/reviews/1"
response = requests.delete(api)
FastAPI入門

既存オブジェクトの参照

  • ORM なし: アプリがオブジェクトと ID を対応付け
  • データベース ID = 一意の識別子
  • データベース ID の _id 慣習
    • review_id: テーブル reviews、列 id
    • ORM ありのフレームワークでも同様の慣習
from pydantic import BaseModel

class DbReview(BaseModel):
    movie: str
    num_stars: int
    text: str
    # Reference database ID of Reviews
    review_id: int
FastAPI入門

PUT 操作の処理

既存の映画レビューを更新する PUT エンドポイント:

  • エンドポイント: /reviews
  • 入力: DbReview(前スライド)
  • 出力: DbReview
@app.put("/reviews", response_model=DbReview)
def update_review(review: DbReview):
    # Update the movie review in the database
    db_review = crud.update_review(review)
    # Return the updated review
    return db_review
FastAPI入門

DELETE 操作の処理

既存の映画レビューを削除する DELETE エンドポイント:

  • エンドポイント: /reviews
  • 入力: DbReview
  • 出力: {}
@app.delete("/reviews")
def delete_review(review: DbReview):
    # Delete the movie review from the database
    crud.delete_review(review)
    # Return nothing since the data is gone
    return {}
FastAPI入門

演習に進みましょう!

FastAPI入門

Preparing Video For Download...