### Quick Start Guide for Custom Data SDK Source: https://docs.canvasmedical.com/release-notes/1-292-0 This snippet is a placeholder for the Quick Start guide. Refer to the guide for instructions on how to begin experimenting with the Custom Data SDK. ```text To start experimenting, see the Quick Start guide, and update the `canvas` CLI tool for latest functionality. ``` -------------------------------- ### Install Canvas Plugin Source: https://docs.canvasmedical.com/guides/note-management-oauth Installs the note management app plugin using the Canvas CLI. Replace YOUR_CLIENT_ID with the actual client ID obtained from Canvas OAuth application setup. ```bash canvas install note_management_app/note_management_app --secret client_id= ``` -------------------------------- ### Install Canvas Application Source: https://docs.canvasmedical.com/guides/your-first-application Use the canvas install command followed by the path to your application directory to install it. ```bash canvas install ``` -------------------------------- ### GET /routes/hello-world Source: https://docs.canvasmedical.com/sdk/handlers-simple-api-http Handles GET requests to the /routes/hello-world endpoint, returning an HTML response. ```APIDOC ## GET /routes/hello-world ### Description Handles GET requests to the /routes/hello-world endpoint, returning an HTML response. ### Method GET ### Endpoint /routes/hello-world ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200 OK) - **content** (string) - The HTML content of the response. - **headers** (object) - Headers to be included in the response. #### Response Example ```json { "content": "

Hello world from my GET endpoint!

