Skip to content

comments.py

This file defines API endpoints for managing user comments on posts, including creation, retrieval, update, and deletion. It ensures proper authentication, authorization, and data validation for all comment operations.

Scope

  • Defines RESTful API endpoints for comment resources.

  • Authenticates and authorizes user requests for comment actions.

  • Validates incoming comment data using Pydantic schemas.

  • Orchestrates comment creation, retrieval, update, and deletion workflows.

  • Handles error conditions and provides appropriate HTTP responses to clients.

File diagram - "comments.py" /app/routes/comments.pyFile diagram - "comments.py"  GlobalImportsAPIRouterDependsstatusHTTPExceptionQuerySessionget_dbget_tokenCommentCreateCommentUpdateCommentResponseCommentServicePostServiceUserServicelogger/app/routes/comments.pyrouterget_current_user()APIRouter()router.post()router.get()router.put()router.delete()get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "comments.py" /app/routes/comments.pyFile diagram - "comments.py"  GlobalImportsAPIRouterDependsstatusHTTPExceptionQuerySessionget_dbget_tokenCommentCreateCommentUpdateCommentResponseCommentServicePostServiceUserServicelogger/app/routes/comments.pyrouterget_current_user()APIRouter()router.post()router.get()router.put()router.delete()get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • APIRouter from fastapi

    Imports APIRouter to create a new router instance, enabling the definition of API endpoints for comment-related operations. It organizes routes and applies common configurations effectively.

  • Depends from fastapi

    Imports Depends for dependency injection, allowing functions like get_db and get_token to provide shared resources or logic to route handlers. This promotes reusability and testability.

  • status from fastapi

    Imports status to access standard HTTP status codes, ensuring consistent and semantically correct responses for API operations. This improves client understanding of request outcomes.

  • HTTPException from fastapi

    Imports HTTPException to raise standard HTTP errors within route handlers, providing structured error responses to API clients. This ensures consistent error handling across the application.

  • Query from fastapi

    Imports Query to define and validate query parameters for API endpoints, such as pagination controls like skip and limit. This ensures robust and flexible data retrieval.

  • Session from sqlalchemy.orm

    Imports Session from SQLAlchemy's ORM, representing a database session. This is crucial for interacting with the database, managing transactions, and performing CRUD operations on models.

  • get_db from app.core.database

    Imports get_db as a dependency to provide a database session to route handlers. This ensures proper database connection management and resource cleanup for each request.

  • get_token from app.core.security

    Imports get_token as a dependency to extract and validate authentication tokens from incoming requests. This is fundamental for securing API endpoints and identifying the current user.

  • CommentCreate, CommentUpdate, CommentResponse from app.schemas.schemas

    Imports Pydantic schemas (CommentCreate, CommentUpdate, CommentResponse) for data validation, serialization, and deserialization of comment-related request bodies and response models. This ensures data integrity.

  • CommentService, PostService, UserService from app.services.service

    Imports various service classes (CommentService, PostService, UserService) to encapsulate business logic and data access operations for comments, posts, and users. This promotes modularity and separation of concerns.

  • logger from app.core.logging

    Imports the logger instance for structured logging of application events, errors, and debugging information. This is essential for monitoring application health and troubleshooting issues effectively.

Variables

  • router

    The APIRouter instance configured with a base prefix and tags for comment-related endpoints. It aggregates all comment routes, making them discoverable and manageable within the API documentation.

Global Code

Initializes the FastAPI APIRouter for comment-related endpoints, setting a common URL prefix and grouping them under the 'Comments' tag for API documentation. This organizes the API structure.

Routers

router

This `router` manages all API endpoints for user comments, providing a dedicated interface for comment operations. It organizes routes for creating, retrieving, updating, and deleting comments. This module integrates seamlessly, enhancing modularity and maintainability.

Prefix

/api/v1/comments

Configuration Details

Tags

  • Comments

Functions

get_current_user

public

Retrieves the currently authenticated user based on the provided token payload. This function is crucial for protecting API endpoints, ensuring only valid, authenticated users can access specific resources and perform authorised actions.
=== " "

