0% found this document useful (0 votes)
7 views18 pages

Chapter 2

Uploaded by

eketha4017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

Chapter 2

Uploaded by

eketha4017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PUT and DELETE

operations
I N T R O D U C T I O N T O FA S TA P I

Matt Eckerle
Software and Data Engineering Leader
PUT vs. DELETE
PUT Operations DELETE Operations
Traditional use: update an existing object Traditional use: delete an existing object

Parameters sent via query string as well as Parameters sent via query string as well as
request body request body

Requires an application or framework Requires an application or framework


e.g. cURL , requests e.g. cURL , requests

api = "http://moviereviews.co/reviews/1" api = "http://moviereviews.co/reviews/1"


body = {"text": "A fantastic movie!"} response = requests.delete(api)
response = requests.put(api, json=body)

INTRODUCTION TO FASTAPI
Referencing Existing Objects
No ORM, so app must map object to ID
from pydantic import BaseModel
Database ID - unique identifier
class DbReview(BaseModel):
_id convention for database IDs
movie: str
review_id : Table reviews , column id
num_stars: int
Same convention in frameworks with
text: str
ORM
# 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!
I N T R O D U C T I O N T O FA S TA P I
Handling errors
I N T R O D U C T I O N T O FA S TA P I

Matt Eckerle
Software and Data Leader
Two Main Reasons To Handle Errors
User error Server error
Invalid or outdated URI Something else happened

Missing or incorrect input


@app.delete("/items")
def delete_item(item: Item):
@app.delete("/items")
try:
def delete_item(item: Item):
crud.delete_item(item)
if item.id not in item_ids:
except Exception:
# Return an error
# Return an error
else:
return {}
crud.delete_item(item)
return {}

INTRODUCTION TO FASTAPI
HTTP Status Codes: "Levels of Yelling"
Enables API to provide status in response 1. Informational responses ( 100 - 199 )
Success, failure, error, etc. 2. Successful responses ( 200 - 299 )
Specific codes defined in HTTP protocol 3. Redirection messages ( 300 - 399 )
Range: 100 - 599
4. Client error responses ( 400 - 499 )
Categorize by first number ( 1 - 5 )
5. Server error responses ( 500 - 599 )

1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

INTRODUCTION TO FASTAPI
Common HTTP Status Codes
Success ( 200 - 299 ) Other responses
200 OK 301 Moved Permantently
Default success response URI changed permanently

201 Created 400 Bad Request


Specific to POST operation Client error

202 Accepted 404 Not Found


Noncommittal. "Working on it" Server cannot find the requested

204 No Content
resource

Success! Nothing more to say 500 Internal Server Error


Server has encountered a situation it
does not know how to handle

INTRODUCTION TO FASTAPI
Handling Errors With Status Codes
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
if item.id not in item_ids:
# Send response with status 404 and specific error message
raise HTTPException(status_code=404, detail="Item not found.")
else:
delete_item_in_database(item)
return {}

INTRODUCTION TO FASTAPI
Let's practice!
I N T R O D U C T I O N T O FA S TA P I
Using async for
concurrent work
I N T R O D U C T I O N T O FA S TA P I

Matt Eckerle
Software and Data Engineering Leader
Why use async? Concurrent Burgers!
Sequential Burgers Concurrent Burgers

1 https://fastapi.tiangolo.com/async/

INTRODUCTION TO FASTAPI
async in practice
Sequential Burgers Concurrent Burgers
Defining a function to get burgers Defining a function to get burgers

# This is not asynchronous async def get_burgers(number: int):


def get_sequential_burgers(number: int): # Do some asynchronous stuff
# Do some sequential stuff return burgers
return burgers
Calling the function asynchronously
Calling the function sequentially
burgers = await get_burgers(2)
burgers = get_burgers(2)

INTRODUCTION TO FASTAPI
FastAPI with async
If we can:

results = await some_library()

Then use async def :

@app.get('/')
async def read_results():
results = await some_library()
return results

Note Only use await inside of functions created with async def

INTRODUCTION TO FASTAPI
When to use async
Use async Don't use async
If our application doesn't have to If our application has to communicate with:
communicate with anything else and wait for
it to respond File system

Database
Examples
Another server
Audio or image processing If we aren't sure
Computer vision

Machine Learning

Deep Learning

INTRODUCTION TO FASTAPI
Let's practice!
I N T R O D U C T I O N T O FA S TA P I

You might also like