Working with FastAPI

Adding comments to the social media API

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

Modified files

storeapi/routers/posts.py
--- 
+++ 
@@ -1,9 +1,20 @@
-from fastapi import APIRouter
-from storeapi.models.post import UserPost, UserPostIn
+from fastapi import APIRouter, HTTPException
+from storeapi.models.post import (
+    Comment,
+    CommentIn,
+    UserPost,
+    UserPostIn,
+    UserPostWithComments,
+)

 router = APIRouter()

 post_table = {}
+comments_table = {}
+
+
+def find_post(post_id: int):
+    return post_table.get(post_id)


 @router.post("/post", response_model=UserPost, status_code=201)
@@ -18,3 +29,35 @@
 @router.get("/post", response_model=list[UserPost])
 async def get_all_posts():
     return list(post_table.values())
+
+
+@router.post("/comment", response_model=Comment, status_code=201)
+async def create_comment(comment: CommentIn):
+    post = find_post(comment.post_id)
+    if not post:
+        raise HTTPException(status_code=404, detail="Post not found")
+
+    data = comment.model_dump()  # previously .dict()
+    last_record_id = len(comments_table)
+    new_comment = {**data, "id": last_record_id}
+    comments_table[last_record_id] = new_comment
+    return new_comment
+
+
+@router.get("/post/{post_id}/comment", response_model=list[Comment])
+async def get_comments_on_post(post_id: int):
+    return [
+        comment for comment in comments_table.values() if comment["post_id"] == post_id
+    ]
+
+
+@router.get("/post/{post_id}", response_model=UserPostWithComments)
+async def get_post_with_comments(post_id: int):
+    post = find_post(post_id)
+    if not post:
+        raise HTTPException(status_code=404, detail="Post not found")
+
+    return {
+        "post": post,
+        "comments": await get_comments_on_post(post_id),
+    }
storeapi/models/post.py
--- 
+++ 
@@ -7,3 +7,17 @@

 class UserPost(UserPostIn):
     id: int
+
+
+class CommentIn(BaseModel):
+    body: str
+    post_id: int
+
+
+class Comment(CommentIn):
+    id: int
+
+
+class UserPostWithComments(BaseModel):
+    post: UserPost
+    comments: list[Comment]