Activity Diagram - "get_current_user" /app/routes/comments.pyActivity Diagram - "get_current_user"  Inputs: token_payload, dbExtract user ID from token payloadRetrieve user from database by IDuser not found?yesnoRaise HTTP 404 exception (User not found)return User object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "get_current_user" /app/routes/comments.pyActivity Diagram - "get_current_user"  Inputs: token_payload, dbExtract user ID from token payloadRetrieve user from database by IDuser not found?yesnoRaise HTTP 404 exception (User not found)return User object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "get_current_user" /app/routes/comments.pyMethod diagram - "get_current_user"  get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "get_current_user" /app/routes/comments.pyMethod diagram - "get_current_user"  get_current_useruser_iduserDepends()int()token_payload.get()UserService.get_user_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "get_current_user" Sequence Diagram - "get_current_user"  get_current_userget_tokenget_dbUserServiceCallerget_current_userget_tokenget_dbUserServiceHTTPExceptionCallerCallerget_current_userget_current_userget_tokenget_tokenget_dbget_dbUserServiceUserServiceHTTPExceptionHTTPExceptionget_current_userget_tokenget_dbUserServiceFunction Entryget_current_user(token_payload, db)Retrieve Token Payloadget_token()token_payloadRetrieve Database Sessionget_db()db_sessionExtract User IDExtract user_id from token_payloaduser_id = int(token_payload.get("sub"))Fetch User from Databaseget_user_by_id(db_session, user_id)user_objectHandle User Not Found or Return Useralt[user_object is None]HTTPException(status_code=404, detail="User not found")Function terminates by raising exceptionraise HTTPException[user_object is not None]user_object/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "get_current_user" Sequence Diagram - "get_current_user"  get_current_userget_tokenget_dbUserServiceCallerget_current_userget_tokenget_dbUserServiceHTTPExceptionCallerCallerget_current_userget_current_userget_tokenget_tokenget_dbget_dbUserServiceUserServiceHTTPExceptionHTTPExceptionget_current_userget_tokenget_dbUserServiceFunction Entryget_current_user(token_payload, db)Retrieve Token Payloadget_token()token_payloadRetrieve Database Sessionget_db()db_sessionExtract User IDExtract user_id from token_payloaduser_id = int(token_payload.get("sub"))Fetch User from Databaseget_user_by_id(db_session, user_id)user_objectHandle User Not Found or Return Useralt[user_object is None]HTTPException(status_code=404, detail="User not found")Function terminates by raising exceptionraise HTTPException[user_object is not None]user_object/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def get_current_user(token_payload: dict = Depends(get_token), db: Session = Depends(get_db)):

Input Parameters

  • token_payload (dict)

    Dictionary containing decoded JWT token payload, typically injected by get_token dependency. It must contain a sub key representing the user's ID for successful user retrieval and authentication purposes.

  • db (Session)

    Database session dependency, injected by get_db, providing access to the database. This session is essential for querying the UserService to fetch user details based on the extracted user ID.

Output / Return Values

  • user (User)

    The User object corresponding to the user_id extracted from the token_payload. This object represents the authenticated user, allowing subsequent operations to access user-specific data and permissions securely.

Exceptions

  • HTTPException 404 Not Found [404]

    Raised when UserService.get_user_by_id returns None, indicating no user was found for the given user_id. This signifies an invalid or non-existent user associated with the provided authentication token.

Logic / Execution Flow

  • Extract the user_id from the token_payload dictionary using the sub key, converting it to an integer.
  • Call UserService.get_user_by_id with the database session db and the extracted user_id to retrieve the user.
  • Check if the user object returned from UserService is None:
    • If user is None (user not found):
      • Raise an HTTPException with a 404 Not Found status code and detail message 'User not found'.
  • If a user object is successfully retrieved, return the user object.

Usage Tips

  • Always use get_current_user as a Depends dependency in your FastAPI path operations to automatically handle user authentication. This ensures only authenticated requests proceed, simplifying endpoint security significantly.

  • Ensure your get_token dependency correctly extracts and validates JWTs, populating the token_payload with a reliable sub (subject) field. This sub field is critical for identifying the user.

Additional Notes

  • This function relies on UserService.get_user_by_id to fetch user details; ensure this service method is robust and handles database interactions efficiently. Performance here directly impacts authentication latency.

  • The user_id is cast to an integer; ensure that the sub claim in your JWT token_payload is always an integer or a string representation of an integer to prevent type conversion errors.

Routes

GET /{comment_id}

