feat:Implements the GET /tasks/{task_id} endpoint to retrieve details of a specific task - #39
Conversation
Implements the GET /tasks/{task_id} endpoint to retrieve details
of a specific task.
- Added get_by_id method to TaskRepository.
- Added get_task_by_id method to TaskService with error handling
for TaskNotFoundException and invalid ObjectId format.
- Updated TaskView to handle requests for a single task ID,
returning 404 for not found and 400 for invalid ID format.
- Added new URL pattern /tasks/<str:task_id> to todo/urls.py.
- Created GetTaskByIdResponse DTO for the response structure.
- Created TaskNotFoundException custom exception.
- Added PATH to ApiErrorSource enum for error reporting.
- Added new API error messages to todo/constants/messages.py.
- Added default SQLite DATABASES configuration to
todo_project/settings/base.py to ensure Django's test runner
operates correctly, resolving teardown errors.
- Added comprehensive unit tests for the new repository method,
service method, and view logic.
- Added integration tests for the new endpoint, covering success (200),
not found (404), and invalid ID format (400) scenarios.
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Summary by CodeRabbit
WalkthroughThis change introduces a new RESTful API endpoint to fetch the details of a single task by its ID. It adds the necessary URL routing, service, repository, and exception handling logic, as well as DTOs and error messages. Comprehensive unit and integration tests are included to verify the new functionality and error handling. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant TaskView
participant TaskService
participant TaskRepository
participant Database
Client->>TaskView: GET /tasks/{task_id}
TaskView->>TaskService: get_task_by_id(task_id)
TaskService->>TaskRepository: get_by_id(task_id)
TaskRepository->>Database: Find task by _id
Database-->>TaskRepository: Task document or None
TaskRepository-->>TaskService: TaskModel or None
alt Task found
TaskService-->>TaskView: TaskDTO
TaskView-->>Client: 200 OK + task details
else Invalid ID format
TaskService-->>TaskView: ValueError
TaskView-->>Client: 400 Bad Request + error
else Task not found
TaskService-->>TaskView: TaskNotFoundException
TaskView-->>Client: 404 Not Found + error
else Unexpected error
TaskService-->>TaskView: Exception
TaskView-->>Client: 500 Internal Server Error
end
Assessment against linked issues
Suggested reviewers
Poem
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (14)
todo/constants/messages.py(3 hunks)todo/dto/responses/create_task_response.py(1 hunks)todo/dto/responses/error_response.py(1 hunks)todo/dto/responses/get_task_by_id_response.py(1 hunks)todo/exceptions/task_exceptions.py(1 hunks)todo/repositories/task_repository.py(2 hunks)todo/services/task_service.py(3 hunks)todo/tests/integration/test_task_detail_api.py(1 hunks)todo/tests/unit/repositories/test_task_repository.py(3 hunks)todo/tests/unit/services/test_task_service.py(2 hunks)todo/tests/unit/views/test_task.py(3 hunks)todo/urls.py(1 hunks)todo/views/task.py(1 hunks)todo_project/settings/base.py(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
todo/urls.py (1)
todo/views/task.py (1)
TaskView(18-132)
todo/repositories/task_repository.py (2)
todo/models/task.py (1)
TaskModel(23-44)todo/repositories/common/mongo_repository.py (1)
get_collection(17-20)
todo/dto/responses/get_task_by_id_response.py (1)
todo/dto/task_dto.py (1)
TaskDTO(10-28)
todo/tests/integration/test_task_detail_api.py (5)
todo/exceptions/task_exceptions.py (1)
TaskNotFoundException(1-2)todo/constants/task.py (2)
TaskPriority(12-15)TaskStatus(4-9)todo/dto/user_dto.py (1)
UserDTO(4-6)todo/dto/task_dto.py (1)
TaskDTO(10-28)todo/views/task.py (1)
get(19-74)
todo/tests/unit/repositories/test_task_repository.py (3)
todo/constants/task.py (2)
TaskPriority(12-15)TaskStatus(4-9)todo/repositories/task_repository.py (2)
TaskRepository(10-93)get_by_id(79-93)todo/models/task.py (1)
TaskModel(23-44)
todo/services/task_service.py (4)
todo/exceptions/task_exceptions.py (1)
TaskNotFoundException(1-2)todo/dto/task_dto.py (1)
TaskDTO(10-28)todo/repositories/task_repository.py (1)
get_by_id(79-93)todo/constants/messages.py (1)
ApiErrors(13-26)
todo/views/task.py (5)
todo/dto/responses/get_task_by_id_response.py (1)
GetTaskByIdResponse(5-6)todo/exceptions/task_exceptions.py (1)
TaskNotFoundException(1-2)todo/constants/messages.py (1)
ApiErrors(13-26)todo/services/task_service.py (1)
get_task_by_id(153-161)todo/dto/responses/error_response.py (3)
ApiErrorResponse(19-22)ApiErrorDetail(13-16)ApiErrorSource(6-10)
🔇 Additional comments (26)
todo/constants/messages.py (1)
23-26: Well-structured error messages for task retrieval functionality.The new API error messages are consistent with existing patterns and provide clear, user-friendly feedback. The use of format placeholders and separate title/detail messages follows established conventions in the codebase.
todo/dto/responses/create_task_response.py (1)
5-5: Good formatting improvement for code readability.Adding the blank line between imports and class definition follows PEP 8 guidelines and improves code readability.
todo/dto/responses/error_response.py (1)
10-10: Appropriate addition to support path parameter error reporting.The new
PATHenum value is well-named and follows the established pattern. This will enable proper error source identification when handling invalid task IDs in URL path parameters for the new endpoint.todo/urls.py (1)
8-8: LGTM! URL pattern follows Django best practices.The new URL pattern correctly implements the task detail endpoint with appropriate string parameter type and descriptive naming. Reusing the existing
TaskViewis an efficient design choice since the view can handle both list and detail scenarios based on the presence oftask_id.todo/dto/responses/get_task_by_id_response.py (1)
1-6: LGTM! Response DTO follows established patterns.The implementation is clean and consistent with the existing codebase patterns. The single
datafield wrappingTaskDTOprovides a clear API response structure that aligns with the system's response design.todo/repositories/task_repository.py (2)
3-3: LGTM! Appropriate import addition for ObjectId functionality.The
ObjectIdimport frombsonis correctly added to support the newget_by_idmethod.
78-93: LGTM! Well-implemented repository method with proper error handling strategy.The
get_by_idmethod implementation is excellent:
- Correct ObjectId handling: Properly converts string ID to
ObjectIdfor MongoDB querying- Appropriate error delegation: Allows
ObjectIdconversion exceptions to bubble up to the service layer, which is the correct architectural choice as seen intodo/views/task.pylines 18-132 whereValueErroris caught and handled appropriately- Clean return logic: Returns
TaskModelinstance when found,Nonewhen not found- Good documentation: Clear docstring following established patterns
- Consistent with codebase: Follows the class method pattern used by other repository methods
The design integrates well with the broader system architecture where the service layer (
TaskService.get_task_by_id) handles exception translation and the view layer provides appropriate HTTP responses.todo/services/task_service.py (3)
22-23: LGTM! Imports are correctly added.The new imports for
TaskNotFoundExceptionandInvalidIdare properly added to support the new functionality.
152-161: Well-implemented error handling and logic.The
get_task_by_idmethod correctly handles the expected error cases:
InvalidIdexception is caught and converted to aValueErrorwith a standardized message- Missing tasks are handled by raising
TaskNotFoundException- Successful retrieval returns a properly prepared
TaskDTOThe implementation follows the established error handling patterns in the codebase.
189-189: Clarify the purpose of explicitly setting_id=None.Setting
_id=Noneexplicitly seems unnecessary since MongoDB will auto-generate an ObjectId when_idis not provided. This change appears unrelated to the main feature.Could you clarify why this change was made? If it's not required for the new functionality, consider removing it to keep the PR focused.
todo/views/task.py (2)
13-14: LGTM! Necessary imports added.The imports for
GetTaskByIdResponseandTaskNotFoundExceptionare correctly added to support the new single task retrieval functionality.
19-68: Excellent implementation with comprehensive error handling.The updated
getmethod correctly handles both the existing paginated list functionality and the new single task retrieval. Key strengths:
- Clean conditional logic based on
task_idpresence- Proper HTTP status codes (200, 400, 404, 500)
- Consistent error response structure using
ApiErrorResponse- Appropriate use of
ApiErrorSource.PATHfor task_id parameter- Fallback error handling for unexpected exceptions
- Debug-aware error details
The implementation follows REST API best practices and maintains consistency with the existing codebase error handling patterns.
todo/tests/unit/services/test_task_service.py (2)
17-19: LGTM! Test imports are properly added.The new imports for
TaskNotFoundException,BsonInvalidId, andApiErrorsare correctly added to support testing the new functionality.
212-248: Comprehensive test coverage for the new service method.The three test methods effectively cover all the critical scenarios:
- Success case - Verifies proper repository call, DTO preparation, and return value
- Not found case - Confirms
TaskNotFoundExceptionis raised with correct message format- Invalid ID format - Ensures
ValueErroris raised when repository throwsInvalidIdThe tests properly mock dependencies and verify both the happy path and error conditions. The use of specific error message assertions ensures consistency with the defined constants.
todo/tests/integration/test_task_detail_api.py (3)
1-17: LGTM! Well-structured test setup.The integration test class is properly set up with necessary imports and a clean setup method. The imports cover all required components for testing the new endpoint functionality.
18-61: Excellent success scenario test coverage.The test effectively validates the happy path:
- Properly mocks the service method with realistic
TaskDTOdata- Uses correct URL reversal for the endpoint
- Verifies HTTP 200 status code
- Thoroughly checks response structure and data fields
- Includes enum serialization verification (priority/status)
- Confirms service method is called with correct parameter
The test data is comprehensive and reflects real-world task attributes.
63-89: Complete error scenario coverage.Both error case tests are well-implemented:
Not Found Test (lines 63-74):
- Correctly simulates
TaskNotFoundException- Verifies 404 status code and error message structure
- Confirms service method invocation
Invalid Format Test (lines 76-89):
- Properly simulates
ValueErrorfor invalid ObjectId format- Verifies 400 status code and error response
- Tests with realistic invalid ID string
The error response structure validation ensures the API returns consistent error formats to clients.
todo/tests/unit/repositories/test_task_repository.py (4)
4-6: LGTM! Appropriate imports for the new functionality.The new imports are necessary and correctly used:
ObjectIdandbson_errorsfor testing ObjectId functionalitycopyfor creating deep copies in test setup
103-112: LGTM! Comprehensive test for successful task retrieval.The test correctly verifies:
- Return type is TaskModel instance
- ID matching between input and result
- Database method called with correct ObjectId filter
- Sample field verification (title)
114-121: LGTM! Proper test for not found scenario.The test correctly verifies:
- Returns None when task doesn't exist
- Database method called with correct ObjectId filter
- Uses a valid but non-existent ObjectId
123-130: LGTM! Good test for invalid ID format handling.The test correctly verifies:
- Raises the expected bson.errors.InvalidId exception
- No database call is made for invalid input
- Uses an appropriately malformed ID string
todo/tests/unit/views/test_task.py (5)
9-9: LGTM! Necessary imports for the new test functionality.The new imports are appropriate:
ObjectIdfor generating valid test IDsGetTaskByIdResponsefor response structure verificationTaskNotFoundExceptionfor exception testingApiErrorsfor error message constantsAlso applies to: 18-20
75-87: LGTM! Comprehensive test for successful task retrieval.The test correctly verifies:
- HTTP 200 status code
- Response data matches expected DTO structure
- Service method called with correct task ID
- Uses valid ObjectId for testing
89-104: LGTM! Thorough test for task not found scenario.The test correctly verifies:
- HTTP 404 status code
- Complete error response structure including statusCode, message, and errors array
- Error source path correctly set to "task_id"
- Service method called with correct task ID
- Uses TaskNotFoundException with proper error message
106-121: LGTM! Proper test for invalid ID format handling.The test correctly verifies:
- HTTP 400 status code for validation error
- Complete error response structure
- Proper error categorization as validation error
- Service method still called (allowing service to handle validation)
- Uses clearly invalid ID string
122-134: LGTM! Good test for unexpected error handling.The test correctly verifies:
- HTTP 500 status code for internal server error
- Generic error response structure
- Service method called with valid task ID
- Proper fallback error handling for unexpected exceptions
method that sets a default descriptive error message, while still allowing a custom message to be passed when raising the exception
/tasks/{task_id} endpoint to retrieve details of a specific task./tasks/{task_id} endpoint to retrieve details of a specific task
…ests . - refactor to use existing fixture instead of local mock data, improving test data consistency.
- Update to use a predefined constant () for its default message, improving consistency with message management. - Correct instantiation in to use instead of , aligning with Pydantic field definitions and alias usage.
- Refactored the monolithic TaskView into TaskListView (handling GET /tasks for listing and POST /tasks for creation) and TaskDetailView (handling GET /tasks/{task_id} for retrieval).
- Updated URL configurations in to map to these new views, resolving previous Method Not Allowed errors and clarifying route responsibilities.
- Significantly enhanced the to provide consistent JSON structures for various error types.
- Ensured specific handling for (and s indicating invalid ID format), mapping them to HTTP 400 with a standardized error message ().
- Corrected logic to ensure objects consistently include a for generic exceptions.
- Streamlined error message usage from .
- Updated to explicitly raise when is encountered from the repository.
- Ensured pagination link generation in uses the correct URL name () via .
- Refined exception handling within service methods to use constants from .
- Consolidated error messages: removed and , relying on the primary messages ( and ).
- Removed an unnecessary docstring from as per review feedback.
- Updated all relevant unit and integration tests to reflect changes in view names, URL structures, error response formats, and constant usage.
- Ensured tests for invalid task IDs now correctly expect HTTP 400 and the standardized error message.
- Modified tests for the custom exception handler to align with its comprehensive error formatting.
- modifies to handle by raising a with the message . This results in a consistent HTTP 404 response when a task ID is malformed. - generic exception handler within has also been updated to raise . - Integration tests (): Updated to expect an HTTP 404 status and the revised error structure for invalid task ID formats. - Unit tests (): Updated to assert that is raised for invalid task ID formats.
|
@Achintya-Chatterjee can you please raise the API contract PR also |
|
@Achintya-Chatterjee can you please confirm if we are only returning the task which has isDeleted=false |
not in the current scope, it will be added after DELETE task API is live, and needs to be in two endpoints, get_task and get_task_by_id |
|
Date:
May 24, 2025Developer Name: @Achintya-Chatterjee
Issue Ticket Number
(GET /tasks/{task_id})#29Description
get_by_idmethod toTaskRepository.get_task_by_idmethod toTaskServicewith error handlingfor
TaskNotFoundExceptionand invalid ObjectId format.TaskViewto handle requests for a single task ID,returning 404 for not found and 400 for invalid ID format.
/tasks/<str:task_id>totodo/urls.py.GetTaskByIdResponseDTO for the response structure.TaskNotFoundExceptioncustom exception.PATHtoApiErrorSourceenum for error reporting.todo/constants/messages.py.DATABASESconfiguration totodo_project/settings/base.pyto ensure Django's test runneroperates correctly, resolving teardown errors.
service method, and view logic.
not found (404), and invalid ID format (400) scenarios.
Documentation Updated?
Under Feature Flag
Database Changes
Breaking Changes
Development Tested?
Screenshots
Screenshot 1
Screen.Recording.2025-05-24.at.00.30.17.mp4
400 Bad Request

404 Not Found

Test Coverage
Screenshot 1
Additional Notes