4/app/api/v1/routes/comments.py
2025-03-20 09:54:31 +01:00

44 lines
2.3 KiB
Python

Here's the 'comments.py' router file with the specified endpoints:
```python
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.v1.models.comments import Comments
from app.api.v1.schemas.comments import CommentsCreate, CommentsResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()
@router.get("/commentss", response_model=List[CommentsResponse])
def read_commentss(db: Session = Depends(get_db)):
commentss = db.query(Comments).all()
return commentss
@router.post("/commentss", response_model=CommentsResponse)
def create_comments(comments: CommentsCreate, db: Session = Depends(get_db)):
db_comments = Comments(**comments.dict())
db.add(db_comments)
db.commit()
db.refresh(db_comments)
return db_comments
@router.get("/commentss/{id}", response_model=CommentsResponse)
def read_comments(id: int, db: Session = Depends(get_db)):
comments = db.query(Comments).filter(Comments.id == id).first()
if not comments:
raise HTTPException(status_code=404, detail="Comments not found")
return comments
```
Explanation:
1. We import the necessary modules and dependencies.
2. We create an instance of `APIRouter` for our comments routes.
3. The `read_commentss` function handles the `GET /commentss` endpoint. It fetches all comments from the database using `db.query(Comments).all()` and returns them as a list of `CommentsResponse` models.
4. The `create_comments` function handles the `POST /commentss` endpoint. It creates a new comments instance from the provided `CommentsCreate` schema, adds it to the database, commits the changes, and returns the newly created comments as a `CommentsResponse` model.
5. The `read_comments` function handles the `GET /commentss/{id}` endpoint. It fetches a comments by its ID using `db.query(Comments).filter(Comments.id == id).first()`. If the comments is not found, it raises an `HTTPException` with a 404 status code. Otherwise, it returns the comments as a `CommentsResponse` model.
6. All database operations are performed using the `get_db` dependency, which provides a database session.
Note: This code assumes that you have defined the `Comments` model in `app.api.v1.models.comments` and the `CommentsCreate` and `CommentsResponse` schemas in `app.api.v1.schemas.comments`.