", "status_code": 200, "headers": {"My-Header": "my header value"} } ``` ``` -------------------------------- ### Install lab-sync Plugin Source: https://docs.canvasmedical.com/guides/using-attribute-hubs-for-plugin-state Install the lab-sync plugin using the canvas CLI. Replace YOUR_INSTANCE with your actual instance host. ```bash canvas install lab-sync --host YOUR_INSTANCE ``` -------------------------------- ### SimpleAPIRoute Example Source: https://docs.canvasmedical.com/sdk/handlers-simple-api-http This example demonstrates how to define GET and POST endpoints using the SimpleAPIRoute handler. The PATH class variable defines the endpoint's route, and methods named after HTTP verbs (e.g., `get`, `post`) implement the endpoint logic. ```APIDOC ## GET /routes/hello-world ### Description Handles GET requests to the /routes/hello-world endpoint. ### Method GET ### Endpoint /routes/hello-world ### Request Body None ### Response #### Success Response (200) - **message** (string) - A greeting message. ### Request Example None ### Response Example ```json { "message": "Hello world from my GET endpoint!" } ``` ## POST /routes/hello-world ### Description Handles POST requests to the /routes/hello-world endpoint. ### Method POST ### Endpoint /routes/hello-world ### Request Body None ### Response #### Success Response (200) - **message** (string) - A greeting message. ### Request Example None ### Response Example ```json { "message": "Hello world from my POST endpoint!" } ``` ``` -------------------------------- ### Initialize and Use ReviewOfSystemsCommand Source: https://docs.canvasmedical.com/sdk/commands Demonstrates how to create a ReviewOfSystemsCommand instance, retrieve questions, check question enablement, disable questions, and view all toggle states. Toggle states are preserved when working with existing commands. ```python from canvas_sdk.commands import ReviewOfSystemsCommand # Create a new review of systems ros = ReviewOfSystemsCommand( note_uuid='8a18931a-acd9-474b-9070-ccd6fd472313', questionnaire_id='ed92577b-a023-4370-bc85-2b57e8afc4d8', ) questions = ros.questions # Retrieve the list of questions # Returns: [ # Question( # self.name='question-14', # self.label='Recurrent fever or chills', # self.type='TXT', # self.options=[]], # self.response=None # ), # Question( # self.name='question-25', # self.label='Other', # self.type='TXT', self.options=[], # self.response=None # ) # Check if a question is enabled if ros.is_question_enabled("14"): print("Recurrent fever or chills question is enabled.") # Disable irrelevant questions ros.set_question_enabled("25", False) # Get all toggle states states = ros.question_toggles # Returns: {"14": True, "25": False, "26": True, ...}, where keys are question IDs and values are enabled states. # Working with existing ros - toggle states are preserved existing_ros = ReviewOfSystemsCommand(command_uuid='existing-exam-uuid') # All previously set toggle states are automatically loaded ``` -------------------------------- ### Example Appointment Resource Source: https://docs.canvasmedical.com/api/appointment This is an example of a FHIR Appointment resource. It includes details such as status, type, reason, supporting information, start and end times, and participant information. ```json { "resourceType": "Appointment", "id": "621a66fc-9d5c-4de0-97fb-935d611ac176", "contained": [ { "resourceType": "Endpoint", "id": "appointment-meeting-endpoint-0", "status": "active", "connectionType": { "code": "https" }, "payloadType": [ { "coding": [ { "code": "video-call" } ] } ], "address": "https://url-for-video-chat.example.com?meeting=abc123" } ], "extension": [ { "url": "http://schemas.canvasmedical.com/fhir/extensions/note-id", "valueId": "2a8154d8-9420-4ab5-97f8-c2dae5a10af5" } ], "identifier": [ { "id": "97b28298-f618-4972-9a6b-d095785587d6", "use": "usual", "system": "AssigningSystem", "value": "test123", "period": { "start": "2024-01-01", "end": "2024-12-31" } } ], "status": "proposed", "appointmentType": { "coding": [ { "system": "http://snomed.info/sct", "code": "448337001", "display": "Telemedicine" } ] }, "reasonCode": [ { "coding": [ { "system": "INTERNAL", "code": "INIV", "display": "Initial Visit", "userSelected": false } ], "text": "Initial 30 Minute Visit" } ], "description": "Initial 30 Minute Visit", "supportingInformation": [ { "reference": "Location/b3476a18-3f63-422d-87e7-b3dc0cd55060", "type": "Location" }, { "reference": "#appointment-meeting-endpoint-0", "type": "Endpoint" }, { "reference": "Encounter/23668e1a-e914-4eac-885c-1a2a27244ab7", "type": "Encounter" }, { "reference": "Appointment/7fa2874e-73c8-418d-bb25-eea0ccac651c", "type": "Appointment", "display": "Co-scheduled appointment" } ], "start": "2023-10-24T13:30:00+00:00", "end": "2023-10-24T14:00:00+00:00", "participant": [ { "actor": { "reference": "Practitioner/4150cd20de8a470aa570a852859ac87e", "type": "Practitioner" }, "status": "accepted" }, { "actor": { "reference": "Patient/ee1c7803325b47b492008f3e7c9d7a3d", "type": "Patient" }, "status": "accepted" } ] } ``` -------------------------------- ### Initialize a New Application Source: https://docs.canvasmedical.com/guides/your-first-application Run this command to create a new application boilerplate and a CANVAS_MANIFEST.json file. ```bash canvas init application ``` -------------------------------- ### Get Practitioner by ID (cURL) Source: https://docs.canvasmedical.com/api/practitioner Example of retrieving a Practitioner resource by its ID using cURL. ```bash curl --request GET \ --url 'https://fumage-example.canvasmedical.com/Practitioner/' \ --header 'Authorization: Bearer ' \ --header 'accept: application/json' \ ``` -------------------------------- ### Create and Apply a Protocol Card with Recommendations and Commands Source: https://docs.canvasmedical.com/sdk/effect-protocol-cards Demonstrates how to instantiate a ProtocolCard, add various types of recommendations (simple text, commands, and mixed), and apply it within a custom handler. This is useful for defining patient-specific care pathways. ```python from canvas_sdk.events import EventType from canvas_sdk.handlers import BaseHandler from datetime import date from canvas_sdk.effects.protocol_card import ProtocolCard, Recommendation from canvas_sdk.commands import DiagnoseCommand, PlanCommand class MyHandler(BaseHandler): RESPONDS_TO = EventType.Name(EventType.PATIENT_UPDATED) def compute(self): diagnose = DiagnoseCommand( icd10_code="I10", background="feeling bad for many years", approximate_date_of_onset=date(2020, 1, 1), today_assessment="still not great", ) plan = PlanCommand( narrative="Follow up in 2 weeks", ) p = ProtocolCard( patient_id=self.target, key="testing-protocol-cards", title="This is a ProtocolCard title", narrative="this is the narrative", status=ProtocolCard.Status.DUE, recommendations=[ Recommendation(title="this recommendation has no action, just words!"), Recommendation(title="this recommendation inserts multiple commands", button="add commands", commands=[diagnose, plan]) ], ) p.add_recommendation( title="this is a recommendation", button="go here", href="https://canvasmedical.com/" ) p.recommendations.append(diagnose.recommend(title="this inserts a diagnose command")) p.recommendations.append(title="new recommendation", button="start", commands=[diagnose]) return [p.apply()] ``` -------------------------------- ### Install Plugin with Secrets Source: https://docs.canvasmedical.com/guides/using-attribute-hubs-for-plugin-state Install the plugin, providing the instance host and securely passing secrets as arguments. Use the `--secret` flag for sensitive information. ```bash canvas install lab-sync \ --host YOUR_INSTANCE \ --secret LAB_VENDOR_API_KEY=your-api-key \ --secret LAB_VENDOR_BASE_URL=https://api.labvendor.example.com/v1 ``` -------------------------------- ### Get Upcoming Events for a Calendar Source: https://docs.canvasmedical.com/sdk/data-calendar Retrieves all upcoming and non-cancelled events for a calendar, ordered by start time. ```APIDOC ## Get Upcoming Events for a Calendar ### Description Retrieves all upcoming events for a calendar that have not been cancelled, ordered by their start time. ### Method GET (assumed from SDK usage) ### Endpoint `/api/v1/data/calendar/{id}/events` (inferred) ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the calendar. #### Query Parameters - **starts_at__gte** (DateTime) - Required - Filter for events starting on or after the current date and time. - **is_cancelled** (Boolean) - Required - Filter for events that are not cancelled (set to `false`). ### Response #### Success Response (200) - **Event[]** (array) - A list of upcoming, non-cancelled events. ### Request Example ```python from canvas_sdk.v1.data.calendar import Calendar from datetime import datetime from logger import log calendar = Calendar.objects.get(id="f53626e4-0683-43ac-a1b7-c52815639ce2") upcoming_events = calendar.events.filter( starts_at__gte=datetime.now(), is_cancelled=False ).order_by('starts_at') for event in upcoming_events: log.info(f"Event: {event.title}") log.info(f"Starts at: {event.starts_at}") log.info(f"Ends at: {event.ends_at}") if event.recurrence: log.info(f"Recurrence: {event.recurrence}") ``` ``` -------------------------------- ### Get Homepage Configuration Event Source: https://docs.canvasmedical.com/sdk/events Occurs when the Homepage is loading. See Set default homepage for examples of how to use this event. ```string GET_HOMEPAGE_CONFIGURATION ``` -------------------------------- ### Initialize Google (Gemini) Client Source: https://docs.canvasmedical.com/sdk/clients-llms Create an LlmGoogle client for Gemini models. Provide your Google API key, specify the model, and set the temperature. ```python from canvas_sdk.clients.llms import LlmGoogle from canvas_sdk.clients.llms.structures.settings import LlmSettingsGemini client = LlmGoogle(LlmSettingsGemini( api_key="your_google_api_key", model="models/gemini-2.0-flash", temperature=0.7, )) ``` -------------------------------- ### Retrieve Communications by Recipient (cURL) Source: https://docs.canvasmedical.com/api/communication Example of retrieving Communication resources filtered by a specific recipient using a cURL GET request. ```curl curl --request GET \ --url 'https://fumage-example.canvasmedical.com/Communication?recipient=Patient/b3084f7e884e4af2b7e23b1dca494abd' \ --header 'Authorization: Bearer ' \ --header 'accept: application/json' ``` -------------------------------- ### Originate a New Plan Command Source: https://docs.canvasmedical.com/sdk/commands Demonstrates how to instantiate a PlanCommand and then originate it. The narrative can be updated before originating. ```python from canvas_sdk.commands import PlanCommand def compute(): new_plan = PlanCommand(note_uuid='rk786p', narrative='new') new_plan.narrative = 'newer' return [new_plan.originate()] ``` -------------------------------- ### Initialize New Plugin with Canvas CLI Source: https://docs.canvasmedical.com/guides/tailoring-the-chart-to-the-patient Use the Canvas CLI to quickly set up a new plugin project. This command prompts for a project name and creates the necessary directory structure. ```bash $ canvas init [1/1] project_name (My Cool Plugin): Pediatric Patient Chart Customizations Project created in /Users/andrew/src/canvas-plugins/pediatric-patient-chart-customizations ``` -------------------------------- ### Successful Provenance Resource Response Source: https://docs.canvasmedical.com/api/provenance Example of a successful Provenance resource response, typically returned when a GET request for a specific Provenance ID is successful. ```json { "resourceType": "Provenance", "id": "db1631ed-bcd3-4e43-84a1-7e507e8aa44c", "target": [ { "reference": "Patient/b8dfa97bdcdf4754bcd8197ca78ef0f0", "type": "Patient" } ], "recorded": "2023-09-18T14:42:14.981528+00:00", "activity": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/v3-DataOperation", "code": "CREATE" } ] }, "agent": [ { "type": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/provenance-participant-type", "code": "composer", "display": "Composer" } ] }, "who": { "reference": "Organization/00000000-0000-0000-0002-000000000000", "type": "Organization", "display": "Canvas Medical" }, "onBehalfOf": { "reference": "Organization/00000000-0000-0000-0002-000000000000", "type": "Organization" } } ] } ``` -------------------------------- ### ServiceProvider Usage Example Source: https://docs.canvasmedical.com/sdk/commands Illustrates how to create a `ServiceProvider` object with detailed information for use in referral commands. This includes names, specialty, practice details, and contact information. ```python from canvas_sdk.commands import ReferCommand from canvas_sdk.commands.constants import ServiceProvider # Creating a referral with service provider information service_provider = ServiceProvider( first_name="John", last_name="Smith", specialty="Cardiology", practice_name="Heart Health Center", business_phone="555-0123", business_address="123 Medical Plaza, Suite 100" ) refer = ReferCommand( note_uuid="rk786p", diagnosis_codes=["E119"], priority=ReferCommand.Priority.ROUTINE, clinical_question=ReferCommand.ClinicalQuestion.DIAGNOSTIC_UNCERTAINTY, notes_to_specialist="Patient needs cardiac evaluation", service_provider=service_provider ) ``` -------------------------------- ### Get Upcoming and Uncancelled Events Source: https://docs.canvasmedical.com/sdk/data-calendar Retrieves all upcoming events for a calendar that have not been cancelled, ordered by their start time. This snippet demonstrates filtering and ordering of events. ```python from canvas_sdk.v1.data.calendar import Calendar from datetime import datetime from logger import log calendar = Calendar.objects.get(id="f53626e4-0683-43ac-a1b7-c52815639ce2") # Get all upcoming events upcoming_events = calendar.events.filter( starts_at__gte=datetime.now(), is_cancelled=False ).order_by('starts_at') for event in upcoming_events: log.info(f"Event: {event.title}") log.info(f"Starts at: {event.starts_at}") log.info(f"Ends at: {event.ends_at}") if event.recurrence: log.info(f"Recurrence: {event.recurrence}") ``` -------------------------------- ### Initialize a new plugin Source: https://docs.canvasmedical.com/guides/custom-landing-page Use the Canvas CLI to initialize a new plugin project. Follow the prompts to name and configure your project. ```bash canvas init ``` -------------------------------- ### Patient Metadata Get Additional Fields Event Source: https://docs.canvasmedical.com/sdk/events Occurs when the Patient Profile is loading. See How to add patient profile additional fields for examples of how to use this event. ```string PATIENT_METADATA__GET_ADDITIONAL_FIELDS ``` -------------------------------- ### GET Patient Request (cURL) Source: https://docs.canvasmedical.com/api/patient Example of fetching a specific patient resource using cURL. Replace `` with the actual patient ID and `` with your authentication token. ```curl curl --request GET \ --url 'https://fumage-example.canvasmedical.com/Patient/' \ --header 'Authorization: Bearer ' \ --header 'accept: application/json' \ --header 'Content-Type: application/json' ``` -------------------------------- ### Example Authorization URL Source: https://docs.canvasmedical.com/api/customer-authentication An example of a complete authorization URL, including encoded scopes and launch context. ```shell {YOUR_CANVAS_EHR_INSTANCE}/auth/authorize/?response_type=code&client_id={CLIENT_ID}&scope=user%2F*.read%20user%2F*.write&redirect_uri=https://your-app.com/callback&launch=eyJwYXRpZW50IjoiIn0= ``` -------------------------------- ### GET /hello-world Source: https://docs.canvasmedical.com/sdk/example-api_samples Responds with a simple JSON message 'Hello world!'. This endpoint is used as a basic example of an API interaction and requires authentication via an API key. ```APIDOC ## GET /hello-world ### Description Provides a simple "Hello world!" JSON message. This endpoint serves as a basic example and requires authentication. ### Method GET ### Endpoint /hello-world ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Headers - **Authorization** (string) - Required - API key matching the plugin secret 'my-api-key'. ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello world!" } ``` ``` -------------------------------- ### Navigate to Project Directory Source: https://docs.canvasmedical.com/guides/using-attribute-hubs-for-plugin-state Change the current directory to the newly created plugin project folder. ```bash cd lab-sync ``` -------------------------------- ### Retrieve Goals for a Patient Source: https://docs.canvasmedical.com/api/goal This snippet shows how to fetch all Goal resources associated with a specific patient using a GET request. It includes example requests in both cURL and Python. ```APIDOC ## GET /Goal ### Description Retrieves a list of Goal resources for a specified patient. ### Method GET ### Endpoint /Goal ### Parameters #### Query Parameters - **patient** (string) - Required - The reference to the patient for whom to retrieve goals (e.g., 'Patient/f3d750f5d77d403c96baef6a6055c6e7'). ### Request Example #### cURL ```curl curl --request GET \ --url 'https://fumage-example.canvasmedical.com/Goal?patient=Patient/f3d750f5d77d403c96baef6a6055c6e7' \ --header 'Authorization: Bearer ' \ --header 'accept: application/json' ``` #### Python ```python import requests url = "https://fumage-example.canvasmedical.com/Goal?patient=Patient/f3d750f5d77d403c96baef6a6055c6e7" headers = { "accept": "application/json", "Authorization": "Bearer " } response = requests.get(url, headers=headers) print(response.text) ``` ### Response #### Success Response (200) Returns a Goal resource if found. #### Response Example ```json { "resourceType": "Goal", "id": "e04a62f8-e6ab-46a1-af34-b635f901e37b", "lifecycleStatus": "active", "achievementStatus": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/goal-achievement", "code": "improving", "display": "Improving" } ] }, "priority": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/goal-priority", "code": "medium-priority", "display": "Medium Priority" } ] }, "description": { "text": "Drink more water" }, "subject": { "reference": "Patient/f3d750f5d77d403c96baef6a6055c6e7", "type": "Patient" }, "startDate": "2022-01-27", "target": [ { "dueDate": "2023-09-28" } ], "expressedBy": { "reference": "Practitioner/4150cd20de8a470aa570a852859ac87e", "type": "Practitioner" }, "note": [ { "id": "c2a45d52-b3d7-4e57-bb70-2b82b8819305", "authorReference": { "reference": "Practitioner/4150cd20de8a470aa570a852859ac87e", "type": "Practitioner" }, "time": "2023-09-19T20:50:25.955348+00:00", "text": "Patient unable to find time to drink during work hours, shows signs of dehydration and fatigue" } ] } ``` ### Error Handling - **400 Bad Request**: Indicates an invalid request, potentially due to malformed parameters. - **401 Unauthorized**: Authentication failed. The provided token is invalid or missing. - **403 Forbidden**: Authorization failed. The user does not have permission to access the requested resource. - **404 Not Found**: The specified Goal resource could not be found. ``` -------------------------------- ### Initiate Single Patient Export via API Source: https://docs.canvasmedical.com/documentation/ehi-export Use this GET request to start an export for a specific patient's EHI. Replace `` and `` with your specific details. ```http GET https://fumage-.canvasmedical.com/Patient//$export ``` -------------------------------- ### Initialize Plugin Project Source: https://docs.canvasmedical.com/guides/using-attribute-hubs-for-plugin-state Use the `canvas init` command to create a new plugin project. You will be prompted to enter a project name. ```bash $ canvas init [1/1] project_name (My Cool Plugin): Lab Sync Project created in /Users/you/lab-sync ``` -------------------------------- ### Initialize OpenAI (GPT) Client Source: https://docs.canvasmedical.com/sdk/clients-llms Instantiate an LlmOpenai client with GPT-4o model settings. Ensure your OpenAI API key is provided. ```python from canvas_sdk.clients.llms import LlmOpenai from canvas_sdk.clients.llms.structures.settings import LlmSettingsGpt4 client = LlmOpenai(LlmSettingsGpt4( api_key="your_openai_api_key", model="gpt-4o", temperature=0.7, )) ``` -------------------------------- ### Retrieve Communications by Recipient (Python) Source: https://docs.canvasmedical.com/api/communication Example of retrieving Communication resources filtered by a specific recipient using Python's requests library. This script sends a GET request to the API. ```python import requests url = "https://fumage-example.canvasmedical.com/Communication?recipient=Patient/b3084f7e884e4af2b7e23b1dca494abd" headers = { "accept": "application/json", "Authorization": "Bearer " } response = requests.get(url, headers=headers) print(response.text) ``` -------------------------------- ### Install canvas[test-utils] with uv Source: https://docs.canvasmedical.com/sdk/testing-utils Install the 'canvas[test-utils]' package directly using the uv command-line tool. ```bash uv add "canvas[test-utils]" ``` -------------------------------- ### Defining SimpleAPI Endpoint Handlers Source: https://docs.canvasmedical.com/sdk/handlers-simple-api-http Example of a SimpleAPI route handler defining GET, POST, PUT, and PATCH methods, each returning a different response type with custom status codes and headers. ```python from http import HTTPStatus from canvas_sdk.effects import Effect from canvas_sdk.effects.simple_api import HTMLResponse, JSONResponse, PlainTextResponse, Response from canvas_sdk.handlers.simple_api import APIKeyCredentials, SimpleAPIRoute class MyAPI(SimpleAPIRoute): PATH = "/routes/hello-world" def authenticate(self, credentials: APIKeyCredentials) -> bool: ... def get(self) -> list[Response | Effect]: return [ HTMLResponse( "

