Bygga ett JSON CRUD API

Introduktion till FastAPI

Matt Eckerle

Software and Data Engineering Leader

Fyra steg i objektets livscykel (CRUD)

Skapa, läsa, uppdatera och ta bort kring en databas

API-operationer

Skapa

  • POST-operation

Läsa

  • GET-operation

Uppdatera

  • PUT-operation

Ta bort

  • DELETE-operation
Introduktion till FastAPI

Motivering för JSON CRUD API

Grundläggande

  • Hantera hela objektets livscykel
  • Förstå bästa praxis för HTTP API-operationer
  • Utforma egna datahanteringsAPI:er

Möjligheter

  • Affärslogik för mer komplexa dataoperationer
  • Datapipelines med hög genomströmning
  • Inferenspipelines för maskininlärning
Introduktion till FastAPI

Bygga en CRUD-modul

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
Introduktion till FastAPI

POST-endpoint för att skapa

  • Endpoint: /reviews
  • Indata: Review
  • Utdata: 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
Introduktion till FastAPI

GET-endpoint för att läsa

  • Endpoint: /reviews
  • Indata: ?review_id=1234
  • Utdata: 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
Introduktion till FastAPI

PUT-endpoint för att uppdatera

  • Endpoint: /reviews
  • Indata: DbReview
  • Utdata: 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
Introduktion till FastAPI

DELETE-endpoint för att ta bort

  • Endpoint: /reviews
  • Indata: DbReview
  • Utdata: {}
@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 {}
Introduktion till FastAPI

Låt oss öva!

Introduktion till FastAPI

Preparing Video For Download...