Building a JSON CRUD API

Introduction to FastAPI

Matt Eckerle

Software and Data Engineering Leader

Four Steps in Object Management Lifecycle (CRUD)

Create, Read, Update, and Delete around a Database

API Operations

Create

  • POST operation

Read

  • GET operation

Update

  • PUT operation

Delete

  • DELETE operation
Introduction to FastAPI

JSON CRUD API Motivation

Fundamentals

  • Manage the entire object lifecycle
  • Understand best practices for HTTP API operations
  • Design our own data management APIs

Opportunities

  • Business logic for more complex data operations
  • High throughput data pipelines
  • Machine Learning inference pipelines
Introduction to FastAPI

Building a CRUD Module

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
Introduction to FastAPI

POST Endpoint to Create

  • Endpoint: /reviews
  • Input: Review
  • Output: 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
Introduction to FastAPI

GET Endpoint to Read

  • Endpoint: /reviews
  • Input: ?review_id=1234
  • Output: 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
Introduction to FastAPI

PUT Endpoint to Update

  • Endpoint: /reviews
  • Input: DbReview
  • 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
Introduction to FastAPI

DELETE Endpoint to Delete

  • Endpoint: /reviews
  • Input: DbReview
  • Output: {}
@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 {}
Introduction to FastAPI

Let's practice!

Introduction to FastAPI

Preparing Video For Download...