Hello world from my GET endpoint!

", status_code=HTTPStatus.OK, headers={"My-Header", "my header value"} ) ] def post(self) -> list[Response | Effect]: return [ JSONResponse( {"message": "Hello world from my POST endpoint!"}, status_code=HTTPStatus.CREATED, headers={"My-Header", "my header value"} ) ] def put(self) -> list[Response | Effect]: return [ PlainTextResponse( "Hello world from my PUT endpoint!", status_code=HTTPStatus.ACCEPTED, headers={"My-Header", "my header value"} ) ] def patch(self) -> list[Response | Effect]: return [ Response( b'{"message": "Hello world from my PATCH endpoint!"}', status_code=HTTPStatus.NOT_MODIFIED, headers={"My-Header", "my header value"}, content_type="application/json" ) ] ``` -------------------------------- ### GET Patient Request (Python) Source: https://docs.canvasmedical.com/api/patient Example of fetching a specific patient resource using Python's requests library. Ensure you replace `` with the patient ID and `` with your authentication token. ```python import requests url = "https://fumage-example.canvasmedical.com/Patient/" headers = { "accept": "application/json", "Authorization": "Bearer ", "Content-Type": "application/json" } response = requests.get(url, headers=headers) print(response.text) ``` -------------------------------- ### PlanCommand Example Source: https://docs.canvasmedical.com/sdk/commands This snippet demonstrates how to create a plan for a patient using the PlanCommand. It requires a narrative and optionally accepts a note UUID. ```python from canvas_sdk.commands import PlanCommand plan = PlanCommand( note_uuid='rk786p', narrative='will return in 2 weeks to check on pain management' ) ``` -------------------------------- ### Filter Active Billing Line Items by CPT Code and Order by Charge Source: https://docs.canvasmedical.com/sdk/data-billing-line-item This example demonstrates filtering a patient's active billing line items to find those starting with '99-' and ordering them by charge amount in descending order. ```APIDOC ## Filter Active Billing Line Items by CPT Code and Order by Charge ### Description Finds a patient's active billing line items with CPT codes starting with '99-' and sorts them by charge amount in descending order. ### Method ```python patient_1.billing_line_items.filter(status=BillingLineItemStatus.ACTIVE, cpt__startswith='99').order_by("charge") ``` ### Example ```python from canvas_sdk.v1.data.patient import Patient from canvas_sdk.v1.data.billing import BillingLineItemStatus patient_1 = Patient.objects.get(id="aebe4d3f5d18410388dc69c4b5169fc3") office_visit_charges = patient_1.billing_line_items.filter(status=BillingLineItemStatus.ACTIVE, cpt__startswith='99').order_by("charge") print([(item.cpt, item.charge,) for item in office_visit_charges]) ``` ``` -------------------------------- ### AdjustPrescription Command Example Source: https://docs.canvasmedical.com/sdk/commands Demonstrates how to instantiate the AdjustPrescriptionCommand with various parameters. Ensure all required fields like `new_fdb_code` are provided. Other parameters can be found in the Prescribe command documentation. ```python from canvas_sdk.commands import AdjustPrescriptionCommand, PrescribeCommand from canvas_sdk.commands.constants import ClinicalQuantity AdjustPrescriptionCommand( fdb_code="172480", new_fdb_code="216092", icd10_codes=["R51"], sig="Take one tablet daily after meals", days_supply=30, quantity_to_dispense=30, type_to_dispense=ClinicalQuantity( representative_ndc="12843016128", ncpdp_quantity_qualifier_code="C48542" ), refills=3, substitutions=PrescribeCommand.Substitutions.ALLOWED, pharmacy="pharmacy_ncpdp_id", prescriber_id="provider_123", supervising_provider_id="provider_456", note_to_pharmacist="Please verify patient's insurance before processing." ) ``` -------------------------------- ### Basic Usage of BatchOriginateCommandEffect Source: https://docs.canvasmedical.com/sdk/effect-batch-originate This example demonstrates how to create and batch originate several different types of commands, including PlanCommand, HistoryOfPresentIllnessCommand, DiagnoseCommand, and QuestionnaireCommand, for a given note. It shows the necessary imports and how to construct the command objects before passing them to the BatchOriginateCommandEffect. ```python from canvas_sdk.commands import ( PlanCommand, HistoryOfPresentIllnessCommand, QuestionnaireCommand, DiagnoseCommand ) from canvas_sdk.effects.batch_originate import BatchOriginateCommandEffect from canvas_sdk.handlers import BaseHandler from canvas_sdk.v1.data import Questionnaire, Note from canvas_sdk.events import EventType class Handler(BaseHandler): def compute(self): note_uuid = Note.objects.last().id # Create multiple commands plan1 = PlanCommand() plan1.narrative = "Order labs for lipid panel" plan1.note_uuid = note_uuid plan2 = PlanCommand() plan2.narrative = "Schedule follow-up in 3 months" plan2.note_uuid = note_uuid hpi = HistoryOfPresentIllnessCommand() hpi.narrative = "Annual wellness visit" hpi.note_uuid = note_uuid diagnose = DiagnoseCommand() diagnose.icd10_code = "E11.9" diagnose.note_uuid = note_uuid diagnose.background = "Type 2 diabetes mellitus" # Add a questionnaire questionnaire = QuestionnaireCommand() questionnaire.note_uuid = note_uuid questionnaire_id = Questionnaire.objects.filter( name="Patient Health Questionnaire" ).first() if questionnaire_id: questionnaire.questionnaire_id = str(questionnaire_id.id) # Batch originate all commands commands_to_originate = [plan1, plan2, hpi, diagnose, questionnaire] return [BatchOriginateCommandEffect(commands=commands_to_originate).apply()] ``` -------------------------------- ### Complete Workflow Example: Extract Data from Document Source: https://docs.canvasmedical.com/sdk/clients-extend-ai This function demonstrates a complete workflow for extracting structured data from a document using the Extend AI SDK. It includes starting a processor, waiting for completion with a timeout, handling results, and cleaning up files. Ensure you have the necessary API key and processor ID. ```python import time from canvas_sdk.clients.extend_ai.libraries import Client from canvas_sdk.clients.extend_ai.constants import RunStatus from canvas_sdk.clients.extend_ai.structures import RequestFailed def extract_from_document(api_key: str, processor_id: str, document_url: str) -> dict: """ Extract structured data from a document using Extend AI. Args: api_key: Your Extend AI API key processor_id: The processor ID to use document_url: Public URL to the document Returns: Dictionary containing the extracted data Raises: RequestFailed: If the API request fails RuntimeError: If processing fails or times out """ client = Client(key=api_key) # Start processing run = client.run_processor( processor_id=processor_id, file_name="document.pdf", file_url=document_url, config=None, ) # Wait for completion (with timeout) max_attempts = 30 # 60 seconds max attempts = 0 while run.status in (RunStatus.PENDING, RunStatus.PROCESSING): if attempts >= max_attempts: raise RuntimeError("Processing timed out") time.sleep(2) run = client.run_status(run.id) attempts += 1 # Handle result if run.status == RunStatus.PROCESSED: # Clean up files for file in run.files: client.delete_file(file.id) return run.output.value if hasattr(run.output, 'value') else run.output.to_dict() raise RuntimeError(f"Processing failed: {run.status.value}") # Usage result = extract_from_document( api_key="your_api_key", processor_id="proc_xxxxxxxxxxxxxxxxx", document_url="https://example.com/document.pdf" ) print(result) ``` -------------------------------- ### Send GET Request Source: https://docs.canvasmedical.com/sdk/utils Use the get method to send an HTTP GET request. Specify the URL and optionally include custom headers. ```python from canvas_sdk.utils import Http http = Http() http.get("https://my-url.com/", headers={"Authorization": f"Bearer token"}) ```