This route retrieves a specific comment using its unique `comment_id` from the path. It queries the database for the comment. If not found, a `404 Not Found` error is raised. Otherwise, the comment data is returned successfully.
=== " "

Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Endpoint

GET /{comment_id}

Handler Input Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This path parameter is used to query the database for the specific comment record.

  • db (Session)

    The database session dependency injected into the route handler. This Session object provides the necessary connection and methods for interacting with the database to fetch comment data.

Request Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This comment_id is extracted directly from the URL path segment and used for database lookup.

Response / Output

  • CommentResponse (CommentResponse)

    A CommentResponse object representing the retrieved comment data. This object is constructed from the database model and returned upon successful retrieval of the comment.

Status Codes & Exceptions

  • 404 Not Found: This status is returned when no comment matching the provided comment_id is found in the database. The response includes a detail message: 'Comment not found'.

Route Logic / Request Processing

  • Receive GET request for /{comment_id} with path parameter comment_id.
  • Obtain a database session db using dependency injection.
  • Call CommentService.get_comment_by_id with db and comment_id to fetch the comment.
  • Check if the db_comment object returned from the service is None.
    • If db_comment is None: Raise an HTTPException with status_code=404 and detail="Comment not found".
  • If db_comment is not None: Convert db_comment to CommentResponse using CommentResponse.from_orm().
  • Return the CommentResponse object.

Usage Tips

  • Always ensure the comment_id provided in the URL path is a valid integer. Providing a non-integer or non-existent ID will result in an error response.

  • Handle the 404 Not Found response gracefully in your client application. This indicates the requested comment does not exist, requiring appropriate user feedback.

Additional Notes

  • The CommentResponse model ensures consistent data serialization for comments. This abstraction separates the internal database representation from the external API response structure.

  • This endpoint relies on CommentService for database interaction, centralizing data access logic. The get_db dependency ensures proper database session management for each request.

GET /{comment_id}

This route retrieves a specific comment using its unique `comment_id` from the path. It queries the database for the comment. If not found, a `404 Not Found` error is raised. Otherwise, the comment data is returned successfully.
=== " "

Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Endpoint

GET /{comment_id}

Handler Input Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This path parameter is used to query the database for the specific comment record.

  • db (Session)

    The database session dependency injected into the route handler. This Session object provides the necessary connection and methods for interacting with the database to fetch comment data.

Request Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This comment_id is extracted directly from the URL path segment and used for database lookup.

Response / Output

  • CommentResponse (CommentResponse)

    A CommentResponse object representing the retrieved comment data. This object is constructed from the database model and returned upon successful retrieval of the comment.

Status Codes & Exceptions

  • 404 Not Found: This status is returned when no comment matching the provided comment_id is found in the database. The response includes a detail message: 'Comment not found'.

Route Logic / Request Processing

  • Receive GET request for /{comment_id} with path parameter comment_id.
  • Obtain a database session db using dependency injection.
  • Call CommentService.get_comment_by_id with db and comment_id to fetch the comment.
  • Check if the db_comment object returned from the service is None.
    • If db_comment is None: Raise an HTTPException with status_code=404 and detail="Comment not found".
  • If db_comment is not None: Convert db_comment to CommentResponse using CommentResponse.from_orm().
  • Return the CommentResponse object.

Usage Tips

  • Always ensure the comment_id provided in the URL path is a valid integer. Providing a non-integer or non-existent ID will result in an error response.

  • Handle the 404 Not Found response gracefully in your client application. This indicates the requested comment does not exist, requiring appropriate user feedback.

Additional Notes

  • The CommentResponse model ensures consistent data serialization for comments. This abstraction separates the internal database representation from the external API response structure.

  • This endpoint relies on CommentService for database interaction, centralizing data access logic. The get_db dependency ensures proper database session management for each request.

GET /{comment_id}

