from typing import List from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.db import get_db from app.models import Comment from app.schemas import CommentCreate, CommentResponse router = APIRouter( prefix="/comments", tags=["Comments"], @router.post("/", response_model=CommentResponse, status_code=status.HTTP_201_CREATED) def create_comment(comment: CommentCreate, db: Session = Depends(get_db)): new_comment = Comment(**comment.dict()) db.add(new_comment) db.commit() db.refresh(new_comment) return new_comment @router.get("/", response_model=List[CommentResponse]) def get_all_comments(db: Session = Depends(get_db)): comments = db.query(Comment).all() return comments @router.get("/{comment_id}", response_model=CommentResponse) def get_comment(comment_id: int, db: Session = Depends(get_db)): comment = db.query(Comment).filter(Comment.id == comment_id).first() if not comment: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Comment not found") return comment @router.put("/{comment_id}", response_model=CommentResponse) def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depends(get_db)): db_comment = db.query(Comment).filter(Comment.id == comment_id).first() if not db_comment: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Comment not found") db_comment.text = comment.text db.commit() db.refresh(db_comment) return db_comment @router.delete("/{comment_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_comment(comment_id: int, db: Session = Depends(get_db)): comment = db.query(Comment).filter(Comment.id == comment_id).first() if not comment: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Comment not found") db.delete(comment) db.commit() return This code defines a `router` object with the prefix `/comments` and the tag `"Comments"`. The router contains the following endpoints: Note: You'll need to define the `Comment`, `CommentCreate`, and `CommentResponse` models and schemas in the appropriate files (`models.py` and `schemas.py`) for this code to work correctly.