PUT and DELETE operations

Introduction to FastAPI

Matt Eckerle

Software and Data Engineering Leader

PUT vs. DELETE

PUT Operations

  • Traditional use: update an existing object

  • Parameters sent via query string as well as request body

  • Requires an application or framework

    • e.g. cURL, requests
api = "http://moviereviews.co/reviews/1"
body = {"text": "A fantastic movie!"}
response = requests.put(api, json=body)

DELETE Operations

  • Traditional use: delete an existing object

  • Parameters sent via query string as well as request body

  • Requires an application or framework

    • e.g. cURL, requests
api = "http://moviereviews.co/reviews/1"
response = requests.delete(api)
Introduction to FastAPI

Referencing Existing Objects

  • No ORM, so app must map object to ID
  • Database ID - unique identifier
  • _id convention for database IDs
    • review_id: Table reviews, column id
    • Same convention in frameworks with ORM
from pydantic import BaseModel

class DbReview(BaseModel):
    movie: str
    num_stars: int
    text: str
    # Reference database ID of Reviews
    review_id: int
Introduction to FastAPI

Handling a PUT Operation

PUT endpoint to update an existing movie review:

  • Endpoint: /reviews
  • Input: DbReview (from previous slide)
  • 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

Handling a DELETE Operation

DELETE endpoint to remove an existing movie review:

  • Endpoint: /reviews
  • Input: DbReview
  • Output: {}
@app.delete("/reviews")
def delete_review(review: DbReview):
    # Delete the movie review from the database
    crud.delete_review(review)
    # Return nothing since the data is gone
    return {}
Introduction to FastAPI

Let's practice!

Introduction to FastAPI

Preparing Video For Download...