This route retrieves a specific comment using its unique `comment_id` from the path. It queries the database for the comment. If not found, a `404 Not Found` error is raised. Otherwise, the comment data is returned successfully.
=== " "

Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "GET /{comment_id}" /app/routes/comments.pyActivity Diagram - "GET /{comment_id}"  Inputs: comment_id, dbRetrieve comment by ID from databasecomment not found?yesnoRaise HTTPException (404, "Comment not found")Convert database comment to CommentResponse modelreturn CommentResponse object   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Route diagram - "GET /{comment_id}" /app/routes/comments.pyRoute diagram - "GET /{comment_id}"  GET /{comment_id}CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentResponse.from_orm()Depends()CommentService.get_comment_by_id()HTTPException()CommentService.get_comment_by_id()HTTPException()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "GET /{comment_id}" Sequence Diagram - "GET /{comment_id}"  get_commentCommentServiceDatabaseCommentResponseCallerget_commentCommentServiceDatabaseCommentResponseHTTPExceptionCallerCallerget_commentget_commentCommentServiceCommentServiceDatabaseDatabaseCommentResponseCommentResponseHTTPExceptionHTTPExceptionget_commentCommentServiceDatabaseCommentResponseRoute EntryGET /{comment_id} (comment_id, db_session)Fetch Commentget_comment_by_id(db_session, comment_id)query_by_id(comment_id)db_comment_recorddb_commentHandle Comment Existencealt[Comment not found (db_comment is None)]raise HTTPException(404, "Comment not found")HTTP 404 Not Found[Comment found (db_comment exists)]from_orm(db_comment)CommentResponse_objectHTTP 200 OK (CommentResponse_object)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Endpoint

GET /{comment_id}

Handler Input Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This path parameter is used to query the database for the specific comment record.

  • db (Session)

    The database session dependency injected into the route handler. This Session object provides the necessary connection and methods for interacting with the database to fetch comment data.

Request Parameters

  • comment_id (int)

    The unique integer identifier for the comment to be retrieved. This comment_id is extracted directly from the URL path segment and used for database lookup.

Response / Output

  • CommentResponse (CommentResponse)

    A CommentResponse object representing the retrieved comment data. This object is constructed from the database model and returned upon successful retrieval of the comment.

Status Codes & Exceptions

  • 404 Not Found: This status is returned when no comment matching the provided comment_id is found in the database. The response includes a detail message: 'Comment not found'.

Route Logic / Request Processing

  • Receive GET request for /{comment_id} with path parameter comment_id.
  • Obtain a database session db using dependency injection.
  • Call CommentService.get_comment_by_id with db and comment_id to fetch the comment.
  • Check if the db_comment object returned from the service is None.
    • If db_comment is None: Raise an HTTPException with status_code=404 and detail="Comment not found".
  • If db_comment is not None: Convert db_comment to CommentResponse using CommentResponse.from_orm().
  • Return the CommentResponse object.

Usage Tips

  • Always ensure the comment_id provided in the URL path is a valid integer. Providing a non-integer or non-existent ID will result in an error response.

  • Handle the 404 Not Found response gracefully in your client application. This indicates the requested comment does not exist, requiring appropriate user feedback.

Additional Notes

  • The CommentResponse model ensures consistent data serialization for comments. This abstraction separates the internal database representation from the external API response structure.

  • This endpoint relies on CommentService for database interaction, centralizing data access logic. The get_db dependency ensures proper database session management for each request.

POST /post/{post_id}

This route creates a new comment for a specific post identified by post_id. It requires user authentication, validates post existence, and persists the comment data to the database. A successful creation returns the new comment object.
=== " "

