Xây dựng API JSON CRUD

Nhập môn FastAPI

Matt Eckerle

Software and Data Engineering Leader

Bốn bước vòng đời quản lý đối tượng (CRUD)

Tạo, Đọc, Cập nhật và Xóa quanh một cơ sở dữ liệu

Thao tác API

Tạo

  • Thao tác POST

Đọc

  • Thao tác GET

Cập nhật

  • Thao tác PUT

Xóa

  • Thao tác DELETE
Nhập môn FastAPI

Động lực API JSON CRUD

Nền tảng

  • Quản lý toàn bộ vòng đời đối tượng
  • Hiểu thực tiễn tốt cho thao tác HTTP API
  • Thiết kế API quản lý dữ liệu của riêng bạn

Cơ hội

  • Logic nghiệp vụ cho thao tác dữ liệu phức tạp hơn
  • Pipeline dữ liệu thông lượng cao
  • Pipeline suy luận Machine Learning
Nhập môn FastAPI

Xây dựng mô-đun CRUD

from pydantic import BaseModel

class Review(BaseModel):
    movie: str
    num_stars: int
    text: str

class DbReview(BaseModel):
    movie: str
    num_stars: int
    text: str
    # Reference database ID of Reviews
    review_id: int
# crud.py
def create_review(review: Review):
    # Create review in database

def read_review(review_id: int):
    # Read review from database

def update_review(review: DbReview):
    # Update review in database

def delete_review(review_id: int):
    # Delete review from database
Nhập môn FastAPI

Endpoint POST để tạo

  • Endpoint: /reviews
  • Đầu vào: Review
  • Đầu ra: DbReview
@app.post("/reviews", response_model=DbReview)
def create_review(review: Review):
    # Create the movie review in the database
    db_review = crud.create_review(review)
    # Return the created review with database ID
    return db_review
Nhập môn FastAPI

Endpoint GET để đọc

  • Endpoint: /reviews
  • Đầu vào: ?review_id=1234
  • Đầu ra: DbReview
@app.get("/reviews", response_model=DbReview)
def read_review(review_id: int):
    # Read the movie review from the database
    db_review = crud.read_review(review_id)
    # Return the review
    return db_review
Nhập môn FastAPI

Endpoint PUT để cập nhật

  • Endpoint: /reviews
  • Đầu vào: DbReview
  • Đầu ra: 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

Endpoint DELETE để xóa

  • Endpoint: /reviews
  • Đầu vào: DbReview
  • Đầu ra: {}
@app.delete("/reviews")
def delete_review(review: DbReview):
    # Delete the movie review from the database
    crud.delete_review(review.review_id)
    # Return nothing since the data is gone
    return {}
Nhập môn FastAPI

Ayo berlatih!

Nhập môn FastAPI

Preparing Video For Download...