FHIR Model Factory
Main class and utilities for dynamically constructing FHIR resource models.
ConstructionMode
Path: fhircraft.fhir.resources.factory.ConstructionMode
ResourceFactory
Path: fhircraft.fhir.resources.factory.ResourceFactory
ResourceFactory(repository: Optional[CompositeStructureDefinitionRepository] = None, internet_enabled: bool = True, enable_packages: bool = True, registry_base_url: Optional[str] = None, timeout: float = 30.0)
Factory for constructing Pydantic models from FHIR StructureDefinitions.
The ResourceFactory provides functionality to
- Load StructureDefinitions from various sources (files, directories, dictionaries)
- Load FHIR packages from package registries
- Construct Pydantic models from StructureDefinitions
- Cache constructed models for performance
- Manage internet access and package registry configuration
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repository
|
Optional[CompositeStructureDefinitionRepository]
|
Custom repository to use. If None, creates a default CompositeStructureDefinitionRepository |
None
|
internet_enabled
|
bool
|
Whether to enable internet access for downloading definitions |
True
|
enable_packages
|
bool
|
Whether to enable FHIR package support |
True
|
registry_base_url
|
Optional[str]
|
Base URL for the FHIR package registry |
None
|
timeout
|
float
|
Request timeout in seconds for package downloads |
30.0
|
Classes:
| Name | Description |
|---|---|
FactoryConfig |
Represents the configuration for the Factory class. |
Methods:
| Name | Description |
|---|---|
configure_repository |
Configure the factory repository with various sources. |
disable_internet_access |
Toggle offline mode (disable internet access) to avoid external requests. |
enable_internet_access |
Toggle online mode (enable internet access) to allow external requests. |
load_definitions_from_directory |
Load FHIR structure definitions from the specified directory. |
load_definitions_from_files |
Loads resource definitions from the specified file paths into the repository. |
load_definitions_from_list |
Loads resource definitions into the repository from a list of definition dictionaries. |
load_package |
Load a FHIR package and return loaded structure definitions. |
get_loaded_packages |
Get dictionary of loaded FHIR packages (name -> version). |
has_package |
Check if a package is loaded. |
remove_package |
Remove a loaded package. |
set_registry_base_url |
Set the FHIR package registry base URL. |
clear_package_cache |
Clear the package cache. |
resolve_structure_definition |
Resolve structure definition using the repository. |
construct_resource_model |
Constructs a Pydantic model based on the provided FHIR structure definition. |
clear_cache |
Clears the factory cache. |
Attributes:
| Name | Type | Description |
|---|---|---|
in_snapshot_mode |
bool
|
Check if the factory is in snapshot construction mode. |
in_differential_mode |
bool
|
Check if the factory is in differential construction mode. |
Source code in fhircraft/fhir/resources/factory.py
in_snapshot_mode
property
in_snapshot_mode: bool
Check if the factory is in snapshot construction mode.
in_differential_mode
property
in_differential_mode: bool
Check if the factory is in differential construction mode.
FactoryConfig
Path: fhircraft.fhir.resources.factory.ResourceFactory.FactoryConfig
Represents the configuration for the Factory class.
Attributes:
| Name | Type | Description |
|---|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
FHIR_release
|
str
|
|
required |
FHIR_version
|
str
|
|
required |
construction_mode
|
ConstructionMode
|
|
<ConstructionMode.AUTO: 'auto'>
|
configure_repository
configure_repository(directory: Optional[Union[str, Path]] = None, files: Optional[List[Union[str, Path]]] = None, definitions: Optional[List[Dict[str, Any]]] = None, packages: Optional[List[Union[str, Tuple[str, str]]]] = None, internet_enabled: bool = True, registry_base_url: Optional[str] = None) -> None
Configure the factory repository with various sources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Optional[Union[str, Path]]
|
Directory containing structure definition files |
None
|
files
|
Optional[List[Union[str, Path]]]
|
List of individual structure definition files to load |
None
|
definitions
|
Optional[List[Dict[str, Any]]]
|
List of structure definition dictionaries to load |
None
|
packages
|
Optional[List[Union[str, Tuple[str, str]]]]
|
List of FHIR packages to load. Each can be a package name (string) or a tuple of (package_name, version) |
None
|
internet_enabled
|
bool
|
Whether to enable internet access |
True
|
registry_base_url
|
Optional[str]
|
Base URL for the package registry |
None
|
Source code in fhircraft/fhir/resources/factory.py
disable_internet_access
Toggle offline mode (disable internet access) to avoid external requests.
enable_internet_access
load_definitions_from_directory
Load FHIR structure definitions from the specified directory.
This method attempts to load structure definitions into the repository from the given directory path.
If the underlying repository supports loading from a directory (i.e., implements load_from_directory),
the method delegates the loading process to it. Otherwise, a NotImplementedError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
Union[str, Path]
|
The path to the directory containing structure definitions. |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the repository does not support loading from a directory. |
Source code in fhircraft/fhir/resources/factory.py
load_definitions_from_files
Loads resource definitions from the specified file paths into the repository.
This method delegates the loading process to the repository's load_from_files method,
if it exists. If the repository does not support loading from files, a NotImplementedError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*file_paths
|
Union[str, Path]
|
One or more file paths from which to load resource definitions. |
()
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the repository does not support loading from files. |
Source code in fhircraft/fhir/resources/factory.py
load_definitions_from_list
Loads resource definitions into the repository from a list of definition dictionaries.
This method forwards the provided definitions to the repository's load_from_definitions
method if it exists. If the repository does not support loading from definitions,
a NotImplementedError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*definitions
|
Dict[str, Any]
|
One or more resource definition dictionaries to load. |
()
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the repository does not support loading from definitions. |
Source code in fhircraft/fhir/resources/factory.py
load_package
Load a FHIR package and return loaded structure definitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_name
|
str
|
Name of the package (e.g., "hl7.fhir.us.core") |
required |
version
|
Optional[str]
|
Version of the package (defaults to latest) |
None
|
Returns:
| Type | Description |
|---|---|
None
|
List of StructureDefinition objects that were loaded |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If package support is not enabled in the repository |
Source code in fhircraft/fhir/resources/factory.py
get_loaded_packages
has_package
Check if a package is loaded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_name
|
str
|
Name of the package |
required |
version
|
Optional[str]
|
Version of the package (if None, checks any version) |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if package is loaded |
Source code in fhircraft/fhir/resources/factory.py
remove_package
Remove a loaded package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_name
|
str
|
Name of the package |
required |
version
|
Optional[str]
|
Version of the package (if None, removes all versions) |
None
|
Source code in fhircraft/fhir/resources/factory.py
set_registry_base_url
set_registry_base_url(base_url: str) -> None
Set the FHIR package registry base URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
The base URL for the package registry |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If package support is not enabled in the repository |
Source code in fhircraft/fhir/resources/factory.py
clear_package_cache
resolve_structure_definition
resolve_structure_definition(canonical_url: str, version: str | None = None) -> StructureDefinition | StructureDefinition | StructureDefinition
Resolve structure definition using the repository.
Source code in fhircraft/fhir/resources/factory.py
construct_resource_model
construct_resource_model(canonical_url: str | None = None, structure_definition: str | dict | StructureDefinition | StructureDefinition | StructureDefinition | None = None, base_model: type[ModelT] | None = None, mode: ConstructionMode | str = AUTO, mixins: Sequence[type] | None = None, fhir_release: Literal['DSTU2', 'STU3', 'R4', 'R4B', 'R5', 'R6'] | None = None) -> type[ModelT | BaseModel]
Constructs a Pydantic model based on the provided FHIR structure definition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
canonical_url
|
str | None
|
The FHIR resource's or profile's canonical URL from which to download the StructureDefinition. |
None
|
structure_definition
|
str | dict | StructureDefinition | StructureDefinition | StructureDefinition | None
|
The FHIR StructureDefinition to build the model from specified as a filename or as a dictionary. |
None
|
base_model
|
type[ModelT] | None
|
Optional base model to inherit from (overrides baseDefinition in differential mode). |
None
|
mode
|
ConstructionMode | str
|
Construction mode (SNAPSHOT, DIFFERENTIAL, or AUTO). Defaults to AUTO which auto-detects. |
AUTO
|
mixins
|
Sequence[type] | None
|
Optional sequence of mixin classes to include in the model. |
None
|
fhir_release
|
Literal['DSTU2', 'STU3', 'R4', 'R4B', 'R5', 'R6'] | None
|
Optional FHIR release version ("DSTU2", "STU3", "R4", "R4B", "R5", "R6") to use for model construction. |
None
|
Returns:
| Type | Description |
|---|---|
type[ModelT | BaseModel]
|
The constructed Pydantic model representing the FHIR resource. |
Source code in fhircraft/fhir/resources/factory.py
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 | |
ResourceFactoryValidators
Path: fhircraft.fhir.resources.factory.ResourceFactoryValidators
Container for resource-level validators.
Methods:
| Name | Description |
|---|---|
add_model_constraint_validator |
Adds a model constraint validator based on the provided constraint. |
add_element_constraint_validator |
Adds a validator for a specific element constraint to the validators dictionary. |
add_slicing_validator |
Adds a validator to ensure that slicing rules are followed for sliced elements. |
add_type_choice_validator |
Adds a validator to ensure that the field's value matches one of the allowed types. |
add_model_constraint_validator
add_model_constraint_validator(constraint: ElementDefinitionConstraint | ElementDefinitionConstraint | ElementDefinitionConstraint)
Adds a model constraint validator based on the provided constraint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraint
|
dict
|
The constraint details including expression, human-readable description, key, and severity. |
required |
Source code in fhircraft/fhir/resources/factory.py
add_element_constraint_validator
add_element_constraint_validator(field: str, constraint: ElementDefinitionConstraint | ElementDefinitionConstraint | ElementDefinitionConstraint, base: Any)
Adds a validator for a specific element constraint to the validators dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
The field to validate. |
required |
constraint
|
dict
|
The details of the constraint including expression, human-readable description, key, and severity. |
required |
base
|
Any
|
The base model to check for existing validators. |
required |
Source code in fhircraft/fhir/resources/factory.py
add_slicing_validator
add_slicing_validator(field: str)
Adds a validator to ensure that slicing rules are followed for sliced elements.
Source code in fhircraft/fhir/resources/factory.py
add_type_choice_validator
add_type_choice_validator(field: str, allowed_types: List[Union[str, type]], forbidden_types: List[Union[str, type]], required: bool = False)
Adds a validator to ensure that the field's value matches one of the allowed types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
The field to validate. |
required |
allowed_types
|
List[Union[str, type]]
|
List of allowed types for the field. |
required |
required
|
bool
|
Whether the field is required. Defaults to |
False
|
Source code in fhircraft/fhir/resources/factory.py
StructureNode
Path: fhircraft.fhir.resources.factory.StructureNode
Bases: BaseModel
A node in the ElementDefinition tree structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str | None
|
|
None
|
path
|
str | None
|
|
None
|
node_label
|
str
|
|
required |
children
|
Dict[str, StructureNode]
|
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'>
|
slices
|
Dict[str, StructureNode]
|
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'>
|
root
|
StructureNode | None
|
|
None
|
definition
|
ElementDefinition | ElementDefinition | ElementDefinition | None
|
|
None
|
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 |
|---|---|
AssertionError
|
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 |
|---|---|
AssertionError
|
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 |
|---|---|
AssertionError
|
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 |
|---|---|
AssertionError
|
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 |
|---|---|
AssertionError
|
If the validation fails and severity is not |
Warning
|
If the validation fails and severity is |
Source code in fhircraft/fhir/resources/validators.py
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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
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 |
|---|---|
AssertionError
|
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: List[Any] | None = None) -> 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). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If more than one value is set for the type choice element or if a non-allowed type is set. |