Search code examples
pythonjsonhl7-fhir

Smart-on-FHIR Python Client with Bundles


So I have a FHIR patient bundle json from the "$everything" operation: https://www.hl7.org/fhir/operation-patient-everything.html

I am now interested in using the Smart on FHIR Python Client Models to make working with the json file a lot easier. An example given is the following:

import json
import fhirclient.models.patient as p
with open('path/to/patient.json', 'r') as h:
     pjs = json.load(h)
patient = p.Patient(pjs)
patient.name[0].given
# prints patient's given name array in the first `name` property

Would it be possible to do instantiate something with just a generic bundle object class to be able access different resources inside the bundle?


Solution

  • Yes, you can instantiate a Bundle like you can instantiate any other model, either manually from JSON or by a read from the server. Every search returns a Bundle as well. Then you can just iterate over the bundle's entries and work with them, like put them in an array:

    resources = []
    if bundle.entry is not None:
        for entry in bundle.entry:
            resources.append(entry.resource)
    

    p.s. It should be possible to execute any $operation with the client, returning the Bundle you mention, but I have to check if we've exposed that or if it has not been committed.


    Command line example:

    import fhirclient.models.bundle as b
    import json
    with open('fhir-parser/downloads/bundle-example.json', 'r') as h:
        js = json.load(h)
    bundle = b.Bundle(js)
    bundle.entry
    [<fhirclient.models.bundle.BundleEntry object at 0x10f40ae48>, 
     <fhirclient.models.bundle.BundleEntry object at 0x10f40ac88>]
    for entry in bundle.entry:
        print(entry.resource)
    
    // prints
    <fhirclient.models.medicationorder.MedicationOrder object at 0x10f407390>
    <fhirclient.models.medication.Medication object at 0x10f407e48>