Activity Diagram - "POST /post/{post_id}" /app/routes/comments.pyActivity Diagram - "POST /post/{post_id}"  Inputs: post_id, comment_create, current_user, dbTry Block: Attempt Comment CreationRetrieve post by IDpost not found?yesnoThis immediately exits the try block and transfers control to the appropriate except block.Raise HTTPException (404: Post not found)Set exception_occurred = trueSet exception_type = HTTPExceptionCreate comment in databaseConvert DB comment to response modelSet exception_occurred = falseSet successful_result = CommentResponseCatch Block: Handle ExceptionsNo exception occurred, skip catch blockCaught HTTPExceptionexception_type is HTTPException?yesnoRe-raise HTTPExceptionreturn HTTPExceptionLog generic errorRaise HTTPException (500: Error creating comment)return HTTPExceptionyesexception_occurred is true?noreturn successful_resultyesexception_occurred is false?no   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "POST /post/{post_id}" /app/routes/comments.pyActivity Diagram - "POST /post/{post_id}"  Inputs: post_id, comment_create, current_user, dbTry Block: Attempt Comment CreationRetrieve post by IDpost not found?yesnoThis immediately exits the try block and transfers control to the appropriate except block.Raise HTTPException (404: Post not found)Set exception_occurred = trueSet exception_type = HTTPExceptionCreate comment in databaseConvert DB comment to response modelSet exception_occurred = falseSet successful_result = CommentResponseCatch Block: Handle ExceptionsNo exception occurred, skip catch blockCaught HTTPExceptionexception_type is HTTPException?yesnoRe-raise HTTPExceptionreturn HTTPExceptionLog generic errorRaise HTTPException (500: Error creating comment)return HTTPExceptionyesexception_occurred is true?noreturn successful_resultyesexception_occurred is false?no   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Route diagram - "POST /post/{post_id}" /app/routes/comments.pyRoute diagram - "POST /post/{post_id}"  POST /post/{post_id}Depends()PostService.get_post_by_id()HTTPException()CommentService.create_comment()CommentResponse.from_orm()logger.error()str()Depends()CommentResponse.from_orm()Depends()PostService.get_post_by_id()HTTPException()Depends()str()Depends()str()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Route diagram - "POST /post/{post_id}" /app/routes/comments.pyRoute diagram - "POST /post/{post_id}"  POST /post/{post_id}Depends()PostService.get_post_by_id()HTTPException()CommentService.create_comment()CommentResponse.from_orm()logger.error()str()Depends()CommentResponse.from_orm()Depends()PostService.get_post_by_id()HTTPException()Depends()str()Depends()str()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "POST /post/{post_id}" Sequence Diagram - "POST /post/{post_id}"  create_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponseRoutercreate_commentget_current_userget_dbPostServiceDatabaseSessionCommentServiceCommentResponseLoggerRouterRoutercreate_commentcreate_commentget_current_userget_current_userget_dbget_dbPostServicePostServiceDatabaseSessionDatabaseSessionCommentServiceCommentServiceCommentResponseCommentResponseLoggerLoggercreate_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponsePOST /post/{post_id}Try BlockRe-raise existing HTTPExceptionDependency Injectionget_current_user()current_userget_db()db_sessionPost Retrievalget_post_by_id(db_session, post_id)query(Post).filter(id=post_id).first()post_recordpostPost not foundalt[post is None]raise HTTPException(404, "Post not found")[post exists]Comment Creationcreate_comment(db_session, comment_create, post_id,current_user.id)add(comment_object)comment_objectcommit()successrefresh(comment_object)refreshed_commentdb_commentResponse Formattingfrom_orm(db_comment)formatted_comment_responseCommentResponse (201 Created)Catch Block: HTTPExceptionGeneric exception caughtbreak[HTTPException]HTTPExceptionCatch Block: Other Exceptionbreak[Exception]error(f"Error creating comment: {str(e)}")raise HTTPException(500, "Error creating comment")HTTPException (500 Internal Server Error)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "POST /post/{post_id}" Sequence Diagram - "POST /post/{post_id}"  create_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponseRoutercreate_commentget_current_userget_dbPostServiceDatabaseSessionCommentServiceCommentResponseLoggerRouterRoutercreate_commentcreate_commentget_current_userget_current_userget_dbget_dbPostServicePostServiceDatabaseSessionDatabaseSessionCommentServiceCommentServiceCommentResponseCommentResponseLoggerLoggercreate_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponsePOST /post/{post_id}Try BlockRe-raise existing HTTPExceptionDependency Injectionget_current_user()current_userget_db()db_sessionPost Retrievalget_post_by_id(db_session, post_id)query(Post).filter(id=post_id).first()post_recordpostPost not foundalt[post is None]raise HTTPException(404, "Post not found")[post exists]Comment Creationcreate_comment(db_session, comment_create, post_id,current_user.id)add(comment_object)comment_objectcommit()successrefresh(comment_object)refreshed_commentdb_commentResponse Formattingfrom_orm(db_comment)formatted_comment_responseCommentResponse (201 Created)Catch Block: HTTPExceptionGeneric exception caughtbreak[HTTPException]HTTPExceptionCatch Block: Other Exceptionbreak[Exception]error(f"Error creating comment: {str(e)}")raise HTTPException(500, "Error creating comment")HTTPException (500 Internal Server Error)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Endpoint

POST /post/{post_id}

Handler Input Parameters

  • post_id (int)

    This path parameter identifies the specific post to which the comment will be added. It is crucial for linking the new comment to its parent post.

  • comment_create (CommentCreate)

    This Pydantic model represents the request body containing the new comment's data. It ensures structured input for comment content and other relevant fields.

  • current_user (User)

    This dependency injects the currently authenticated user object. It provides the user.id for associating the new comment with its creator.

  • db (Session)

    This dependency provides a database session object. It is used for all database operations, including fetching the post and creating the new comment.

Request Parameters

  • post_id (int)

    The post_id is extracted from the URL path. It specifies the target post for the new comment, ensuring correct association within the system.

  • comment_create (CommentCreate)

    The request body, parsed into a CommentCreate Pydantic model, contains the actual comment data. This includes the comment's text and any other required fields.

  • current_user.id (int)

    The authenticated user's ID, obtained from current_user dependency, is used to link the newly created comment to its author. This ensures proper ownership.

Response / Output

  • CommentResponse (CommentResponse)

    Upon successful comment creation, a CommentResponse object is returned. This Pydantic model represents the newly created comment, including its ID and content.

Status Codes & Exceptions

  • 201 Created: This status code indicates that the comment was successfully created and persisted in the database. The response body contains the newly created CommentResponse object.
  • 404 Not Found: This status code is returned if the post_id provided in the path does not correspond to an existing post. The comment cannot be created.
  • 500 Internal Server Error: This status code indicates an unexpected server-side error during comment creation. It suggests a problem beyond client control, requiring server investigation.

Route Logic / Request Processing

  • Receive POST request for /post/{post_id} with post_id, comment_create body, current_user, and db session.
  • Attempt to execute the following operations:
    • Retrieve the post from the database using PostService.get_post_by_id with db and post_id.
    • Check if the post object was found.
      • If post is None: raise HTTPException with 404 status and "Post not found" detail.
    • Create a new comment in the database using CommentService.create_comment with db, comment_create data, post_id, and current_user.id.
    • Convert the created database comment db_comment into a CommentResponse Pydantic model using CommentResponse.from_orm.
    • Return the CommentResponse object with 201 Created status.
  • Handle HTTPException specifically:
    • Re-raise the caught HTTPException directly.
  • Handle any other Exception:
    • Log the error using logger.error with a descriptive message including the exception details.
    • Raise HTTPException with 500 Internal Server Error status and "Error creating comment" detail.

Usage Tips

  • Always ensure the post_id exists before attempting to create a comment. A non-existent post_id will result in a 404 Not Found error response.

  • Provide a valid CommentCreate object in the request body. Missing or malformed data will likely lead to validation errors or unexpected server behavior.

Additional Notes

  • This endpoint relies on get_current_user for authentication. Ensure a valid authentication token is provided in the request headers to access this resource.

  • The CommentResponse.from_orm conversion ensures that the database object is correctly serialized into the API's defined response format before being sent.

POST /post/{post_id}

This route creates a new comment for a specific post identified by post_id. It requires user authentication, validates post existence, and persists the comment data to the database. A successful creation returns the new comment object.
=== " "

Activity Diagram - "POST /post/{post_id}" /app/routes/comments.pyActivity Diagram - "POST /post/{post_id}"  Inputs: post_id, comment_create, current_user, dbTry Block: Attempt Comment CreationRetrieve post by IDpost not found?yesnoThis immediately exits the try block and transfers control to the appropriate except block.Raise HTTPException (404: Post not found)Set exception_occurred = trueSet exception_type = HTTPExceptionCreate comment in databaseConvert DB comment to response modelSet exception_occurred = falseSet successful_result = CommentResponseCatch Block: Handle ExceptionsNo exception occurred, skip catch blockCaught HTTPExceptionexception_type is HTTPException?yesnoRe-raise HTTPExceptionreturn HTTPExceptionLog generic errorRaise HTTPException (500: Error creating comment)return HTTPExceptionyesexception_occurred is true?noreturn successful_resultyesexception_occurred is false?no   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "POST /post/{post_id}" /app/routes/comments.pyActivity Diagram - "POST /post/{post_id}"  Inputs: post_id, comment_create, current_user, dbTry Block: Attempt Comment CreationRetrieve post by IDpost not found?yesnoThis immediately exits the try block and transfers control to the appropriate except block.Raise HTTPException (404: Post not found)Set exception_occurred = trueSet exception_type = HTTPExceptionCreate comment in databaseConvert DB comment to response modelSet exception_occurred = falseSet successful_result = CommentResponseCatch Block: Handle ExceptionsNo exception occurred, skip catch blockCaught HTTPExceptionexception_type is HTTPException?yesnoRe-raise HTTPExceptionreturn HTTPExceptionLog generic errorRaise HTTPException (500: Error creating comment)return HTTPExceptionyesexception_occurred is true?noreturn successful_resultyesexception_occurred is false?no   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Route diagram - "POST /post/{post_id}" /app/routes/comments.pyRoute diagram - "POST /post/{post_id}"  POST /post/{post_id}Depends()PostService.get_post_by_id()HTTPException()CommentService.create_comment()CommentResponse.from_orm()logger.error()str()Depends()CommentResponse.from_orm()Depends()PostService.get_post_by_id()HTTPException()Depends()str()Depends()str()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Route diagram - "POST /post/{post_id}" /app/routes/comments.pyRoute diagram - "POST /post/{post_id}"  POST /post/{post_id}Depends()PostService.get_post_by_id()HTTPException()CommentService.create_comment()CommentResponse.from_orm()logger.error()str()Depends()CommentResponse.from_orm()Depends()PostService.get_post_by_id()HTTPException()Depends()str()Depends()str()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "POST /post/{post_id}" Sequence Diagram - "POST /post/{post_id}"  create_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponseRoutercreate_commentget_current_userget_dbPostServiceDatabaseSessionCommentServiceCommentResponseLoggerRouterRoutercreate_commentcreate_commentget_current_userget_current_userget_dbget_dbPostServicePostServiceDatabaseSessionDatabaseSessionCommentServiceCommentServiceCommentResponseCommentResponseLoggerLoggercreate_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponsePOST /post/{post_id}Try BlockRe-raise existing HTTPExceptionDependency Injectionget_current_user()current_userget_db()db_sessionPost Retrievalget_post_by_id(db_session, post_id)query(Post).filter(id=post_id).first()post_recordpostPost not foundalt[post is None]raise HTTPException(404, "Post not found")[post exists]Comment Creationcreate_comment(db_session, comment_create, post_id,current_user.id)add(comment_object)comment_objectcommit()successrefresh(comment_object)refreshed_commentdb_commentResponse Formattingfrom_orm(db_comment)formatted_comment_responseCommentResponse (201 Created)Catch Block: HTTPExceptionGeneric exception caughtbreak[HTTPException]HTTPExceptionCatch Block: Other Exceptionbreak[Exception]error(f"Error creating comment: {str(e)}")raise HTTPException(500, "Error creating comment")HTTPException (500 Internal Server Error)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "POST /post/{post_id}" Sequence Diagram - "POST /post/{post_id}"  create_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponseRoutercreate_commentget_current_userget_dbPostServiceDatabaseSessionCommentServiceCommentResponseLoggerRouterRoutercreate_commentcreate_commentget_current_userget_current_userget_dbget_dbPostServicePostServiceDatabaseSessionDatabaseSessionCommentServiceCommentServiceCommentResponseCommentResponseLoggerLoggercreate_commentget_current_userget_dbPostServiceDatabaseSessionDatabaseSessionDatabaseSessionDatabaseSessionCommentServiceCommentResponsePOST /post/{post_id}Try BlockRe-raise existing HTTPExceptionDependency Injectionget_current_user()current_userget_db()db_sessionPost Retrievalget_post_by_id(db_session, post_id)query(Post).filter(id=post_id).first()post_recordpostPost not foundalt[post is None]raise HTTPException(404, "Post not found")[post exists]Comment Creationcreate_comment(db_session, comment_create, post_id,current_user.id)add(comment_object)comment_objectcommit()successrefresh(comment_object)refreshed_commentdb_commentResponse Formattingfrom_orm(db_comment)formatted_comment_responseCommentResponse (201 Created)Catch Block: HTTPExceptionGeneric exception caughtbreak[HTTPException]HTTPExceptionCatch Block: Other Exceptionbreak[Exception]error(f"Error creating comment: {str(e)}")raise HTTPException(500, "Error creating comment")HTTPException (500 Internal Server Error)/app/routes/comments.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Endpoint

POST /post/{post_id}

