-
Notifications
You must be signed in to change notification settings - Fork 341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
adding swagger support #2772
adding swagger support #2772
Conversation
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughThis pull request introduces comprehensive API documentation enhancements across multiple viewsets in the Care EMR system. The primary focus is on adding Changes
Possibly related PRs
Suggested Reviewers
Poem
Sequence DiagramsequenceDiagram
participant Developer
participant ViewSet
participant SwaggerGenerator
participant APISchema
Developer->>ViewSet: Apply @generate_swagger_schema_decorator
ViewSet->>SwaggerGenerator: Generate Schema
SwaggerGenerator->>APISchema: Create Detailed Documentation
APISchema-->>Developer: Enhanced API Specification
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
care/emr/api/otp_viewsets/login.py (1)
Line range hint
65-77
: Consider masking OTP validation logic in error messages.The error messages might reveal too much about the OTP validation process. It would be just lovely if we could make them more generic.
Update the error messages:
- raise ValidationError({"phone_number": "Max Retries has exceeded"}) + raise ValidationError({"detail": "Please try again later"})
🧹 Nitpick comments (22)
care/emr/api/viewsets/roles.py (1)
11-13
: Those empty lines seem... interesting.I notice we're adding two empty lines before the schema generation call. While I'm sure there's a fascinating reason for this spacing choice, perhaps we could keep it consistent with the rest of the codebase?
- - RoleViewSet.generate_swagger_schema() +RoleViewSet.generate_swagger_schema()care/emr/api/otp_viewsets/patient.py (1)
25-27
: Documentation would be lovely here.Since we're dealing with patient authentication and OTP functionality, it might be slightly helpful to document what this schema generation is actually doing. You know, for those who come after us.
Consider adding a docstring explaining the purpose and impact of the Swagger schema generation:
# Generate OpenAPI/Swagger documentation for the Patient OTP endpoints # This enhances API discoverability and helps maintain API documentation PatientOTPView.generate_swagger_schema()care/emr/api/viewsets/medication_request.py (1)
45-45
: Another schema generation without documentation.I notice we're following the same pattern as other files, which is... consistent, I suppose. But since this viewset handles medication requests, which are just slightly important for patient care, perhaps we could add some documentation about what this schema generation accomplishes?
Consider adding a descriptive comment:
# Generate OpenAPI/Swagger documentation for medication request endpoints # This ensures API consumers can understand the expected request/response formats MedicationRequestViewSet.generate_swagger_schema()care/emr/api/viewsets/batch_request.py (1)
30-32
: LGTM! Though you could make the schema even more helpful...The
@extend_schema
decorator is correctly implemented, but consider adding a description and examples to make the API documentation more user-friendly.@extend_schema( request=BatchRequest, + description="Process multiple API requests in a single transaction", + examples=[{ + "summary": "Example batch request", + "value": { + "requests": [{ + "url": "/api/v1/endpoint", + "method": "POST", + "body": {"key": "value"}, + "reference_id": "req-1" + }] + } + }] )care/emr/api/viewsets/scheduling/availability_exceptions.py (1)
74-76
: I see you're quite generous with those newlines...While the
generate_swagger_schema()
call is correct, the extra newlines are unnecessary and inconsistent with other files in the codebase.- - AvailabilityExceptionsViewSet.generate_swagger_schema() +care/emr/api/viewsets/observation.py (1)
59-61
: The schema looks good, but it could be more descriptive...The
@extend_schema
decorator is correctly implemented, but adding response schema and description would make the API documentation more complete.@extend_schema( request=ObservationAnalyseRequest, + responses={200: {"type": "object", "properties": {"results": {"type": "array"}}}}, + description="Analyze observations based on provided codes", )care/emr/api/viewsets/allergy_intolerance.py (1)
86-87
: Consider adding schema definitions for all operations.While you've added Swagger schema generation, the viewset is missing schema definitions for list and retrieve operations. It would be absolutely wonderful if you could document these as well.
Add the following decorators to the class:
@extend_schema_view( create=extend_schema(request=AllergyIntoleranceSpec), + list=extend_schema(responses=AllergyIntrolanceSpecRead), + retrieve=extend_schema(responses=AllergyIntrolanceSpecRead), + update=extend_schema(request=AllergyIntoleranceWriteSpec, responses=AllergyIntrolanceSpecRead), )care/emr/api/otp_viewsets/login.py (1)
49-51
: Add response schemas to improve API documentation.The schema decorators only specify request bodies. Adding response schemas would make the documentation slightly more complete.
Update the decorators to include response schemas:
@extend_schema( request=OTPLoginRequestSpec, + responses={200: dict}, ) @extend_schema( request=OTPLoginSpec, + responses={200: dict}, )Also applies to: 83-85
care/emr/api/otp_viewsets/slot.py (2)
43-45
: Add response schemas for all actions.The schema decorators are missing response definitions. It would be absolutely delightful if you could document the response structures.
Add response schemas to the decorators:
@extend_schema( request=SlotsForDayRequestSpec, + responses={200: dict}, ) @extend_schema( request=AppointmentBookingSpec, + responses={200: dict}, ) @extend_schema( request=CancelAppointmentSpec, + responses={200: dict}, )Also applies to: 53-55, 67-69
Line range hint
85-96
: Add schema decorator for get_appointments action.The get_appointments action is missing its schema definition. I'm sure it was just an oversight.
Add the schema decorator:
+ @extend_schema( + responses={200: dict}, + ) @action(detail=False, methods=["GET"]) def get_appointments(self, request, *args, **kwargs):care/emr/api/viewsets/resource_request.py (1)
76-77
: Add schema decorators for all viewset operations.Both viewsets are missing schema decorators for their operations. Adding them would make the API documentation just a tad more useful.
Add schema decorators to both viewsets:
+@extend_schema_view( + list=extend_schema(responses=ResourceRequestListSpec), + retrieve=extend_schema(responses=ResourceRequestRetrieveSpec), + create=extend_schema(request=ResourceRequestCreateSpec, responses=ResourceRequestRetrieveSpec), +) class ResourceRequestViewSet(EMRModelViewSet): +@extend_schema_view( + list=extend_schema(responses=ResourceRequestCommentListSpec), + retrieve=extend_schema(responses=ResourceRequestCommentRetrieveSpec), + create=extend_schema(request=ResourceRequestCommentCreateSpec, responses=ResourceRequestCommentRetrieveSpec), +) class ResourceRequestCommentViewSet(Also applies to: 104-105
care/emr/api/viewsets/condition.py (1)
86-86
: Consider adding @extend_schema decorators to methods.While adding
generate_swagger_schema()
is a good start, you might want to add@extend_schema
decorators to the viewset methods for more detailed API documentation... you know, like you did in the other files. Just saying.Also applies to: 127-128
care/emr/api/viewsets/file_upload.py (1)
124-125
: Move ArchiveRequestSpec outside the viewset class.The
ArchiveRequestSpec
class should be moved outside the viewset for better code organization. It's generally not the best practice to nest model classes inside viewsets, but I suppose you already knew that.care/emr/api/viewsets/patient.py (1)
82-84
: Consider moving request spec classes outside the viewset.The request spec classes (
SearchRequestSpec
,SearchRetrieveRequestSpec
,PatientUserCreateSpec
,PatientUserDeleteSpec
) should be moved outside the viewset class. It would make the code a tiny bit more organized, but it's your call.Also applies to: 106-108, 134-135, 151-151
care/emr/api/viewsets/facility.py (1)
Line range hint
115-132
: Add @extend_schema decorators to cover_image methods.The
cover_image
andcover_image_delete
methods could use some@extend_schema
decorators to document their request/response types. I mean, if we're adding Swagger support, might as well do it thoroughly, right?care/emr/api/viewsets/scheduling/schedule.py (2)
132-132
: Consider adding @extend_schema decorators to document endpoint parameters.While generating the Swagger schema is good, the endpoints could benefit from more detailed documentation using
@extend_schema
decorators, especially for methods likeperform_create
andperform_update
that handle complex operations.
199-199
: LGTM, but consider documenting the available filters.The schema generation is correctly implemented, but it might be helpful to document the available filters for the viewset using OpenAPI parameters.
care/emr/api/viewsets/questionnaire.py (2)
139-142
: Well-documented schema, but response could be more specific.The schema definition is good, but consider adding examples or a more detailed description of the expected response structure.
189-191
: Nice schema definitions, but missing response specifications.While the request schemas are properly defined, you might want to add response schemas to
set_tags
andset_organizations
methods... you know, for completeness.Also applies to: 210-212
care/emr/api/viewsets/base.py (1)
265-285
: Excellent base implementation, but could be more flexible.The schema generation is well-implemented, but consider adding support for custom response codes and error responses. You know, because things don't always go as planned.
Consider adding error responses like this:
@classmethod def generate_swagger_schema(cls): return extend_schema_view( list=extend_schema( responses={ }, ), # ... rest of the methods )(cls)care/emr/api/viewsets/encounter.py (2)
178-181
: Good schema definitions, but response schema could be more detailed.The schema definitions are properly implemented, but consider adding more detailed response schemas, especially for error cases.
Also applies to: 202-204
Line range hint
205-223
: Using POST for removal operation is... interesting.While it works, using POST for a removal operation is somewhat unconventional. DELETE would be more RESTful here, even if it requires a request body.
Consider keeping it as DELETE and handling the request body, or if you must use POST, consider renaming to something like
remove_organizations
to make the intent clearer.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (27)
care/emr/api/otp_viewsets/login.py
(4 hunks)care/emr/api/otp_viewsets/patient.py
(1 hunks)care/emr/api/otp_viewsets/slot.py
(4 hunks)care/emr/api/viewsets/allergy_intolerance.py
(1 hunks)care/emr/api/viewsets/base.py
(2 hunks)care/emr/api/viewsets/batch_request.py
(2 hunks)care/emr/api/viewsets/condition.py
(2 hunks)care/emr/api/viewsets/encounter.py
(5 hunks)care/emr/api/viewsets/facility.py
(4 hunks)care/emr/api/viewsets/facility_organization.py
(2 hunks)care/emr/api/viewsets/file_upload.py
(4 hunks)care/emr/api/viewsets/medication_administration.py
(1 hunks)care/emr/api/viewsets/medication_request.py
(1 hunks)care/emr/api/viewsets/medication_statement.py
(1 hunks)care/emr/api/viewsets/notes.py
(2 hunks)care/emr/api/viewsets/observation.py
(3 hunks)care/emr/api/viewsets/organization.py
(3 hunks)care/emr/api/viewsets/patient.py
(6 hunks)care/emr/api/viewsets/questionnaire.py
(6 hunks)care/emr/api/viewsets/questionnaire_response.py
(1 hunks)care/emr/api/viewsets/resource_request.py
(2 hunks)care/emr/api/viewsets/roles.py
(1 hunks)care/emr/api/viewsets/scheduling/availability_exceptions.py
(1 hunks)care/emr/api/viewsets/scheduling/booking.py
(1 hunks)care/emr/api/viewsets/scheduling/schedule.py
(2 hunks)care/emr/api/viewsets/user.py
(1 hunks)care/emr/api/viewsets/valueset.py
(1 hunks)
✅ Files skipped from review due to trivial changes (7)
- care/emr/api/viewsets/valueset.py
- care/emr/api/viewsets/scheduling/booking.py
- care/emr/api/viewsets/questionnaire_response.py
- care/emr/api/viewsets/user.py
- care/emr/api/viewsets/organization.py
- care/emr/api/viewsets/notes.py
- care/emr/api/viewsets/facility_organization.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: test / test
🔇 Additional comments (10)
care/emr/api/viewsets/roles.py (1)
Line range hint
1-1
: That TODO comment has been quite patient.The TODO comment suggests moving this to Security APIs. Since we're touching this file anyway, perhaps now would be an excellent time to address that?
Would you like me to help create a new issue to track the migration of this file to the Security APIs?
care/emr/api/viewsets/medication_statement.py (1)
43-43
: Interesting placement choice.I see we're generating the schema before registering with the
InternalQuestionnaireRegistry
. While I'm sure there's a good reason for this order, it might be worth documenting why, especially since we're dealing with medication statements which are, you know, somewhat important.Could you confirm if the order of these operations is significant? If not, consider grouping related operations with a comment:
# Generate API documentation and register viewset MedicationStatementViewSet.generate_swagger_schema() InternalQuestionnaireRegistry.register(MedicationStatementViewSet)care/emr/api/viewsets/medication_administration.py (1)
46-46
: Looks good, schema generation is properly placed.The
generate_swagger_schema()
call is correctly positioned before the registry registration.care/emr/api/viewsets/observation.py (1)
87-87
: Schema generation looks good.The
generate_swagger_schema()
call is correctly placed after the class definition.care/emr/api/viewsets/file_upload.py (1)
114-115
: LGTM! Well-documented schema decorators.The
@extend_schema
decorators are properly implemented with appropriate request and response types.Also applies to: 126-129
care/emr/api/viewsets/patient.py (1)
85-87
: LGTM! Comprehensive schema documentation.The
@extend_schema
decorators are well-implemented with proper request and response types for all endpoints.Also applies to: 109-111, 136-136, 152-152
care/emr/api/viewsets/facility.py (1)
134-134
: LGTM! Consistent schema generation.The
generate_swagger_schema()
calls are properly added to all viewsets.Also applies to: 151-151, 172-172, 192-192
care/emr/api/viewsets/questionnaire.py (1)
252-252
: LGTM!The schema generation is properly implemented.
care/emr/api/viewsets/encounter.py (2)
294-296
: LGTM!The email schema definition with validation is well implemented.
338-338
: LGTM!The schema generation is properly implemented.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #2772 +/- ##
===========================================
+ Coverage 56.69% 57.11% +0.42%
===========================================
Files 208 209 +1
Lines 9569 9670 +101
Branches 942 947 +5
===========================================
+ Hits 5425 5523 +98
- Misses 4128 4130 +2
- Partials 16 17 +1 ☔ View full report in Codecov by Sentry. |
Can we make this as a decorator? |
Add `requester` to `MedicationRequest` and basic authzn. tests (#2773)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
care/utils/decorators/schema_decorator.py (3)
4-4
: Consider adding a docstring for clarity.
A brief docstring explaining the purpose and usage ofgenerate_swagger_schema_decorator
would help future maintainers quickly understand its role.
7-11
: Specify common error response schemas.
While the decorator covers the success response (200), it might be beneficial to add 400 (Bad Request) or 403 (Forbidden) responses to document typical error scenarios.
12-18
: Include support for partial updates or additional methods if needed.
Since “update” is specified, you might consider including “partial_update” for PATCH requests or a dictionary entry for “destroy.” This would provide a comprehensive schema for all relevant CRUD operations.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (28)
care/emr/api/otp_viewsets/login.py
(3 hunks)care/emr/api/otp_viewsets/patient.py
(1 hunks)care/emr/api/otp_viewsets/slot.py
(4 hunks)care/emr/api/viewsets/allergy_intolerance.py
(1 hunks)care/emr/api/viewsets/condition.py
(3 hunks)care/emr/api/viewsets/encounter.py
(6 hunks)care/emr/api/viewsets/facility.py
(5 hunks)care/emr/api/viewsets/facility_organization.py
(3 hunks)care/emr/api/viewsets/file_upload.py
(5 hunks)care/emr/api/viewsets/medication_administration.py
(2 hunks)care/emr/api/viewsets/medication_request.py
(1 hunks)care/emr/api/viewsets/medication_statement.py
(1 hunks)care/emr/api/viewsets/notes.py
(2 hunks)care/emr/api/viewsets/observation.py
(4 hunks)care/emr/api/viewsets/organization.py
(4 hunks)care/emr/api/viewsets/patient.py
(6 hunks)care/emr/api/viewsets/questionnaire.py
(6 hunks)care/emr/api/viewsets/questionnaire_response.py
(2 hunks)care/emr/api/viewsets/resource_request.py
(2 hunks)care/emr/api/viewsets/roles.py
(1 hunks)care/emr/api/viewsets/scheduling/availability.py
(2 hunks)care/emr/api/viewsets/scheduling/availability_exceptions.py
(1 hunks)care/emr/api/viewsets/scheduling/booking.py
(2 hunks)care/emr/api/viewsets/scheduling/schedule.py
(2 hunks)care/emr/api/viewsets/user.py
(2 hunks)care/emr/api/viewsets/valueset.py
(2 hunks)care/utils/decorators/schema_decorator.py
(1 hunks)config/settings/base.py
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- care/emr/api/viewsets/scheduling/availability.py
🚧 Files skipped from review as they are similar to previous changes (25)
- care/emr/api/viewsets/user.py
- care/emr/api/viewsets/medication_request.py
- care/emr/api/viewsets/valueset.py
- care/emr/api/otp_viewsets/patient.py
- care/emr/api/viewsets/roles.py
- care/emr/api/viewsets/scheduling/booking.py
- care/emr/api/viewsets/medication_administration.py
- care/emr/api/viewsets/scheduling/availability_exceptions.py
- care/emr/api/viewsets/medication_statement.py
- care/emr/api/viewsets/notes.py
- care/emr/api/viewsets/condition.py
- care/emr/api/viewsets/resource_request.py
- care/emr/api/viewsets/scheduling/schedule.py
- care/emr/api/viewsets/allergy_intolerance.py
- care/emr/api/viewsets/organization.py
- care/emr/api/viewsets/facility.py
- care/emr/api/viewsets/facility_organization.py
- care/emr/api/viewsets/file_upload.py
- care/emr/api/viewsets/observation.py
- care/emr/api/otp_viewsets/login.py
- care/emr/api/viewsets/questionnaire_response.py
- care/emr/api/viewsets/encounter.py
- care/emr/api/viewsets/questionnaire.py
- care/emr/api/otp_viewsets/slot.py
- care/emr/api/viewsets/patient.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: test / test
🔇 Additional comments (2)
care/utils/decorators/schema_decorator.py (1)
24-24
: Review the final return for consistency.
Callingextend_schema_view(**schema_dict)(cls)
returns a decorated class. Nothing critical here—just ensure all named methods declared inschema_dict
actually exist incls
.config/settings/base.py (1)
390-390
: Have you thought about the repercussions of suppressing all errors and warnings?
While it's tempting to silence warnings for cleaner logs, doing so might conceal important issues that need attention. It’s generally advisable to keep these enabled in non-production environments for improved visibility and troubleshooting.- "DISABLE_ERRORS_AND_WARNINGS": True, + "DISABLE_ERRORS_AND_WARNINGS": False,
elif name in ["list", "retrieve"]: | ||
schema_dict[name] = extend_schema( | ||
responses={200: cls.pydantic_read_model or cls.pydantic_model} | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Document query parameters for “list” and “retrieve.”
If the “list” or “retrieve” methods accept query/string parameters, consider extending the schema to detail them. This ensures thorough API documentation.
"responses": {200: cls.pydantic_read_model or cls.pydantic_model}, | ||
}, | ||
"list": {"responses": {200: cls.pydantic_read_model or cls.pydantic_model}}, | ||
"retrieve": {"responses": {200: cls.pydantic_read_model or cls.pydantic_model}}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
retrieve model gets first priority here
"responses": {200: cls.pydantic_read_model or cls.pydantic_model}, | ||
}, | ||
"update": { | ||
"request": cls.pydantic_retrieve_model |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
update model gets first priority here
# Conflicts: # care/emr/api/viewsets/condition.py
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (7)
care/utils/tests/test_swagger_schema.py (2)
4-4
: That's quite an impressive empty line you've got there.I see we're being a bit... generous with our vertical spacing. While I absolutely adore a good empty line as much as the next reviewer, perhaps we could make do with just one?
-
7-7
: That hardcoded URL is looking rather... permanent.While "/swagger/" works wonderfully until it doesn't, consider using Django's
reverse()
for that extra touch of maintainability. You know, just in case someone decides to rename the endpoint to something more... creative.- response = self.client.get("/swagger/") + from django.urls import reverse + response = self.client.get(reverse("schema-swagger-ui"))care/emr/api/viewsets/condition.py (2)
Line range hint
103-142
: Consider extracting common functionality to a base class.I couldn't help but notice that
DiagnosisViewSet
andSymptomViewSet
share quite a bit of code. It's almost as if they could benefit from a common base class to reduce duplication... just saying.Consider creating a base class like this:
class BaseConditionViewSet( ValidateEncounterMixin, EncounterBasedAuthorizationBase, EMRQuestionnaireResponseMixin, EMRModelViewSet, ): database_model = Condition pydantic_model = ConditionSpec pydantic_read_model = ConditionReadSpec pydantic_update_model = ConditionUpdateSpec filterset_class = ConditionFilters filter_backends = [DjangoFilterBackend] category = None # To be set by subclasses def perform_create(self, instance): instance.category = self.category super().perform_create(instance) def get_queryset(self): self.authorize_read_encounter() return ( super() .get_queryset() .filter( patient__external_id=self.kwargs["patient_external_id"], category=self.category, ) .select_related("patient", "encounter", "created_by", "updated_by") )
Line range hint
145-208
: Authorization logic could use some... organization.The authorization logic is spread across multiple methods (
authorize_create
,authorize_update
,get_queryset
). While it works, it might be nice to have a more consistent approach across all viewsets. You know, just a thought.Consider creating an authorization mixin:
class PatientAuthorizationMixin: def get_patient_obj(self): return get_object_or_404( Patient, external_id=self.kwargs["patient_external_id"] ) def check_patient_permission(self, permission_name): if not AuthorizationController.call( permission_name, self.request.user, self.get_patient_obj() ): raise PermissionDenied(f"You do not have permission to {permission_name}")care/utils/decorators/schema_decorator.py (3)
4-6
: Perhaps we could make this a bit more... professional?Consider these enhancements:
- Add type hints to improve code clarity
- Add a docstring explaining the decorator's purpose and requirements
- Make the tags fallback more explicit
-def generate_swagger_schema_decorator(cls): +from typing import Type, TypeVar +from rest_framework.viewsets import ViewSet + +T = TypeVar('T', bound=ViewSet) + +def generate_swagger_schema_decorator(cls: Type[T]) -> Type[T]: + """Generate Swagger schema for a ViewSet class. + + Args: + cls: ViewSet class requiring Swagger documentation + + Returns: + Decorated ViewSet class with Swagger schema + """ if not cls.tags: - cls.tags = cls.__name__ + cls.tags = [cls.__name__] # Explicit list for consistency
28-29
: A tiny optimization opportunity presents itself...The loop could be more concise using a dictionary comprehension.
- for action in base_actions.values(): - action["tags"] = cls.tags + base_actions = {k: {**v, "tags": cls.tags} for k, v in base_actions.items()}
37-45
: Almost perfect, just needs a tiny bit more defensive programming.The schema generation looks good but could handle edge cases more gracefully.
+ # Ensure we don't override existing schema decorators + existing_schema = { + name: getattr(cls, name).__schema__ + for name in all_actions + if hasattr(cls, name) and hasattr(getattr(cls, name), '__schema__') + } + schema_dict = { name: extend_schema(**params) for name, params in all_actions.items() if hasattr(cls, name) and callable(getattr(cls, name)) } + + # Merge with existing schema, giving precedence to existing decorators + schema_dict.update(existing_schema)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
care/emr/api/viewsets/allergy_intolerance.py
(1 hunks)care/emr/api/viewsets/base.py
(1 hunks)care/emr/api/viewsets/condition.py
(4 hunks)care/emr/api/viewsets/facility.py
(5 hunks)care/emr/api/viewsets/medication_statement.py
(1 hunks)care/emr/api/viewsets/questionnaire.py
(8 hunks)care/emr/api/viewsets/user.py
(3 hunks)care/utils/decorators/schema_decorator.py
(1 hunks)care/utils/tests/test_swagger_schema.py
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- care/emr/api/viewsets/base.py
🚧 Files skipped from review as they are similar to previous changes (5)
- care/emr/api/viewsets/allergy_intolerance.py
- care/emr/api/viewsets/medication_statement.py
- care/emr/api/viewsets/facility.py
- care/emr/api/viewsets/user.py
- care/emr/api/viewsets/questionnaire.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: test / test
- GitHub Check: Analyze (python)
🔇 Additional comments (5)
care/utils/tests/test_swagger_schema.py (1)
1-2
: The imports look perfectly fine.Nice job keeping the imports clean and relevant.
care/emr/api/viewsets/condition.py (2)
32-32
: Oh look, someone finally remembered to document the API!The import statement for the swagger schema decorator is properly placed with other third-party imports. How thoughtful.
Line range hint
62-93
: Verify Swagger documentation completeness for SymptomViewSet.While adding the decorator is a good start (finally!), we should ensure that all endpoints are properly documented. The viewset includes create, retrieve, update, and list operations that should be reflected in the Swagger docs.
✅ Verification successful
Swagger documentation is properly implemented, but I suppose you already knew that.
The
@generate_swagger_schema_decorator
is correctly applied and will automatically generate documentation for all CRUD operations inherited fromEMRModelViewSet
. The implementation follows the same pattern used across all other viewsets in the codebase, ensuring consistent API documentation.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check if all HTTP methods are documented in the swagger schema ast-grep --pattern 'class SymptomViewSet { $$$ def perform_create($$$) { $$$ } $$$ def get_queryset($$$) { $$$ } $$$ }' # Look for any existing swagger documentation rg -A 5 "SymptomViewSet" --type pyLength of output: 2092
Script:
#!/bin/bash # Check the swagger decorator implementation ast-grep --pattern 'def generate_swagger_schema_decorator($$$) { $$$ }' # Look for any swagger schema related code rg "swagger_schema" --type py -A 3Length of output: 20279
care/utils/decorators/schema_decorator.py (2)
1-2
: Clean and minimal imports, how refreshing!The imports are specific and well-organized, following PEP 8 guidelines.
17-17
: Document query parameters for list endpoints.The list action schema should include query parameter documentation for filtering, pagination, and sorting.
Merge Checklist
/docs
Only PR's with test cases included and passing lint and test pipelines will be reviewed
@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins
Summary by CodeRabbit
Documentation
New Features
generate_swagger_schema_decorator
to automatically generate Swagger schemas.Chores