Vytvoření JSON CRUD API

Úvod do FastAPI

Matt Eckerle

Software and Data Engineering Leader

Čtyři kroky životního cyklu správy objektů (CRUD)

Vytvořit, číst, aktualizovat a mazat kolem databáze

Operace API

Vytvořit

  • Operace POST

Číst

  • Operace GET

Aktualizovat

  • Operace PUT

Smazat

  • Operace DELETE
Úvod do FastAPI

Motivace pro JSON CRUD API

Základy

  • Spravujte celý životní cyklus objektu
  • Pochopte osvědčené postupy pro operace HTTP API
  • Navrhněte vlastní API pro správu dat

Příležitosti

  • Obchodní logika pro složitější datové operace
  • Vysoce výkonné datové pipeline
  • Pipeline pro inference strojového učení
Úvod do FastAPI

Vytváříme modul 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
Úvod do FastAPI

POST endpoint pro vytvoření

  • Endpoint: /reviews
  • Vstup: Review
  • Výstup: 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
Úvod do FastAPI

GET endpoint pro čtení

  • Endpoint: /reviews
  • Vstup: ?review_id=1234
  • Výstup: 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
Úvod do FastAPI

PUT endpoint pro aktualizaci

  • Endpoint: /reviews
  • Vstup: DbReview
  • Výstup: 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
Úvod do FastAPI

DELETE endpoint pro smazání

  • Endpoint: /reviews
  • Vstup: DbReview
  • Výstup: {}
@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 {}
Úvod do FastAPI

Ayo berlatih!

Úvod do FastAPI

Preparing Video For Download...