Construirea unui API JSON CRUD

Introducere în FastAPI

Matt Eckerle

Software and Data Engineering Leader

Cei patru pași ai ciclului de viață al obiectelor (CRUD)

Creare, Citire, Actualizare și Ștergere în jurul unei baze de date

Operații API

Creare

  • Operație POST

Citire

  • Operație GET

Actualizare

  • Operație PUT

Ștergere

  • Operație DELETE
Introducere în FastAPI

Motivație pentru API-ul JSON CRUD

Fundamente

  • Gestionarea întregului ciclu de viață al obiectelor
  • Bune practici pentru operațiile API HTTP
  • Proiectarea API-urilor proprii de gestionare a datelor

Oportunități

  • Logică de business pentru operații complexe cu date
  • Pipelines de date cu randament ridicat
  • Pipelines de inferență Machine Learning
Introducere în FastAPI

Construirea unui 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
Introducere în FastAPI

Endpoint POST pentru creare

  • Endpoint: /reviews
  • Intrare: Review
  • Ieșire: 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
Introducere în FastAPI

Endpoint GET pentru citire

  • Endpoint: /reviews
  • Intrare: ?review_id=1234
  • Ieșire: 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
Introducere în FastAPI

Endpoint PUT pentru actualizare

  • Endpoint: /reviews
  • Intrare: DbReview
  • Ieșire: 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
Introducere în FastAPI

Endpoint DELETE pentru ștergere

  • Endpoint: /reviews
  • Intrare: DbReview
  • Ieșire: {}
@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 {}
Introducere în FastAPI

Să exersăm!

Introducere în FastAPI

Preparing Video For Download...