Skip to content
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

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from

Conversation

DraKen0009
Copy link
Contributor

@DraKen0009 DraKen0009 commented Jan 22, 2025

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

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

    • Enhanced API documentation with Swagger schema generation across multiple view sets
    • Added schema decorators to improve request and response specifications for various API endpoints
  • Chores

    • Systematically added generate_swagger_schema() method calls to numerous view sets to improve API documentation capabilities
    • Introduced request and response schema specifications using @extend_schema decorators

The changes focus on improving API documentation and schema generation across the project's view sets, providing more detailed and structured API specifications without altering core functionality.

@DraKen0009 DraKen0009 requested a review from a team as a code owner January 22, 2025 14:10
Copy link

coderabbitai bot commented Jan 22, 2025

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive enhancements to API documentation across multiple viewsets in the EMR system. The changes primarily focus on leveraging the drf_spectacular library to generate more detailed Swagger schemas, adding @extend_schema decorators, and introducing generate_swagger_schema() methods. These modifications aim to improve API documentation clarity and provide more precise request/response specifications without altering the underlying functionality of existing methods.

Changes

File Path Change Summary
care/emr/api/otp_viewsets/* Added @extend_schema decorators and generate_swagger_schema() calls to login, patient, and slot-related viewsets
care/emr/api/viewsets/base.py Introduced a new class method generate_swagger_schema for dynamic schema extension
care/emr/api/viewsets/encounter.py Updated HTTP method for organizations_remove, added schema decorators and generate_swagger_schema()
Multiple viewset files Added generate_swagger_schema() method calls for various view sets like Patient, Questionnaire, Organization, etc.

Poem

🌟 Swagger schemas dancing bright,
Code documentation taking flight
With decorators precise and clean
Our API's now more clearly seen
Documentation's poetic might! 📘✨

Possibly related PRs

Suggested Reviewers

  • vigneshhari

I mean, who wouldn't want to review such a meticulously crafted documentation enhancement? 😏 Just a tiny bit of swagger in our schemas, if you know what I mean.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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 and cover_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 like perform_create and perform_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 and set_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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f59824 and 58a9987.

📒 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.

Copy link

codecov bot commented Jan 22, 2025

Codecov Report

Attention: Patch coverage is 98.52941% with 1 line in your changes missing coverage. Please review.

Project coverage is 64.93%. Comparing base (2f59824) to head (00550df).

Files with missing lines Patch % Lines
care/emr/api/viewsets/encounter.py 83.33% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2772      +/-   ##
===========================================
+ Coverage    64.74%   64.93%   +0.18%     
===========================================
  Files          252      252              
  Lines        12743    12809      +66     
  Branches      1119     1119              
===========================================
+ Hits          8251     8317      +66     
  Misses        4384     4384              
  Partials       108      108              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@vigneshhari
Copy link
Member

Can we make this as a decorator?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants