0
# References
1
2
FHIR reference handling with resolution capabilities and local/external reference detection. References represent relationships between FHIR resources and can be resolved to retrieve the referenced resource.
3
4
## Capabilities
5
6
### Reference Resolution
7
8
Resolve references to retrieve the actual referenced resources.
9
10
```python { .api }
11
async def resolve(self) -> FHIRResource:
12
"""
13
Resolve the reference to retrieve the referenced resource.
14
15
Returns:
16
The resource instance that this reference points to
17
18
Raises:
19
- ResourceNotFound: If referenced resource doesn't exist
20
- InvalidResponse: If reference cannot be resolved
21
"""
22
```
23
24
### Reference Properties
25
26
Properties for accessing reference information and metadata.
27
28
```python { .api }
29
@property
30
def reference(self) -> str:
31
"""
32
The reference string (e.g., 'Patient/123' or 'https://external.com/Patient/456').
33
34
Returns:
35
Full reference string
36
"""
37
38
@property
39
def id(self) -> str:
40
"""
41
The resource ID if this is a local reference.
42
43
Returns:
44
Resource ID for local references, None for external references
45
"""
46
47
@property
48
def resource_type(self) -> str:
49
"""
50
The resource type if this is a local reference.
51
52
Returns:
53
Resource type for local references, None for external references
54
"""
55
56
@property
57
def is_local(self) -> bool:
58
"""
59
Whether this reference points to a local resource.
60
61
Returns:
62
True for local references (ResourceType/id), False for external URLs
63
"""
64
```
65
66
## Usage Examples
67
68
### Creating References
69
70
```python
71
import asyncio
72
from fhirpy import AsyncFHIRClient
73
74
async def creating_references():
75
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
76
77
# Create reference by resource type and ID
78
patient_ref = client.reference('Patient', '123')
79
print(f"Reference: {patient_ref.reference}") # 'Patient/123'
80
81
# Create reference by full reference string
82
external_ref = client.reference(reference='https://external.com/Patient/456')
83
print(f"External reference: {external_ref.reference}")
84
85
# Create reference with additional attributes
86
display_ref = client.reference('Patient', '123',
87
display='John Doe',
88
type='Patient')
89
90
# Convert resource to reference
91
patient = client.resource('Patient', id='123',
92
name=[{'family': 'Doe', 'given': ['John']}])
93
patient_ref = patient.to_reference(display='John Doe')
94
```
95
96
### Reference Properties and Detection
97
98
```python
99
async def reference_properties():
100
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
101
102
# Local reference
103
local_ref = client.reference('Patient', '123')
104
print(f"Is local: {local_ref.is_local}") # True
105
print(f"Resource type: {local_ref.resource_type}") # 'Patient'
106
print(f"ID: {local_ref.id}") # '123'
107
print(f"Reference: {local_ref.reference}") # 'Patient/123'
108
109
# External reference
110
external_ref = client.reference(reference='https://external.com/Patient/456')
111
print(f"Is local: {external_ref.is_local}") # False
112
print(f"Resource type: {external_ref.resource_type}") # None
113
print(f"ID: {external_ref.id}") # None
114
print(f"Reference: {external_ref.reference}") # 'https://external.com/Patient/456'
115
116
# Reference with only display (contained resource scenario)
117
display_only_ref = client.reference(reference='#patient1',
118
display='Contained Patient')
119
print(f"Is local: {display_only_ref.is_local}") # False (not ResourceType/id format)
120
```
121
122
### Reference Resolution
123
124
```python
125
async def reference_resolution():
126
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
127
128
# Create a patient first
129
patient = client.resource('Patient',
130
name=[{'family': 'Doe', 'given': ['John']}])
131
await patient.create()
132
133
# Create reference to the patient
134
patient_ref = client.reference('Patient', patient.id)
135
136
# Resolve reference to get full patient data
137
resolved_patient = await patient_ref.resolve()
138
print(f"Resolved patient name: {resolved_patient.get_by_path('name.0.family')}")
139
140
# Use reference in another resource
141
observation = client.resource('Observation',
142
status='final',
143
code={
144
'coding': [{
145
'system': 'http://loinc.org',
146
'code': '55284-4',
147
'display': 'Blood pressure'
148
}]
149
},
150
subject=patient_ref, # Reference to patient
151
valueQuantity={
152
'value': 120,
153
'unit': 'mmHg'
154
}
155
)
156
await observation.create()
157
158
# Later, resolve the subject reference
159
subject_ref = observation['subject']
160
subject_patient = await subject_ref.resolve()
161
print(f"Subject: {subject_patient.get_by_path('name.0.given.0')}")
162
```
163
164
### Working with References in Resources
165
166
```python
167
async def references_in_resources():
168
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
169
170
# Create related resources
171
practitioner = client.resource('Practitioner',
172
name=[{'family': 'Smith', 'given': ['Dr. Jane']}])
173
await practitioner.create()
174
175
organization = client.resource('Organization',
176
name='General Hospital')
177
await organization.create()
178
179
patient = client.resource('Patient',
180
name=[{'family': 'Doe', 'given': ['John']}],
181
generalPractitioner=[practitioner.to_reference()],
182
managingOrganization=organization.to_reference()
183
)
184
await patient.create()
185
186
# Access and resolve references
187
gp_ref = patient['generalPractitioner'][0] # First GP reference
188
org_ref = patient['managingOrganization'] # Organization reference
189
190
print(f"GP reference: {gp_ref.reference}")
191
print(f"Org reference: {org_ref.reference}")
192
193
# Resolve references to get full data
194
gp = await gp_ref.resolve()
195
org = await org_ref.resolve()
196
197
print(f"GP Name: {gp.get_by_path('name.0.family')}")
198
print(f"Organization: {org['name']}")
199
```
200
201
### Reference Validation and Error Handling
202
203
```python
204
async def reference_error_handling():
205
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
206
207
# Create reference to non-existent resource
208
invalid_ref = client.reference('Patient', 'non-existent-id')
209
210
try:
211
resolved = await invalid_ref.resolve()
212
except ResourceNotFound:
213
print("Referenced resource does not exist")
214
215
# Check reference validity before resolving
216
def is_valid_reference_format(ref):
217
if ref.is_local:
218
return ref.resource_type and ref.id
219
return ref.reference.startswith(('http://', 'https://'))
220
221
refs_to_check = [
222
client.reference('Patient', '123'),
223
client.reference(reference='https://external.com/Patient/456'),
224
client.reference(reference='#contained1')
225
]
226
227
for ref in refs_to_check:
228
if is_valid_reference_format(ref):
229
try:
230
resolved = await ref.resolve()
231
print(f"Successfully resolved: {ref.reference}")
232
except ResourceNotFound:
233
print(f"Valid format but resource not found: {ref.reference}")
234
else:
235
print(f"Invalid reference format: {ref.reference}")
236
```
237
238
### Bundle References and Contained Resources
239
240
```python
241
async def bundle_and_contained_references():
242
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
243
244
# Create bundle with references between entries
245
bundle_data = {
246
'resourceType': 'Bundle',
247
'type': 'transaction',
248
'entry': [
249
{
250
'fullUrl': 'urn:uuid:patient-1',
251
'resource': {
252
'resourceType': 'Patient',
253
'name': [{'family': 'Doe', 'given': ['John']}]
254
},
255
'request': {'method': 'POST', 'url': 'Patient'}
256
},
257
{
258
'fullUrl': 'urn:uuid:observation-1',
259
'resource': {
260
'resourceType': 'Observation',
261
'status': 'final',
262
'code': {
263
'coding': [{
264
'system': 'http://loinc.org',
265
'code': '55284-4'
266
}]
267
},
268
'subject': {'reference': 'urn:uuid:patient-1'}, # Bundle reference
269
'valueQuantity': {'value': 120, 'unit': 'mmHg'}
270
},
271
'request': {'method': 'POST', 'url': 'Observation'}
272
}
273
]
274
}
275
276
# Submit bundle
277
result = await client.execute('', method='post', data=bundle_data)
278
279
# Work with contained resources
280
patient_with_contained = client.resource('Patient',
281
name=[{'family': 'Parent', 'given': ['Jane']}],
282
contained=[{
283
'resourceType': 'RelatedPerson',
284
'id': 'child1',
285
'patient': {'reference': '#'}, # Reference to containing resource
286
'relationship': [{
287
'coding': [{
288
'system': 'http://terminology.hl7.org/CodeSystem/v3-RoleCode',
289
'code': 'CHILD'
290
}]
291
}]
292
}],
293
contact=[{
294
'relationship': [{
295
'coding': [{
296
'system': 'http://terminology.hl7.org/CodeSystem/v2-0131',
297
'code': 'C'
298
}]
299
}],
300
'name': {'family': 'Child', 'given': ['Little']},
301
# Reference to contained resource
302
'organization': {'reference': '#child1'}
303
}]
304
)
305
306
await patient_with_contained.create()
307
```