Package: shaarpec
Python client for SHAARPEC Analytics API.Explore the docs »View Demo·Report Bug·Request FeatureTable of ContentsAbout The ProjectBuilt WithGetting StartedPrerequisitesInstallationUsageTroubleshootingRoadmapLicenseContactAbout The ProjectThis is a Python client for simple access to the SHAARPEC Analytics API. Authentication is handled automatically via device flow, authorization code flow, or client credentials flow. Authentication can also be disabled if accessing a public Analytics API.The SHAARPEC Analytics API provides calculations on the healthcare organization's resources, capacities, clinical outcomes, and much more. These results can be accessed via a standard REST API, which is usually protected by the SHAARPEC Identity Server.(back to top)Built With(back to top)Getting StartedPrerequisitesThe shaarpec client is used as a standard Python library. It is always a good idea to install the library in a virtual environment.InstallationInstall the library into your virtual environment.pipinstallshaarpecStore your credentials to the SHAARPEC IdentityServer in an .env file.$cat.envOIDCISH_HOST="https://idp.example.com"OIDCISH_CLIENT_ID="my client id"OIDCISH_CLIENT_SECRET="my client secret"OIDCISH_AUDIENCE="shaarpec_api.full_access_scope"OIDCISH_SCOPE="openid shaarpec_api.full_access_scope offline_access"(back to top)UsageThis library provides a Client class to easily interact with the SHAARPEC Analytics API. The class methodsClient.with_device(...),Client.with_code(...), andClient.with_credentials(...)create clients that authenticate with the SHAARPEC IdentityServer with either device flow (not tied to an individual user, recommended), code flow (tied to an individual user, for debugging and development), or credentials flow (non-interactive). There is also a class methodClient.without_auth(...)that does not invoke the IDP server (but will only work if the Analytics API is public, otherwise give 401 Authentication invalid errors).All API data is returned ashttpx.Responseobjects.Let's look at some code examples on how to get data from the Analytics API. First, import the client.fromshaarpecimportClientNext, usedevice floworcode flowto connect the client to the API with theClient.with_device(...),Client.with_code(...), and/orClient.with_credentials(...)class methods.The credentials can either be stored in a .env file in the working directory (as explained in the Prerequisites section), provided as a path, or given directly as arguments to theauthdict.# Create a client with device flow, give authentication details directly.client=Client.with_device(host="https://api.shaarpec.com/",auth={"host":"https://idp.shaarpec.com","client_id":...,"client_secret":...,"scope":...,"audience":...})# Create a client with device flow, read authentication details from .env file.client=Client.with_device(host="https://api.shaarpec.com/",auth="path/to/.env")Herehostis the base URL to the Analytics API andauthis a dictionary with the login credentials. With device flow, the user needs to finish the sign-in by visiting a url provided by the IdentityServer. A message will be shown:Visithttps://idp.shaarpec.com/device?userCode=XXXXXXXXXto complete sign-in.The user visits the website, verifies that the user code is correct and confirms the sign-in. After a few seconds, the client will confirm the sign-in:SUCCESS: Authentication was successful. Took XX.Y seconds.The client is now connected to the API. Visit the Analytics API Base URL to interactively test the endpoints and read the documentation about their path and query parameters. These parameters are used in the regularrequestsandhttpxway withclient.verbcalls, whereverbis eitherget,post, orrun(see below).GET and POSTThegetandpostverbs are supported in the standard way. For example (API responses are returned ashttpx.Responseobjects):client.get("terminology/allergy_type").json()might return{'419263009': 'Allergy to tree pollen',
 '420174000': 'Allergy to wheat',
 '425525006': 'Allergy to dairy product',
 '714035009': 'Allergy to soya',
 '419474003': 'Allergy to mould',
 '232347008': 'Dander (animal) allergy',
 '91934008': 'Allergy to nut',
 '417532002': 'Allergy to fish',
 '300913006': 'Shellfish allergy',
 '232350006': 'House dust mite allergy',
 '418689008': 'Allergy to grass pollen',
 '91935009': 'Allergy to peanuts',
 '91930004': 'Allergy to eggs',
 '300916003': 'Latex allergy',
 '424213003': 'Allergy to bee venom'}orclient.post("population",conditions=["T78.2","K81.0"])might return[{'patient_origin_id': '4c92f494-3c98-f8dd-1473-da9eb0196f6f',
    'age': '10-16',
    'is_alive': True,
    'gender': 'F',
    'deceased_year': 0},
 ...
]You can send keyword arguments to the underlyinghttpxcalls via thehttpx_kwargsparameter, for example:client.get("terminology/condition_type/codes",httpx_kwargs={"timeout":120}).json()# Sends API call with 120 second timeout)Read about the available parameters in thehttpx documentation.Running tasksSHAARPEC Analytics API supports long-running tasks byPOST:ing to/service/path/to/endpoint, and then polling withGETto/service/tasks/{task_id}/statusuntil the result becomes available at/service/tasks/{task_id}/results. There is arunfunction in the library that performs this pattern.For exampletask=client.run("population/conditions")will return a task with the comorbidities in the entire population. A task is aPydanticmodel with the following properties:classTask(BaseModel):"""A running task."""service:strtask_id:strsubmitted_at:strstatus:strsuccess:Optional[bool]progress:Optional[float]result:Optional[Any]error:Optional[Any]As you can see, the success, progress, result and error are optional and updated automatically when available. The method comes with a progress bar which can be disabled viaclient.run("path/to/task", progress_bar=False). If you want to use the task result in a subsequent command, you can wait (blocking) for the result with thetask.wait_for_result()method:task=client.run("path/to/task")print(f"The result is:{task.wait_for_result()}!")(back to top)TroubleshootingProgress bar fails to render in (Dockerized) Jupyter LabSometimes (especially in a Dockerized environment) the progress bar fails to render when running a task. This seems to be related to an issue intqdmand its dependencies. A workaround seems to be to run:jupyterlabbuildin the environment (in a terminal inside the running Docker container) and refresh the browser. This requires anode.jsinstallation first, e.g. per:conda install -c conda-forge nodejsSee discussion forissue 1310on thetqdmGithub repo.RoadmapSee theopen issuesfor a full list of proposed features (and known issues).(back to top)LicenseDistributed under the MIT License. SeeLICENSEfor more information.(back to top)ContactSHAARPEC Support -support@shaarpec.comProject Link:https://github.com/SHAARPEC/shaarpec-python-client(back to top)