Skip to content

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
  • Read
    • List all posts (GET /posts) — implemented
    • Retrieve one post (GET /posts/{post_id}) — implemented
    • Search posts (GET /posts/search) — implemented
  • Update
    • Update a post (PATCH /posts/{post_id})
  • Delete
    • Delete a post (DELETE /posts/{post_id})

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.

main.py
@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:

main.py
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:

main.py
@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:

main.py
@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, continue moves to the next post.
  • ② If body.title is not None, replace the title.
  • ③ If body.content is not None, replace the content.
  • ④ Return the post and end the function after applying the changes.
  • ⑤ If no post matches, raise HTTPException with 404 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.

main.py
@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 continue to skip nonmatching IDs.
  • ③ Remove the matching post with posts.remove(post).
  • ④ End the function with return. A 204 No Content response 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 HTTPException with 404 Not Found.

Check Your Understanding

Decide whether each statement is true or false.

  1. Read in CRUD means retrieving stored data.
  2. Partial updates must use PUT.
  3. Applying only supplied changes can preserve fields omitted from a partial update.
  4. A 204 No Content response can include the deleted resource in its body.
  5. An update API can return 404 Not Found when the target resource does not exist.
Answers and Explanations
  1. True — CRUD stands for Create, Read, Update, and Delete.
  2. False — PATCH is for partial changes; PUT replaces the whole resource.
  3. True — Unchanged fields retain their previous values.
  4. False — A 204 response indicates success without a response body.
  5. True — A 404 indicates that the requested resource could not be found.