FHIR Model Factory
Main class and utilities for dynamically constructing FHIR resource models.
ModelAssembler
Path: fhircraft.fhir.resources.factory.assembler.ModelAssembler
ModelAssembler(index: DefinitionIndex, ctx: BuildContext, resource_name: str = 'Unknown')
Methods:
| Name | Description |
|---|---|
assemble |
Dynamically assembles and returns a Pydantic model class based on the provided name, base classes, |
build_model_fixed_value_constraint |
Constructs a ValidatorInformation object for enforcing a fixed value constraint on a FHIR model element. |
build_model_pattern_constraint |
Constructs a ValidatorInformation object for enforcing a pattern constraint on a FHIR model element. |
Attributes:
| Name | Type | Description |
|---|---|---|
index |
DefinitionIndex
|
The definition index to assemble from. |
ctx |
BuildContext
|
The build context. |
resource_name |
str
|
The name of the resource being assembled (for error messages). |
builder_chain |
Sequence[Builder]
|
The chain of builders to use for assembling fields. Initialized from :attr: |
Source code in fhircraft/fhir/resources/factory/assembler.py
resource_name
instance-attribute
resource_name: str = resource_name
The name of the resource being assembled (for error messages).
builder_chain
instance-attribute
The chain of builders to use for assembling fields. Initialized from :attr:BUILDER_CHAIN.
assemble
Dynamically assembles and returns a Pydantic model class based on the provided name, base classes, and the structure defined in the internal index. Args: name (str): The name of the model to be created. base (type or tuple[type, ...], optional): The base class(es) for the model. If None, uses the default base from context or FHIRBaseModel. Returns: type: The dynamically created Pydantic model class. Raises: ValueError: If a child element in the index lacks a definition. FactoryAssemblerError: If a builder fails to construct a field or validator. Notes: - Resolves base classes and iterates over child elements to build fields, validators, and properties. - Handles model-level constraints, including fixed values and patterns. - Attaches properties and sets constraint defaults as needed. - Issues a warning if no fields are built and no fields are inherited from base classes.
Source code in fhircraft/fhir/resources/factory/assembler.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
build_model_fixed_value_constraint
staticmethod
build_model_fixed_value_constraint(node: ElementNode) -> ValidatorInformation
Constructs a ValidatorInformation object for enforcing a fixed value constraint on a FHIR model element. Args: node (ElementNode): The element node containing the fixed value to be validated. Returns: ValidatorInformation: An object encapsulating the validator's name, kind, function, and arguments for the fixed value constraint.
Source code in fhircraft/fhir/resources/factory/assembler.py
build_model_pattern_constraint
staticmethod
build_model_pattern_constraint(node: ElementNode) -> ValidatorInformation
Constructs a ValidatorInformation object for enforcing a pattern constraint on a FHIR model element. Args: node (ElementNode): The element node containing the pattern to be validated. Returns: ValidatorInformation: An object containing the validator's name, kind, and a partial function for pattern validation specific to the provided node.
Source code in fhircraft/fhir/resources/factory/assembler.py
BackboneFieldBuilder
Path: fhircraft.fhir.resources.factory.builders.backbone.BackboneFieldBuilder
BackboneFieldBuilder(context: BuildContext)
Build
Path: fhircraft.fhir.resources.factory.builders.base.Build
dataclass
Build(fields: List[FieldInformation] = list(), validators: List[ValidatorInformation] = list(), properties: dict[str, Callable] = dict())
The result of a Builder's build() method, containing the field and validator information needed to construct a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
List[FieldInformation]
|
Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified. |
<dynamic>
|
validators
|
List[ValidatorInformation]
|
Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified. |
<dynamic>
|
properties
|
dict[str, Callable]
|
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) |
<class 'dict'>
|
Attributes:
| Name | Type | Description |
|---|---|---|
fields |
List[FieldInformation]
|
The list of fields to include in the model. |
validators |
List[ValidatorInformation]
|
The list of validators to include in the model. |
properties |
dict[str, Callable]
|
The dictionary of properties to include in the model. |
fields
class-attribute
instance-attribute
fields: List[FieldInformation] = field(default_factory=list)
The list of fields to include in the model.
validators
class-attribute
instance-attribute
validators: List[ValidatorInformation] = field(default_factory=list)
The list of validators to include in the model.
Builder
Path: fhircraft.fhir.resources.factory.builders.base.Builder
Builder(context: BuildContext)
Bases: ABC
Methods:
| Name | Description |
|---|---|
handle_python_keyword |
Handle Python keywords and reserved class keywords by creating safe aliases. |
build_field_information |
Build field information for a FHIR resource field. |
build_invariant_constraint |
Build validator information for a FHIR invariant constraint. |
resolve_type |
Resolve a FHIR type definition to its corresponding type information. |
build_field_validators |
Constructs a list of field validators for a given FHIR element node. |
Source code in fhircraft/fhir/resources/factory/builders/base.py
handle_python_keyword
staticmethod
handle_python_keyword(field_name: str) -> tuple[str, AliasChoices | None]
Handle Python keywords and reserved class keywords by creating safe aliases.
This function checks if a field name is a Python keyword or a reserved class keyword. If it is, the function creates a safe alternative by appending an underscore and returns both the safe name and an AliasChoices object mapping the original name to the safe name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The name of the field to check. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, AliasChoices | None]
|
tuple[str, AliasChoices | None]: A tuple containing: - str: The safe field name (with underscore appended if it's a keyword, otherwise unchanged) - AliasChoices | None: An AliasChoices object mapping original to safe name if a conflict exists, None otherwise. |
Example
handle_python_keyword("class") ("class_", AliasChoices("class", "class_")) handle_python_keyword("my_field") ("my_field", None)
Source code in fhircraft/fhir/resources/factory/builders/base.py
build_field_information
staticmethod
build_field_information(name: str, node: ElementNode, type: Any, alias: str | None = None, validation_alias: AliasChoices | None = None, description: str | None = None, default: Any = _Unset) -> FieldInformation
Build field information for a FHIR resource field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the field. |
required |
node
|
ElementNode
|
The ElementNode containing field metadata and constraints. |
required |
type
|
Any
|
The base type annotation for the field (type or Annotated). |
required |
alias
|
str | None
|
Optional alias for the field during serialization. |
None
|
validation_alias
|
AliasChoices | None
|
Optional validation alias choices for the field. |
None
|
description
|
str | None
|
Optional description of the field. If not provided, uses node.documentation. |
None
|
default
|
Any
|
Optional default value for the field. If not provided, it will be determined based on node's default_value, fixed, or pattern. |
_Unset
|
Returns:
| Name | Type | Description |
|---|---|---|
FieldInformation |
FieldInformation
|
A FieldInformation object containing the field's name, annotation, default value, alias, validation alias, description, and constraints (min/max length and min/max value). |
Notes
- Default value priority: node.default_value > node.fixed > node.pattern > None
- If the field is an array and a default is set, it is converted to a list.
- Arrays are annotated as List[type].
- All fields are made Optional to enforce optionality.
- Min/max cardinality constraints only apply to array fields.
Source code in fhircraft/fhir/resources/factory/builders/base.py
build_invariant_constraint
staticmethod
build_invariant_constraint(field_name: str, constraint: ElementDefinitionConstraint | ElementDefinitionConstraint | ElementDefinitionConstraint, kind: Literal['field', 'model'] = 'field') -> ValidatorInformation
Build validator information for a FHIR invariant constraint. This function creates a ValidatorInformation object that encapsulates the details of a FHIR invariant constraint, which can be used to validate elements against user-defined constraints expressed in FHIRPath expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The name of the field/element to apply the constraint to. |
required |
constraint
|
ElementDefinitionConstraint | ElementDefinitionConstraint | ElementDefinitionConstraint
|
An ElementDefinitionConstraint object (from FHIR R4, R4B, or R5) containing the constraint definition with required attributes: key, expression, human, and severity. |
required |
kind
|
Literal['field', 'model']
|
The kind of validator to create, either "field" for field-level validation or "model" for model-level validation. Defaults to "field". |
'field'
|
Returns:
| Name | Type | Description |
|---|---|---|
ValidatorInformation |
ValidatorInformation
|
An object containing the name, kind, function, and arguments for the constraint validator. |
Raises:
| Type | Description |
|---|---|
FactoryBuilderError
|
If the constraint is missing any required attributes |
Source code in fhircraft/fhir/resources/factory/builders/base.py
resolve_type
resolve_type(type: ElementDefinitionType | ElementDefinitionType | ElementDefinitionType) -> TypeInformation
Resolve a FHIR type definition to its corresponding type information. This method processes FHIR ElementDefinitionType objects and returns TypeInformation containing the resolved type, its kind, and whether it requires primitive extensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
ElementDefinitionType | ElementDefinitionType | ElementDefinitionType
|
An ElementDefinitionType from FHIR R4, R4B, or R5 release that specifies a type code, optional profile URL, and other type metadata. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TypeInformation |
TypeInformation
|
An object containing the resolved Python type, its kind (primitive, complex, resource), and whether it requires a primitive extension field. |
Raises:
| Type | Description |
|---|---|
FactoryTypeResolutionError
|
If the type definition has no code attribute, making it impossible to resolve the type for the given FHIR release. |
Source code in fhircraft/fhir/resources/factory/builders/base.py
build_field_validators
build_field_validators(node: ElementNode, safe_name: str) -> List[ValidatorInformation]
Constructs a list of field validators for a given FHIR element node.
This method inspects the provided ElementNode and generates appropriate
validators based on fixed values, patterns, and custom constraints defined
in the node's definition. Each validator is represented as a
ValidatorInformation object.
Args:
node (ElementNode): The FHIR element node for which validators are built.
safe_name (str): The sanitized field name used in validator identification.
Returns:
List[ValidatorInformation]: A list of field-level validators for the element.
Source code in fhircraft/fhir/resources/factory/builders/base.py
FieldInformation
Path: fhircraft.fhir.resources.factory.builders.base.FieldInformation
dataclass
FieldInformation(name: str, annotation: Any, default: Any = _Unset, alias: str | None = None, validation_alias: AliasChoices | None = None, description: str | None = None, min_length: int | None = None, max_length: int | None = None, min_value: int | None = None, max_value: int | None = None)
FieldInformation(name: str, annotation: Any, default: Any = PydanticUndefined, alias: str | None = None, validation_alias: pydantic.aliases.AliasChoices | None = None, description: str | None = None, min_length: int | None = None, max_length: int | None = None, min_value: int | None = None, max_value: int | None = None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the field. |
required |
annotation
|
Any
|
The type annotation for the field. |
required |
default
|
Any
|
The default value for the field. |
PydanticUndefined
|
alias
|
str | None
|
The alias for the field. |
None
|
validation_alias
|
AliasChoices | None
|
The validation alias for the field. |
None
|
description
|
str | None
|
The description of the field. |
None
|
min_length
|
int | None
|
The minimum length of the field. |
None
|
max_length
|
int | None
|
The maximum length of the field. |
None
|
min_value
|
int | None
|
The minimum value of the field. |
None
|
max_value
|
int | None
|
The maximum value of the field. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the field. |
annotation |
Any
|
The type annotation for the field. |
default |
Any
|
The default value for the field. |
alias |
str | None
|
The alias for the field. |
validation_alias |
AliasChoices | None
|
The validation alias for the field. |
description |
str | None
|
The description of the field. |
min_length |
int | None
|
The minimum length of the field. |
max_length |
int | None
|
The maximum length of the field. |
min_value |
int | None
|
The minimum value of the field. |
max_value |
int | None
|
The maximum value of the field. |
validation_alias
class-attribute
instance-attribute
validation_alias: AliasChoices | None = None
The validation alias for the field.
description
class-attribute
instance-attribute
description: str | None = None
The description of the field.
min_length
class-attribute
instance-attribute
min_length: int | None = None
The minimum length of the field.
max_length
class-attribute
instance-attribute
max_length: int | None = None
The maximum length of the field.
min_value
class-attribute
instance-attribute
min_value: int | None = None
The minimum value of the field.
max_value
class-attribute
instance-attribute
max_value: int | None = None
The maximum value of the field.
TypeInformation
Path: fhircraft.fhir.resources.factory.builders.base.TypeInformation
dataclass
Resolved type information for an ElementDefinitionType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
type
|
The resolved Python type. |
required |
kind
|
str
|
The kind of FHIR type (e.g., "primitive", "complex", "resource"). |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
type |
type
|
The resolved Python type. |
kind |
str
|
The kind of FHIR type (e.g., "primitive", "complex", "resource"). |
ValidatorInformation
Path: fhircraft.fhir.resources.factory.builders.base.ValidatorInformation
dataclass
ValidatorInformation(name: str, kind: Literal['field', 'model'], function: Callable, arguments: dict[str, Any] = dict(), field: str | None = None)
Resolved validator information for a Pydantic validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the validator. |
required |
kind
|
Literal['field', 'model']
|
The kind of validator (field-level or model-level). |
required |
function
|
Callable
|
The actual validator function. |
required |
arguments
|
dict[str, Any]
|
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) |
<class 'dict'>
|
field
|
str | None
|
The fields this validator applies to (for field validators). |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the validator. |
kind |
Literal['field', 'model']
|
The kind of validator (field-level or model-level). |
function |
Callable
|
The actual validator function. |
arguments |
dict[str, Any]
|
The arguments for the validator function. |
field |
str | None
|
The fields this validator applies to (for field validators). |
kind
instance-attribute
kind: Literal['field', 'model']
The kind of validator (field-level or model-level).
arguments
class-attribute
instance-attribute
The arguments for the validator function.
field
class-attribute
instance-attribute
field: str | None = None
The fields this validator applies to (for field validators).
SimpleFieldBuilder
Path: fhircraft.fhir.resources.factory.builders.simple.SimpleFieldBuilder
SimpleFieldBuilder(context: BuildContext)
Bases: Builder
Fallback builder for all other elements.
Produces a plain typed field, and — for FHIR primitive types — also
appends a _{name} extension placeholder field.
Source code in fhircraft/fhir/resources/factory/builders/base.py
SlicedFieldBuilder
Path: fhircraft.fhir.resources.factory.builders.slices.SlicedFieldBuilder
SlicedFieldBuilder(context: BuildContext)
TypeChoiceFieldBuilder
Path: fhircraft.fhir.resources.factory.builders.type_choice.TypeChoiceFieldBuilder
TypeChoiceFieldBuilder(context: BuildContext)
BuildContext
Path: fhircraft.fhir.resources.factory.context.BuildContext
dataclass
BuildContext(fhir_release: str, fhir_version: str, base: type, resource_name: str, factory: FHIRModelFactory, registry: 'StructureDefinitionRegistry')
Immutable context container passed through the entire factory pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fhir_release
|
str
|
FHIR release version (e.g. 'R4', 'STU3', 'R5'). |
required |
fhir_version
|
str
|
Full FHIR version string (e.g. '4.3.0'). |
required |
base
|
type
|
The base model class for this build session. |
required |
resource_name
|
str
|
The resource name for this build session. |
required |
factory
|
FHIRModelFactory
|
The FHIR structure factory for this build session. |
required |
registry
|
'StructureDefinitionRegistry'
|
The structure definition registry for resolving references and looking up base definitions. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
fhir_release |
str
|
FHIR release version (e.g. 'R4', 'STU3', 'R5'). |
fhir_version |
str
|
Full FHIR version string (e.g. '4.3.0'). |
base |
type
|
The base model class for this build session. |
resource_name |
str
|
The resource name for this build session. |
factory |
FHIRModelFactory
|
The FHIR structure factory for this build session. |
registry |
'StructureDefinitionRegistry'
|
The structure definition registry for resolving references and looking up base definitions. |
factory
instance-attribute
factory: FHIRModelFactory
The FHIR structure factory for this build session.
FHIRModelFactory
Path: fhircraft.fhir.resources.factory.core.FHIRModelFactory
FHIRModelFactory(fhir_release: str, registry: StructureDefinitionRegistry | None = None)
FHIRModelFactory constructs Pydantic model classes from FHIR StructureDefinitions.
The factory manages a registry of StructureDefinitions, supports loading FHIR packages, and caches constructed models to optimise performance.
Attributes:
| Name | Type | Description |
|---|---|---|
fhir_release |
str
|
The FHIR release version (e.g. "R4", "R5") used by the factory. |
definition_registry |
StructureDefinitionRegistry
|
Registry for storing and retrieving StructureDefinitions. |
construction_cache |
dict[str, type[BaseModel]]
|
Cache mapping canonical URLs to constructed Pydantic model classes. |
Methods:
| Name | Description |
|---|---|
build |
Constructs and returns a Pydantic model class based on a FHIR StructureDefinition. |
register_package |
Download and register all StructureDefinitions from a FHIR npm package. |
register |
Register a StructureDefinition with the factory. |
unregister |
Remove a StructureDefinition from the registry and evict it from the cache. |
reset_cache |
Discard the entire construction cache. |
has_registered_definition |
Return |
get_registered_definition |
Retrieve a registered StructureDefinition by canonical URL. |
list_registered_definitions |
Return all canonical URLs registered in the definition registry. |
is_built |
Return |
list_built |
Return all canonical URLs whose models are currently cached. |
evict |
Remove a single entry from the construction cache. |
rebuild |
Evict url from the cache and build a fresh model. |
enable_internet_access |
Allow the definition registry to resolve unknown URLs from the internet. |
disable_internet_access |
Prevent the definition registry from making any outgoing HTTP requests. |
Source code in fhircraft/fhir/resources/factory/core.py
build
build(structure_definition: Any = None, *, canonical_url: str | None = None, mixins: Sequence[type] | None = None, mode: Literal['auto', 'snapshot', 'differential'] = 'auto') -> type[BaseModel]
Constructs and returns a Pydantic model class based on a FHIR StructureDefinition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure_definition
|
Any
|
The FHIR StructureDefinition object to build the model from. |
None
|
canonical_url
|
str
|
The canonical URL of the StructureDefinition to retrieve from the registry. |
None
|
mixins
|
Sequence[type]
|
Additional mixin classes to include in the generated model. |
None
|
mode
|
Literal['auto', 'snapshot', 'differential']
|
The mode for building the model. "auto" selects the best mode automatically, "snapshot" uses the snapshot representation, and "differential" uses the differential representation. |
'auto'
|
Returns:
| Type | Description |
|---|---|
type[BaseModel]
|
type[BaseModel]: The constructed Pydantic model class. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If neither structure_definition nor canonical_url is provided, or if the canonical_url is not found in the registry. |
Notes
- Uses a cache to avoid rebuilding models for the same StructureDefinition URL.
- If both structure_definition and canonical_url are provided, structure_definition takes precedence.
Source code in fhircraft/fhir/resources/factory/core.py
register_package
register_package(package_name: str, version: str, skip_invalid: bool = False, include_dependencies: bool = True) -> None
Download and register all StructureDefinitions from a FHIR npm package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_name
|
str
|
Package identifier (e.g. |
required |
version
|
str
|
Package version string (e.g. |
required |
skip_invalid
|
bool
|
Whether to skip invalid StructureDefinitions. |
False
|
include_dependencies
|
bool
|
Whether to include dependencies when downloading the package. |
True
|
Source code in fhircraft/fhir/resources/factory/core.py
register
register(sd: StructureDefinition | StructureDefinition | StructureDefinition | dict) -> StructureDefinition | StructureDefinition | StructureDefinition
Register a StructureDefinition with the factory.
Accepts a typed StructureDefinition model instance or a plain dict. The normalised, validated SD instance is returned so callers can inspect it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sd
|
StructureDefinition | StructureDefinition | StructureDefinition | dict
|
A StructureDefinition model instance or a |
required |
Returns:
| Type | Description |
|---|---|
StructureDefinition | StructureDefinition | StructureDefinition
|
The normalised StructureDefinition instance that was stored. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If sd is neither a dict nor a StructureDefinition instance. |
Source code in fhircraft/fhir/resources/factory/core.py
unregister
unregister(url: str) -> None
Remove a StructureDefinition from the registry and evict it from the cache.
If url is not registered, the call is a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The canonical URL of the StructureDefinition to remove. |
required |
Source code in fhircraft/fhir/resources/factory/core.py
reset_cache
has_registered_definition
get_registered_definition
get_registered_definition(url: str) -> StructureDefinition | StructureDefinition | StructureDefinition
Retrieve a registered StructureDefinition by canonical URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The canonical URL of the StructureDefinition. |
required |
Returns:
| Type | Description |
|---|---|
StructureDefinition | StructureDefinition | StructureDefinition
|
The StructureDefinition instance stored in the registry. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If url is not registered. |
Source code in fhircraft/fhir/resources/factory/core.py
list_registered_definitions
Return all canonical URLs registered in the definition registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str | None
|
When provided, only URLs whose StructureDefinition has a matching
|
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of canonical URL strings. |
Source code in fhircraft/fhir/resources/factory/core.py
is_built
list_built
evict
evict(url: str) -> None
Remove a single entry from the construction cache.
If url is not cached, the call is a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Canonical URL of the model to evict. |
required |
Source code in fhircraft/fhir/resources/factory/core.py
rebuild
rebuild(url: str, *, mixins: Sequence[type] | None = None, mode: Literal['auto', 'snapshot', 'differential'] = 'auto') -> type[BaseModel]
Evict url from the cache and build a fresh model.
Useful when the underlying StructureDefinition has changed after the
initial build (e.g. after calling :meth:register again with an updated SD).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Canonical URL of the StructureDefinition to rebuild. |
required |
mixins
|
Sequence[type] | None
|
Optional mixin classes forwarded to :meth: |
None
|
mode
|
Literal['auto', 'snapshot', 'differential']
|
Build mode forwarded to :meth: |
'auto'
|
Returns:
| Type | Description |
|---|---|
type[BaseModel]
|
The newly constructed Pydantic model class. |
Source code in fhircraft/fhir/resources/factory/core.py
enable_internet_access
Allow the definition registry to resolve unknown URLs from the internet.
disable_internet_access
Prevent the definition registry from making any outgoing HTTP requests.
ElementNode
Path: fhircraft.fhir.resources.factory.element_node.ElementNode
dataclass
ElementNode(definition: ElementDefinition | ElementDefinition | ElementDefinition)
Immutable wrapper around a FHIR ElementDefinition that exposes a rich set of computed properties used throughout the factory pipeline.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ElementDefinition | ElementDefinition | ElementDefinition
|
|
required |
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Full element id (dot-separated, slices encoded with colon). |
id_segments |
list[str]
|
List of segments of |
id_ancestry |
list[str]
|
List of ancestor ids of |
path |
str
|
Element path (dot-separated, no slice names). |
depth |
int
|
Number of '.' separators in the id (root = 0). |
path_segments |
list[str]
|
List of segments of |
path_ancestry |
list[str]
|
List of ancestor segments of |
name |
str
|
Official element name |
local_id |
str
|
Leaf segment of id (may include |
parent_id |
str | None
|
id with the last |
is_root |
bool
|
Whether this element is a root element (has no parent). |
is_type_choice_slice |
bool
|
True when this element is a type-choice type-slice. |
is_slice |
bool
|
True when this element is a named slice definition. |
is_slice_entry |
bool
|
The first element that declares slicing is considered to be the slicing entry |
is_slice_child |
bool
|
True when any ancestor segment of the id contains a named-slice |
is_content_reference |
bool
|
True when |
slice_name |
str | None
|
The slice name (part after |
is_slicing_ordered |
bool
|
If elements must be in same order as slices |
slicing_rules |
Literal['openAtEnd', 'open', 'closed']
|
The slicing rules for this slice entry element, one of |
slice_ancestry |
list[str]
|
Names of all named ancestor slices in outermost-first order. |
base_min_cardinality |
int | None
|
Minimum cardinality of the base element when this node was produced by merging a differential element with its base. |
base_max_cardinality |
int | None
|
Maximum cardinality of the base element when this node was produced by merging a differential element with its base. |
base_is_array |
bool | None
|
Whether the base element is multi-valued and represented as a list ( |
min_cardinality |
int
|
Minimum cardinality (defaults to 0 when not specified). |
max_cardinality |
int | None
|
Maximum cardinality. |
is_required |
bool
|
True when |
is_prohibited |
bool
|
True when |
is_array |
bool | None
|
Whether this element is multi-valued and represented as a list ( |
types |
Sequence[ElementDefinitionType] | Sequence[ElementDefinitionType] | Sequence[ElementDefinitionType]
|
List of FHIR type codes from |
type_codes |
list[str]
|
List of FHIR type codes from |
is_polymorphic_type |
bool
|
Whether the element is polymorphic (a.k.a type-choice). |
profile_urls |
list[str]
|
All profile canonical URLs collected from |
documentation |
str
|
Full combination of the elemments's |
pattern |
The pattern[x] value for this element, if any. Returns |
|
fixed |
The fixed[x] value for this element, if any. Returns |
|
default_value |
The defaultValue[x] value for this element, if any. Returns |
|
min_value |
The minValue[x] value for this element, if any. Returns |
|
max_value |
The maxValue[x] value for this element, if any. Returns |
|
max_length |
int | None
|
The maxLength[x] value for this element, if any. Returns |
parent_id
property
parent_id: str | None
id with the last .segment removed. None for root-level elements.
Note: for a top-level slice like Observation.component:systolic the
parent_id is "Observation" (not "Observation.component"). This is
intentional — slices are accessed via :meth:DefinitionIndex.slices, never
via :meth:DefinitionIndex.children.
is_type_choice_slice
property
is_type_choice_slice: bool
True when this element is a type-choice type-slice.
Per the FHIR spec, when a polymorphic element (path ends in [x]) is
constrained to a specific type, the id reflects that type with a colon
suffix directly after the [x], e.g.
Patient.deceased[x]:deceasedBoolean.
This is distinct from a named list-slice such as
Observation.component:systolic where the colon follows a plain
element name.
is_slice
property
is_slice: bool
True when this element is a named slice definition.
A named slice has a colon in its :attr:local_id that is not
immediately preceded by [x], e.g.
Observation.component:systolic → local_id = "component:systolic".
Type-choice type-slices such as Patient.deceased[x]:deceasedBoolean
are not considered named slices; use :attr:is_type_choice_slice for
those.
is_slice_entry
property
is_slice_entry: bool
The first element that declares slicing is considered to be the slicing entry
is_slice_child
property
is_slice_child: bool
True when any ancestor segment of the id contains a named-slice colon — this element lives inside a named-slice sub-tree.
Type-choice colon suffixes ([x]:TypeName) are excluded; they are not
a slice ancestry boundary.
is_content_reference
property
is_content_reference: bool
True when definition.contentReference is set.
slice_name
property
slice_name: str | None
The slice name (part after : in :attr:local_id), or None if this
element is not a named slice or type-choice type-slice.
slicing_rules
property
slicing_rules: Literal['openAtEnd', 'open', 'closed']
The slicing rules for this slice entry element, one of "openAtEnd", "open", or "closed". Defaults to "open" when not specified.
slice_ancestry
property
Names of all named ancestor slices in outermost-first order.
Type-choice colon suffixes ([x]:TypeName) are excluded because they
denote a type specialisation, not a named list-slice boundary.
base_min_cardinality
property
base_min_cardinality: int | None
Minimum cardinality of the base element when this node was produced by merging a differential element with its base. None means this node was not produced by a merge (snapshot or root element).
base_max_cardinality
property
base_max_cardinality: int | None
Maximum cardinality of the base element when this node was produced by merging a differential element with its base. None means unbounded (*).).
base_is_array
property
base_is_array: bool | None
Whether the base element is multi-valued and represented as a list (max > 1 or *) when this node was produced by merging a differential element with its base. None means this node was not produced by a merge (snapshot or root element).
min_cardinality
property
min_cardinality: int
Minimum cardinality (defaults to 0 when not specified).
is_array
property
is_array: bool | None
Whether this element is multi-valued and represented as a list (max > 1 or *). Returns None if cardinality is not specified.
types
property
types: Sequence[ElementDefinitionType] | Sequence[ElementDefinitionType] | Sequence[ElementDefinitionType]
List of FHIR type codes from definition.type.
is_polymorphic_type
property
is_polymorphic_type: bool
Whether the element is polymorphic (a.k.a type-choice).
Note: If the element is polymorphic (has more than one datatype), then the end of the path for the element SHALL be "[x]" to designate that the name of the element may vary when serialized.
Type-choice slice nodes (e.g. Patient.deceased[x]:deceasedBoolean) are
not considered polymorphic — they represent a single concrete type
constraint and must not trigger type-choice synthesis in the index.
profile_urls
property
All profile canonical URLs collected from definition.type[*].profile.
documentation
property
documentation: str
Full combination of the elemments's short, definition, and comment fields, in
that order of preference. Returns an empty string if none of those fields are set.
Strings that contain no alphanumeric characters are treated as absent and the next candidate is tried instead.
pattern
property
The pattern[x] value for this element, if any. Returns None if no pattern is specified.
fixed
property
The fixed[x] value for this element, if any. Returns None if no fixed is specified.
default_value
property
The defaultValue[x] value for this element, if any. Returns None if no default is specified.
min_value
property
The minValue[x] value for this element, if any. Returns None if no minValue is specified.
max_value
property
The maxValue[x] value for this element, if any. Returns None if no maxValue is specified.
max_length
property
max_length: int | None
The maxLength[x] value for this element, if any. Returns None if no maxLength is specified.
DefinitionIndex
Path: fhircraft.fhir.resources.factory.index.DefinitionIndex
DefinitionIndex(nodes: list[ElementNode])
Indexed collection of :class:ElementNode objects keyed by element.id and element.path.
Methods:
| Name | Description |
|---|---|
from_elements |
Wrap each ElementDefinition in an :class: |
add |
Add an :class: |
update |
Add multiple :class: |
contains |
Check if an element node exists by id or path. |
get |
Get element node by id |
get_by_path |
Get element node by path, can return multiple matches |
get_single_by_path |
Get a single element node by path, raises an error if multiple matches are found. |
ids |
Sorted list of all element ids in this index. |
paths |
Set of all element paths in this index. |
root |
Return the single root element of this index. |
get_parent |
Return the parent of the element with id. |
get_children |
Return immediate non-slice children of id. |
get_slices |
Return the named slices defined under id. |
get_slice_children |
Convenience alias for :meth: |
get_subtree |
Return a new :class: |
Attributes:
| Name | Type | Description |
|---|---|---|
nodes |
list[ElementNode]
|
List of all nodes in this index. |
Source code in fhircraft/fhir/resources/factory/index.py
from_elements
classmethod
from_elements(elements: list[Any]) -> DefinitionIndex
Wrap each ElementDefinition in an :class:ElementNode and build the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elements
|
list[Any]
|
List of raw FHIR |
required |
Returns:
| Type | Description |
|---|---|
DefinitionIndex
|
A fully populated :class: |
Source code in fhircraft/fhir/resources/factory/index.py
add
add(node: ElementNode, replace: bool = False) -> None
Add an :class:ElementNode to this index.
Source code in fhircraft/fhir/resources/factory/index.py
update
update(nodes: list[ElementNode], replace: bool = False) -> None
Add multiple :class:ElementNode objects to this index.
contains
Check if an element node exists by id or path.
Source code in fhircraft/fhir/resources/factory/index.py
get
get(id: str, ignore_root: bool = False) -> ElementNode
Get element node by id
Source code in fhircraft/fhir/resources/factory/index.py
get_by_path
get_by_path(path: str, ignore_root: bool = False, ignore_slices: bool = False) -> List[ElementNode]
Get element node by path, can return multiple matches
Source code in fhircraft/fhir/resources/factory/index.py
get_single_by_path
get_single_by_path(path: str, ignore_root: bool = False, ignore_slices: bool = False) -> ElementNode
Get a single element node by path, raises an error if multiple matches are found.
Source code in fhircraft/fhir/resources/factory/index.py
ids
paths
root
root() -> ElementNode
Return the single root element of this index.
Source code in fhircraft/fhir/resources/factory/index.py
get_parent
get_parent(id: str) -> ElementNode
Return the parent of the element with id.
Source code in fhircraft/fhir/resources/factory/index.py
get_children
get_children(id: str) -> list[ElementNode]
Return immediate non-slice children of id.
Synthetic type-expansion nodes (e.g. Observation.valueQuantity
generated from Observation.value[x]) are excluded — the
:class:TypeChoiceFieldBuilder already handles the canonical
value[x] element and emits one typed field per type.
Source code in fhircraft/fhir/resources/factory/index.py
get_slices
get_slices(id: str) -> list[ElementNode]
Return the named slices defined under id.
Source code in fhircraft/fhir/resources/factory/index.py
get_slice_children
get_slice_children(slice_id: str) -> list[ElementNode]
Convenience alias for :meth:children when navigating inside a slice.
Returns immediate non-slice elements whose parent_id == slice_id.
Source code in fhircraft/fhir/resources/factory/index.py
get_subtree
get_subtree(id: str) -> DefinitionIndex
Return a new :class:DefinitionIndex scoped to id and all of
its descendants (children, slices, and their sub-elements).
The returned index is re-rooted: the matched element becomes the root
with an id equal to its capitalised :attr:~ElementNode.name
(e.g. Observation.component → Component), and all descendant
ids and paths are rewritten accordingly.
Source code in fhircraft/fhir/resources/factory/index.py
SnapshotResolver
Path: fhircraft.fhir.resources.factory.resolver.SnapshotResolver
SnapshotResolver(registry: StructureDefinitionRegistry)
Resolves a FHIR StructureDefinition into a complete :class:DefinitionIndex.
Methods:
| Name | Description |
|---|---|
resolve |
Resolve a StructureDefinition into a DefinitionIndex. |
Source code in fhircraft/fhir/resources/factory/resolver.py
resolve
resolve(sd: StructureDefinition | StructureDefinition | StructureDefinition, mode: Literal['auto', 'snapshot', 'differential'] = 'auto') -> DefinitionIndex
Resolve a StructureDefinition into a DefinitionIndex. This method resolves either the snapshot or differential representation of a StructureDefinition into a normalized DefinitionIndex. When mode is set to "auto", the method automatically selects the differential mode if available, otherwise uses snapshot mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sd
|
StructureDefinition | StructureDefinition | StructureDefinition
|
A FHIR StructureDefinition resource (R4, R4B, or R5 version). |
required |
mode
|
Literal['auto', 'snapshot', 'differential']
|
Resolution mode to use. Defaults to "auto". Options are: - "auto": Automatically selects "differential" if available, else "snapshot" - "snapshot": Uses the snapshot representation directly - "differential": Merges the differential over the base_index |
'auto'
|
Returns:
| Name | Type | Description |
|---|---|---|
DefinitionIndex |
DefinitionIndex
|
A resolved index of FHIR elements. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the selected mode's required elements are missing or contain None values. |
FactoryDefinitionResolutionError
|
If neither snapshot nor differential elements are available. |
Source code in fhircraft/fhir/resources/factory/resolver.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
get_type_choice_value_by_base
Retrieve the value of a type-choice field in an instance based on the field name starting with a specific base string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
object
|
The instance object to retrieve the value from. |
required |
base
|
str
|
The base string that the field name should start with. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
Any
|
The value of the first field found in the instance that starts with the specified base string,
or |
Source code in fhircraft/fhir/resources/validators.py
validate_FHIR_element_fixed_value
validate_FHIR_element_fixed_value(cls: Any, element: Union[FHIRBaseModel, List[FHIRBaseModel], Any], constant: Union[FHIRBaseModel, List[FHIRBaseModel], Any]) -> Any
Validate the FHIR element against a specified constant value and return the element if it fulfills the constant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Any
|
Placeholder for an argument that is not used in the function. |
required |
element
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The FHIR element to validate against the constant. |
required |
constant
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The constant value to validate the element against. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Union[FHIRBaseModel, List[FHIRBaseModel]]: The validated FHIR element. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the element does not fulfill the specified constant. |
Source code in fhircraft/fhir/resources/validators.py
validate_FHIR_element_pattern
validate_FHIR_element_pattern(cls: Any, element: Union[FHIRBaseModel, List[FHIRBaseModel], Any], pattern: Union[FHIRBaseModel, List[FHIRBaseModel], Any]) -> Any
Validate the FHIR element against a specified pattern and return the element if it fulfills the pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Any
|
Placeholder for an argument that is not used in the function. |
required |
element
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The FHIR element to validate against the pattern. |
required |
pattern
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The pattern to validate the element against. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Union[FHIRBaseModel, List[FHIRBaseModel]]: The validated FHIR element. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the element does not fulfill the specified pattern. |
Source code in fhircraft/fhir/resources/validators.py
validate_FHIR_model_fixed_value
validate_FHIR_model_fixed_value(model: Union[FHIRBaseModel, List[FHIRBaseModel], Any], constant: Union[FHIRBaseModel, List[FHIRBaseModel], Any]) -> Any
Validate the FHIR model against a specified constant value and return the model if it fulfills the constant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The FHIR model to validate against the constant. |
required |
constant
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The constant value to validate the model against. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Union[FHIRBaseModel, List[FHIRBaseModel]]: The validated FHIR element. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the element does not fulfill the specified constant. |
Source code in fhircraft/fhir/resources/validators.py
validate_FHIR_model_pattern
validate_FHIR_model_pattern(model: Union[FHIRBaseModel, List[FHIRBaseModel], Any], pattern: Union[FHIRBaseModel, List[FHIRBaseModel], Any]) -> Any
Validate the FHIR model against a specified pattern and return the model if it fulfills the pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The FHIR model to validate against the pattern. |
required |
pattern
|
Union[FHIRBaseModel, List[FHIRBaseModel]]
|
The pattern to validate the model against. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Union[FHIRBaseModel, List[FHIRBaseModel]]: The validated FHIR model. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the model does not fulfill the specified pattern. |
Source code in fhircraft/fhir/resources/validators.py
validate_element_constraint
validate_element_constraint(instance: T, elements: Sequence[str], expression: str, human: str, key: str, severity: str) -> T
Validates a FHIR element constraint based on a FHIRPath expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The instance to be validated. |
required |
elements
|
Sequence[str]
|
The elements to be validated. |
required |
expression
|
str
|
The FHIRPath expression to evaluate. |
required |
human
|
str
|
A human-readable description of the constraint. |
required |
key
|
str
|
The key associated with the constraint. |
required |
severity
|
str
|
The severity level of the constraint ('warning' or 'error'). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
T
|
The validated value. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the validation fails and severity is not |
Warning
|
If the validation fails and severity is |
Source code in fhircraft/fhir/resources/validators.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
validate_model_constraint
Validates a FHIR model constraint based on a FHIRPath expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
Instance of the model to be validated. |
required |
expression
|
str
|
The FHIRPath expression to evaluate. |
required |
human
|
str
|
A human-readable description of the constraint. |
required |
key
|
str
|
The key associated with the constraint. |
required |
severity
|
str
|
The severity level of the constraint ('warning' or 'error'). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
instance |
type[T]
|
The validated model instance. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If the validation fails and severity is not |
Warning
|
If the validation fails and severity is |
Source code in fhircraft/fhir/resources/validators.py
validate_slicing_cardinalities
validate_slicing_cardinalities(cls: Any, values: List[Any] | None, field_name: str) -> List[FHIRSliceModel] | None
Validates the cardinalities of FHIR slices for a specific field within a FHIR resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Any
|
The Pydantic FHIR model class. |
required |
values
|
List[Any]
|
List of values for the field. |
required |
field_name
|
str
|
The name of the field to validate. |
required |
Returns:
| Type | Description |
|---|---|
List[FHIRSliceModel] | None
|
List[FHIRSliceModel]: The validated list of values. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If cardinality constraints are violated for any slice. |
Source code in fhircraft/fhir/resources/validators.py
validate_type_choice_element
validate_type_choice_element(instance: T, field_types: List[Any], field_name_base: str, required: bool = False, non_allowed_types=[]) -> T
Validate the type choice element for a given instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The instance to validate. |
required |
field_types
|
List[Any]
|
List of field types to check. |
required |
field_name_base
|
str
|
Base name of the field. |
required |
required
|
bool
|
Whether the type choice element is required. |
False
|
non_allowed_types
|
List[Any] | None
|
List of types that are not allowed for this element (for negative checks). |
[]
|
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
PydanticCustomError
|
If more than one value is set for the type choice element or if a non-allowed type is set. |
Source code in fhircraft/fhir/resources/validators.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |