Olá a todos,
Sou eu de novo 😁. No artigo anterior, Writing a REST api service for exporting the generated FHIR bundle in JSON, nós geramos um recurso DocumentReference, com o conteúdo codificados em Base64.
.png)
Question!! Is it possible to write a REST service for decoding it? Because I am very curious what is the message data talking about🤔🤔🤔
Duvida!! É possível escrever um serviço REST para decodificar isso? Porque estou muito curioso para saber o conteúdo da mensagem 🤔🤔🤔
OK, Vamos começar!
1. Crie uma nova classe utilitária datagen.utli.decodefhirjson.cls para decodificar os dados dentro de DocumentReference
Class datagen.utli.decodefhirjson Extends %RegisteredObject
{
}
2. Escreva uma função Python decodebase64docref para
a. percorrer o bundle FHIR
b. encontrar o recurso DocumentReference
-pegar o primeiro elemento em content
- pegar o attachment do content
- recuperar o data do attachment
c. decodificar os dados em Base64
(essa parte pedi ajuda ao chatGPT😂🤫)
Class datagen.utli.decodefhirjson Extends %RegisteredObject
{
ClassMethod decodebase64docref(fhirbundle = "") As %String [ Language = python ]
{
# w ##class(datagen.utli.decodefhirjson).decodebase64docref()
import base64
import json
def decode_discharge_summary(bundle_json):
"""
Extracts and decodes the Base64-encoded discharge summary note
from a FHIR Bundle containing a DocumentReference.
"""
for entry in bundle_json.get("entry", []):
resource = entry.get("resource", {})
if resource.get("resourceType") == "DocumentReference":
# Traverse to the attachment
content_list = resource.get("content", [])
if not content_list:
continue
attachment = content_list[0].get("attachment", {})
base64_data = attachment.get("data")
if base64_data:
decoded_text = base64.b64decode(base64_data).decode("utf-8")
return decoded_text
return None
# Example usage
# Load your FHIR Bundle JSON from a file or object
#with open("fhir_bundle.json", "r") as f:
# fhir_bundle = json.loads(f)
if fhirbundle=="":
rtstr=f"⚠️ No input found - JSON string is required."
jsstr={"operation_outcome" : rtstr}
return json.dumps(jsstr, indent=2)
fhir_bundle = json.loads(fhirbundle)
decoded_note = decode_discharge_summary(fhir_bundle)
if decoded_note:
#print("📝 Decoded Discharge Summary:\n")
#print(decoded_note)
rtstr=f"📝 Decoded Discharge Summary:\n {decoded_note}"
else:
#print("⚠️ No DocumentReference with Base64 note found.")
rtstr=f"⚠️ No DocumentReference with Base64 note found."
jsstr={"data" : rtstr}
return json.dumps(jsstr, indent=2)
}
}
Para testar essa função, eu tentei fazer um pequeno truque, que é usar a função genfhirbundle para gerar um bundle FHIR em string JSON, conforme mostrado no artigo anterior Writing a REST api service for exporting the generated FHIR bundle in JSON.
Vamos gerar um bundle FHIR e armazená-lo em uma variável chamada jsonstr.
set jsonstr=##class(datagen.utli.genfhirjson).genfhirbundle(1)
Depois, teste a função de decodificação decodebase64docref usando jsonstr.
w ##class(datagen.utli.decodefhirjson).decodebase64docref(jsonstr)
.png)
OK 😉. Parece tudo certo. Agora posso ler a mensagem decodificada.
Agora, voltando ao artigo anterior e ao anterior a esse, Writing a REST api service for exporting the generated patient data in .csv.
Gostaríamos de adicionar uma nova função e atualizar a rota da classe datagen.restservice.
1. Adicionar uma nova função DecodeDocRef, que deverá processar o bundle FHIR enviado no corpo da requisição em formato JSON.
Ou seja, neste caso esperamos um POST.
O conteúdo do corpo é empacotado por padrão como %CSP.BinaryStream e armazenado na variável %request.Content, então podemos usar o método .Read() da classe %CSP.BinaryStream para ler o BinaryStream.
ClassMethod DecodeDocRef() As %Status
{
#dim bistream As %CSP.BinaryStream =""
set bistream=%request.Content
set jsstr=bistream.Read()
w ##class(datagen.utli.decodefhirjson).decodebase64docref(jsstr)
return $$$OK
}
2. Depois, adicionamos uma rota para o REST service e compilamos 😀
<Route Url="/decode/docref" Method="POST" Call="DecodeDocRef" />
a classe datagen.restservice atualizada ficará parecida com o seguinte:
.png)
Perfeito!😁
Vamnos testar no postman!!
Envie uma chamada POST para o seguinte caminho:
localhost/irishealth/csp/mpapp/decode/docref
com o seguinte corpo (eu simplifiquei o bundle FHIR, você pode testar com o completo 😀)
{
"resourceType": "Bundle",
"type": "transaction",
"id": "98bfce83-7eb1-4afe-bf2b-42916512244e",
"meta": {
"lastUpdated": "2025-10-13T05:49:07Z"
},
"entry": [
{
"fullUrl": "urn:uuid:5be1037d-a481-45ca-aea9-2034e27ebdcd",
"resource": {
"resourceType": "DocumentReference",
"id": "5be1037d-a481-45ca-aea9-2034e27ebdcd",
"status": "current",
"type": {
"coding": [
{
"system": "http://loinc.org",
"code": "18842-5",
"display": "Discharge summary"
}
]
},
"subject": {
"reference": "9e3a2636-4e87-4dee-b202-709d6f94ed18"
},
"author": [
{
"reference": "2aa54642-6743-4153-a171-7b8a8004ce5b"
}
],
"context": {
"encounter": [
{
"reference": "98cd848b-251f-4d0b-bf36-e35c9fe68956"
}
]
},
"content": [
{
"attachment": {
"contentType": "text/plain",
"language": "en",
"data": "RGlzY2hhcmdlIHN1bW1hcnkgZm9yIHBhdGllbnQgOWUzYTI2MzYtNGU4Ny00ZGVlLWIyMDItNzA5ZDZmOTRlZDE4LiBEaWFnbm9zaXM6IFN0YWJsZS4gRm9sbG93LXVwIGluIDIgd2Vla3Mu",
"title": "Discharge Summary Note"
}
}
]
},
"request": {
"method": "POST",
"url": "DocumentReference"
}
}
]
}
.png)
Funcionou bem!!!😆😉
Muito obrigado pela leitura. 😘