Completing the CRUD API
After publishing a blog post, you should be able to find it in the list, correct a typo, or remove it. These four basic operations—Create, Read, Update, and Delete—are called CRUD.
Our blog APIs fall into these groups:
- Create
- Create a post (
POST /posts) — implemented
- Create a post (
- Read
- List all posts (
GET /posts) — implemented - Retrieve one post (
GET /posts/{post_id}) — implemented - Search posts (
GET /posts/search) — implemented
- List all posts (
- Update
- Update a post (
PATCH /posts/{post_id})
- Update a post (
- Delete
- Delete a post (
DELETE /posts/{post_id})
- Delete a post (
We have implemented creation, listing, retrieval, and search. Let's use what we have learned to add update and delete APIs.
Updating Posts
An existing post may need a corrected title or body. Let's build an API for those changes.
HTTP commonly uses PUT and PATCH for updates. PUT replaces the entire target resource; PATCH applies partial changes.
Our API should allow changing the title without changing the body, or vice versa. PATCH suits this partial update.
First, add a route in main.py that accepts the post ID as a path parameter.
@app.patch(
"/posts/{post_id}",
summary="Update a post",
response_model=PostResponse,
)
def update_post_handler(post_id: int = Path(ge=1)):
return
Defining the Request Model
The body should include only the fields to change. Define this model below PostCreateRequest:
class PostUpdateRequest(BaseModel):
title: str | None = None
content: str | None = None
str | None allows a string or None, and = None provides the value for an omitted field. To change only the title, send {"title": "New title"}. The omitted content becomes None in the model. Send both fields to change both.
Now add the request body parameter:
@app.patch(
"/posts/{post_id}",
summary="Update a post",
response_model=PostResponse,
)
def update_post_handler(
post_id: int = Path(ge=1),
body: PostUpdateRequest = Body(),
):
return
Implementing the Update
Find the post using post_id, then update its title and content. In this example, None means leave the existing value unchanged. Return the updated post, or 404 Not Found if it does not exist.
Complete the handler as follows:
@app.patch(
"/posts/{post_id}",
summary="Update a post",
response_model=PostResponse,
)
def update_post_handler(
post_id: int = Path(ge=1),
body: PostUpdateRequest = Body(),
):
for post in posts:
if post["id"] != post_id: # ①
continue
if body.title is not None: # ②
post["title"] = body.title
if body.content is not None: # ③
post["content"] = body.content
return post # ④
raise HTTPException( # ⑤
status_code=status.HTTP_404_NOT_FOUND,
detail="Post not found.",
)
- ① If the current post's ID does not match,
continuemoves to the next post. - ② If
body.titleis notNone, replace the title. - ③ If
body.contentis notNone, replace the content. - ④ Return the post and end the function after applying the changes.
- ⑤ If no post matches, raise
HTTPExceptionwith404 Not Found.
Deleting Posts
Users may want to remove an accidental or outdated post. Let's add DELETE /posts/{post_id}. The path identifies the post, so no request body is needed.
Find and remove the matching post from posts. Return 204 No Content on success, or 404 Not Found if it does not exist.
@app.delete(
"/posts/{post_id}",
summary="Delete a post",
status_code=status.HTTP_204_NO_CONTENT,
)
def delete_post_handler(post_id: int = Path(ge=1)):
for post in posts: # ①
if post["id"] != post_id: # ②
continue
posts.remove(post) # ③
return # ④
raise HTTPException( # ⑤
status_code=status.HTTP_404_NOT_FOUND,
detail="Post not found.",
)
- ① Iterate over the posts.
- ② Use
continueto skip nonmatching IDs. - ③ Remove the matching post with
posts.remove(post). - ④ End the function with
return. A204 No Contentresponse has no body, so no return data is needed. FastAPI sends it without a body even if the handler returns a value. - ⑤ If no post matches, raise
HTTPExceptionwith404 Not Found.
Check Your Understanding
Decide whether each statement is true or false.
- Read in CRUD means retrieving stored data.
- Partial updates must use PUT.
- Applying only supplied changes can preserve fields omitted from a partial update.
- A 204 No Content response can include the deleted resource in its body.
- An update API can return 404 Not Found when the target resource does not exist.
Answers and Explanations
- True — CRUD stands for Create, Read, Update, and Delete.
- False — PATCH is for partial changes; PUT replaces the whole resource.
- True — Unchanged fields retain their previous values.
- False — A 204 response indicates success without a response body.
- True — A 404 indicates that the requested resource could not be found.