To allow users to like or dislike posts in your social media application, you’ll need to create API routes that handle these actions. These routes will interact with your database to create, update, or delete post likes.
Creating API Routes
Python
from fastapi import APIRouter, Depends
from app.models import PostLike
from app.schemas import PostLikeSchema
router = APIRouter()
@router.post("/posts/{post_id}/like")
async def like_post(post_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
# Check if the user has already liked or disliked the post
existing_like = await db.query(PostLike).filter(PostLike.user_id == current_user.id, PostLike.post_id == post_id).first()
if existing_like:
return {"message": "You have already liked or disliked this post"}
# Create a new like
like = PostLike(user_id=current_user.id, post_id=post_id)
db.add(like)
await db.commit()
await db.refresh(like)
return {"message": "Post liked"}
@router.delete("/posts/{post_id}/like")
async def unlike_post(post_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
# Find the existing like
existing_like = await db.query(PostLike).filter(PostLike.user_id == current_user.id, PostLike.post_id == post_id).first()
if not existing_like:
return {"message": "You have not liked or disliked this post"}
# Delete the like
db.delete(existing_like)
await db.commit()
return {"message": "Post unliked"}
Explanation:
- The
like_post
endpoint creates a newPostLike
record if the user hasn’t already liked or disliked the post. - The
unlike_post
endpoint deletes an existingPostLike
record if the user has already liked or disliked the post. - Both endpoints use the
current_user
dependency to retrieve the current user’s information. - The
db
dependency provides access to the database session.
Additional Considerations
- Error Handling: Implement appropriate error handling to catch exceptions like database errors or validation errors.
- Authorization: Ensure that only authenticated users can like or dislike posts.
- Rate Limiting: Consider implementing rate limiting to prevent abuse and spam.
- Performance Optimization: Optimize your database queries for performance, especially if you have a large number of users and posts.