In this section, we’ll extend our social media API to allow users to add comments to existing posts. We’ll utilize FastAPI’s powerful data modeling and relationship capabilities to create a robust and efficient commenting system.
Setting Up the Data Model
First, we’ll define a data model for comments:
Python
from pydantic import BaseModel
class Comment(BaseModel):
content: str
user_id: int
post_id: int
This model ensures that comments have a content
field, a user_id
field, and a post_id
field to associate them with specific posts.
Creating a POST Endpoint
Next, we’ll create a POST endpoint to handle the creation of comments:
Python
from fastapi import APIRouter, HTTPException
router = APIRouter()
@router.post("/posts/{post_id}/comments")
async def create_comment(post_id: int, comment: Comment, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="Post not found")
new_comment = CommentModel(content=comment.content, user_id=comment.user_id, post_id=post_id)
db.add(new_comment)
db.commit()
db.refresh(new_comment)
return new_comment
Explanation:
- The
@router.post("/posts/{post_id}/comments")
decorator defines a POST endpoint for creating comments on a specific post. - The
post_id
path parameter is used to identify the target post. - The
comment
argument is used to receive the comment data. - The
db.query(Post).filter(Post.id == post_id).first()
line retrieves the post with the specified ID from the database. - If the post is not found, a 404 HTTPException is raised.
- A new
CommentModel
instance is created using the comment data and the post ID. - The new comment is added to the database session.
- The changes are committed to the database.
- The created comment is refreshed to get its assigned ID.
- The created comment is returned as a response.
Retrieving Comments for a Post
To retrieve comments for a specific post, you can create a GET endpoint:
Python
@router.get("/posts/{post_id}/comments")
async def get_comments(post_id: int, db: Session = Depends(get_db)):
comments = db.query(Comment).filter(Comment.post_id == post_id).all()
return comments