Handler Input Parameters

  • post_id (int)

    This path parameter identifies the specific post to which the comment will be added. It is crucial for linking the new comment to its parent post.

  • comment_create (CommentCreate)

    This Pydantic model represents the request body containing the new comment's data. It ensures structured input for comment content and other relevant fields.

  • current_user (User)

    This dependency injects the currently authenticated user object. It provides the user.id for associating the new comment with its creator.

  • db (Session)

    This dependency provides a database session object. It is used for all database operations, including fetching the post and creating the new comment.

Request Parameters

  • post_id (int)

    The post_id is extracted from the URL path. It specifies the target post for the new comment, ensuring correct association within the system.

  • comment_create (CommentCreate)

    The request body, parsed into a CommentCreate Pydantic model, contains the actual comment data. This includes the comment's text and any other required fields.

  • current_user.id (int)

    The authenticated user's ID, obtained from current_user dependency, is used to link the newly created comment to its author. This ensures proper ownership.

Response / Output

  • CommentResponse (CommentResponse)

    Upon successful comment creation, a CommentResponse object is returned. This Pydantic model represents the newly created comment, including its ID and content.

Status Codes & Exceptions

  • 201 Created: This status code indicates that the comment was successfully created and persisted in the database. The response body contains the newly created CommentResponse object.
  • 404 Not Found: This status code is returned if the post_id provided in the path does not correspond to an existing post. The comment cannot be created.
  • 500 Internal Server Error: This status code indicates an unexpected server-side error during comment creation. It suggests a problem beyond client control, requiring server investigation.

Route Logic / Request Processing

  • Receive POST request for /post/{post_id} with post_id, comment_create body, current_user, and db session.
  • Attempt to execute the following operations:
    • Retrieve the post from the database using PostService.get_post_by_id with db and post_id.
    • Check if the post object was found.
      • If post is None: raise HTTPException with 404 status and "Post not found" detail.
    • Create a new comment in the database using CommentService.create_comment with db, comment_create data, post_id, and current_user.id.
    • Convert the created database comment db_comment into a CommentResponse Pydantic model using CommentResponse.from_orm.
    • Return the CommentResponse object with 201 Created status.
  • Handle HTTPException specifically:
    • Re-raise the caught HTTPException directly.
  • Handle any other Exception:
    • Log the error using logger.error with a descriptive message including the exception details.
    • Raise HTTPException with 500 Internal Server Error status and "Error creating comment" detail.

Usage Tips

  • Always ensure the post_id exists before attempting to create a comment. A non-existent post_id will result in a 404 Not Found error response.

  • Provide a valid CommentCreate object in the request body. Missing or malformed data will likely lead to validation errors or unexpected server behavior.

Additional Notes

  • This endpoint relies on get_current_user for authentication. Ensure a valid authentication token is provided in the request headers to access this resource.

  • The CommentResponse.from_orm conversion ensures that the database object is correctly serialized into the API's defined response format before being sent.

FAQs

Why is get_current_user implemented as a dependency?

get_current_user is a FastAPI dependency function, ensuring user authentication and retrieval are consistently applied across multiple routes. This promotes reusability and separation of concerns effectively throughout the API layer.

What is the purpose of CommentResponse.from_orm?

CommentResponse.from_orm converts SQLAlchemy ORM model instances into Pydantic response models. This ensures data serialization, validation, and proper formatting before sending responses to clients, maintaining API contract consistency and clarity.

Why are CommentService, PostService, and UserService used?

These services encapsulate specific business logic and data access for their respective domains. This promotes separation of concerns, reusability, and maintainability, keeping the API layer focused on request handling and orchestration rather than implementation details.

Insights

Metric Score Level
Complexity 0.70 High Complexity
Security 0.80 Secure
Performance 0.70 Acceptable Performance

Complexity

Medium - Repetitive Error Handling Logic

The error handling for create_comment, update_comment, and delete_comment is duplicated. Centralizing this logic into a custom exception handler or decorator would improve maintainability and reduce boilerplate.

Security

High - Missing Rate Limiting on Comment Operations

There is no explicit rate limiting implemented for comment creation, update, or deletion endpoints. This could expose the API to abuse, such as spamming or denial-of-service attacks, by malicious users.

Performance

Medium - Potential N+1 Query Issue in Response Model

The CommentResponse.from_orm conversion might trigger N+1 queries if the CommentResponse model accesses related entities (e.g., author details) that are not eagerly loaded by the service layer. This could impact performance.