Thao tác PUT và DELETE

Nhập môn FastAPI

Matt Eckerle

Software and Data Engineering Leader

PUT vs. DELETE

Thao tác PUT

  • Dùng truyền thống: cập nhật đối tượng hiện có

  • Tham số gửi qua query string và request body

  • Cần ứng dụng hoặc framework

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

Thao tác DELETE

  • Dùng truyền thống: xóa đối tượng hiện có

  • Tham số gửi qua query string và request body

  • Cần ứng dụng hoặc framework

    • ví dụ: cURL, requests
api = "http://moviereviews.co/reviews/1"
response = requests.delete(api)
Nhập môn FastAPI

Tham chiếu đối tượng hiện có

  • Không có ORM, ứng dụng phải ánh xạ đối tượng tới ID
  • ID trong cơ sở dữ liệu: định danh duy nhất
  • Quy ước _id cho ID CSDL
    • review_id: Bảng reviews, cột id
    • Cùng quy ước trong các framework có ORM
from pydantic import BaseModel

class DbReview(BaseModel):
    movie: str
    num_stars: int
    text: str
    # Reference database ID of Reviews
    review_id: int
Nhập môn FastAPI

Xử lý thao tác PUT

Endpoint PUT để cập nhật bài đánh giá phim:

  • Endpoint: /reviews
  • Input: DbReview (từ trang trước)
  • Output: 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
Nhập môn FastAPI

Xử lý thao tác DELETE

Endpoint DELETE để xóa bài đánh giá phim:

  • Endpoint: /reviews
  • Input: DbReview
  • Output: {}
@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 {}
Nhập môn FastAPI

Ayo berlatih!

Nhập môn FastAPI

Preparing Video For Download...