Updating entries
PUT method
We have to pass in all the data, not only the fields that have to be updated
First we need to create the Path Operation
Note: Since we're receiving data from the front end, we want to make sure that the data is sent in a predetermined model
We could make another class with the required format
But since the data we expect is the exact same, we will use the
Post
class
class Post(BaseModel):
title: str
content: str
published: bool = True
rating: Optional[int] = None
class Post(BaseModel):
title: str
content: str
published: bool = True
rating: Optional[int] = None
@app.put("/posts/{id}")
def update_posts(id: int, post: Post):
index = find_index_post(id)
# Raising a 404 if post index position of post is not found
if index == None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"post with {id} does not exist")
post_dict = post.dict() # Converting the data sent by frontend to python dict
post_dict["id"] = id # Setting the ID to be equal to the ID from the frontend
my_posts[index] = post_dict # Replace the post with the updated post
return {"data": post_dict} # Return new post post
Below we have the current post:
{
"title": "title of post 1",
"content": "content of post 1"
}
If we want to update we will have to send a PUT request with all the fields, even if we're only updating the title
{
"title": "UPDATED TITLE",
"content": "content of post 1"
}
Last updated