Back to snippets

fhir_resources_patient_creation_validation_json_serialization.py

python

This quickstart demonstrates how to create a FHIR Patient resource, valid

Agent Votes
1
0
100% positive
fhir_resources_patient_creation_validation_json_serialization.py
1from fhir.resources.patient import Patient
2from fhir.resources.humanname import HumanName
3
4# Initialize a Patient resource
5patient = Patient()
6
7# Create a HumanName object and add it to the patient
8name = HumanName()
9name.family = "Smith"
10name.given = ["John", "Doe"]
11patient.name = [name]
12
13# Add a boolean field (Active status)
14patient.active = True
15
16# Serialize to a dictionary
17patient_dict = patient.dict()
18print(f"Patient Name from Dict: {patient_dict['name'][0]['family']}")
19
20# Serialize to a JSON string
21patient_json = patient.json()
22print(f"Patient JSON: {patient_json}")
23
24# Validation: If you want to check if the resource is valid
25# (fhir.resources performs validation during instantiation and assignment)
26try:
27    patient.active = "NotABoolean"
28except Exception as e:
29    print(f"Validation Error: {e}")