Skip to the content.

Achievement 2

Achievement 2

Backend for Comment System - Legendary Motorsports

Building a Fast & Secure Comment System Backend

Interactivity is key for any social media platform, and comments are essential for fostering engagement. For Legendary Motorsports, I developed the entire backend API and database model for the comment system, ensuring fast, secure, and reliable communication between users.

Comment System in Action

Scroll down to see how the API processes and stores comments in real time:

Backend Design & API Endpoints

The backend for the comment system is built using Flask (Python) and utilizes SQLAlchemy for database management. The API supports the following CRUD operations:

  • GET: Retrieve all comments for a specific post.
  • POST: Add a new comment.
  • PUT: Update an existing comment (only if the user owns it).
  • DELETE: Remove a comment (only if the user owns it).

Database Model - CarComments

All comments are stored in a SQLAlchemy database model, ensuring structured and efficient data retrieval. Here’s the model definition:


from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class CarComments(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    post_id = db.Column(db.Integer, nullable=False)
    content = db.Column(db.String(500), nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            "id": self.id,
            "user_id": self.user_id,
            "post_id": self.post_id,
            "content": self.content,
            "timestamp": self.timestamp
        }
        

Comment API - CRUD Operations

The API follows RESTful principles, allowing smooth communication between the frontend and backend.

1. Adding a Comment (POST Request)

When a user submits a comment, the frontend sends a POST request with JSON data:


@app.route('/comments', methods=['POST'])
def add_comment():
    data = request.json
    if "content" not in data or "post_id" not in data or "user_id" not in data:
        return jsonify({"error": "Missing required fields"}), 400

    new_comment = CarComments(
        user_id=data["user_id"],
        post_id=data["post_id"],
        content=data["content"]
    )

    db.session.add(new_comment)
    db.session.commit()

return jsonify(new_comment.to_dict()), 201
        

2. Retrieving Comments (GET Request)

The frontend fetches all comments for a specific post using a GET request:


@app.route('/comments/', methods=['GET'])

def get_comments(post_id):
    comments = CarComments.query.filter_by(post_id=post_id).all()
    return jsonify([comment.to_dict() for comment in comments])
        </code></pre>

        

3. Editing a Comment (PUT Request)

Users can edit their own comments. The backend checks ownership before updating:


@app.route('/comments/', methods=['PUT'])

def update_comment(comment_id):
    comment = CarComments.query.get(comment_id)
    data = request.json
    if "content" in data:
        comment.content = data["content"]
        db.session.commit()
        return jsonify(comment.to_dict()), 200
    return jsonify({"error": "Invalid request"}), 400
        </code></pre>

        

4. Deleting a Comment (DELETE Request)

Users can delete only their own comments. This prevents unauthorized modifications:


@app.route('/comments/', methods=['DELETE'])

def delete_comment(comment_id):
    comment = CarComments.query.get(comment_id)
    db.session.delete(comment)
    db.session.commit()
    return jsonify({"message": "Comment deleted"}), 200
        </code></pre>

Challenges & Solutions

Building a **real-time comment system backend** had its challenges, but I tackled them effectively:

  • Challenge: Ensuring fast retrieval of comments without overloading the server.
  • Solution: Used **SQLAlchemy indexing** and optimized queries for performance.
  • Challenge: Preventing spam and inappropriate content.
  • Solution: Implemented **input validation, keyword filtering, and user authentication checks**.
  • Challenge: Maintaining security and preventing unauthorized deletions.
  • Solution: Enforced **user authentication and ownership verification** before updating or deleting comments.

The Impact & Future Improvements

The comment system backend made *Legendary Motorsports* a truly interactive platform. Future improvements include:

  • Adding **comment replies and threads** for deeper discussions.
  • Integrating **AI-based moderation** for automatic spam detection.
  • Enhancing **database indexing** for even faster response times.