Skip to content

Base FHIR Models

These classes provide base for constructing Fhircraft-compatible Pydantic FHIR models.

FHIRContextMixin

Path: fhircraft.fhir.resources.base.mixins.context.FHIRContextMixin

Mixin that provides hierarchical parent-context tracking.

Every FHIR model instance stores a reference to its direct parent (_parent) and its position within a list (_index). The root resource and nearest enclosing resource are resolved lazily by walking the parent chain, avoiding the need to store and update those references.

FHIRPolymorphicMixin

Path: fhircraft.fhir.resources.base.mixins.polymorphic.FHIRPolymorphicMixin

Mixin providing polymorphic serialization and deserialization helpers.

These are helpers called from the Pydantic validators/serializers that remain on FHIRBaseModel; they are not validators themselves and carry no Pydantic decorator magic.

FHIRXMLMixin

Path: fhircraft.fhir.resources.base.mixins.xml.FHIRXMLMixin

Mixin providing XML serialization and deserialization for FHIR models.

Implements the FHIR XML format as described in the FHIR specification, including correct handling of primitive shadow elements and namespace.

Methods:

Name Description
model_dump_xml

Serialize the FHIR resource to an XML string.

model_validate_xml

Deserialize a FHIR XML string into a model instance.

model_dump_xml

model_dump_xml(*, indent: int | None = None, ensure_ascii: bool = True, include: IncEx | None = None, exclude: IncEx | None = None, exclude_unset: bool = False, exclude_none: bool = False, exclude_defaults: bool = False) -> str

Serialize the FHIR resource to an XML string.

Parameters:

Name Type Description Default
indent int | None

Number of indent levels. None produces compact output.

None
ensure_ascii bool

When True, non-ASCII characters are escaped.

True
include IncEx | None

Fields to include (passed through to model_dump).

None
exclude IncEx | None

Fields to exclude (passed through to model_dump).

None
exclude_unset bool

Exclude fields that were not explicitly set.

False
exclude_none bool

Exclude fields whose value is None.

False
exclude_defaults bool

Exclude fields that equal their default value.

False

Returns:

Type Description
str

An XML string conforming to the FHIR XML format.

Source code in fhircraft/fhir/resources/base/mixins/xml.py
def model_dump_xml(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = True,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    exclude_unset: bool = False,
    exclude_none: bool = False,
    exclude_defaults: bool = False,
) -> str:
    """
    Serialize the FHIR resource to an XML string.

    Args:
        indent: Number of indent levels.  ``None`` produces compact output.
        ensure_ascii: When True, non-ASCII characters are escaped.
        include: Fields to include (passed through to model_dump).
        exclude: Fields to exclude (passed through to model_dump).
        exclude_unset: Exclude fields that were not explicitly set.
        exclude_none: Exclude fields whose value is None.
        exclude_defaults: Exclude fields that equal their default value.

    Returns:
        An XML string conforming to the FHIR XML format.
    """
    root_el = self._serialize_as_xml(
        name=self._type,  # type: ignore[attr-defined]
        include=include,
        exclude=exclude,
        exclude_unset=exclude_unset,
        exclude_none=exclude_none,
        exclude_defaults=exclude_defaults,
    )
    tree = xml.ElementTree(root_el)
    if indent is not None:
        xml.indent(tree, space="  " * indent)
    return xml.tostring(
        root_el,
        encoding="unicode" if ensure_ascii else "unicode",
        xml_declaration=True,
    )

model_validate_xml classmethod

model_validate_xml(xml_data: str, *, strict: bool | None = None, context: Any = None) -> T

Deserialize a FHIR XML string into a model instance.

Parameters:

Name Type Description Default
xml_data str

The XML string to deserialize.

required
strict bool | None

Whether to validate strictly.

None
context Any

Additional context forwarded to model_validate.

None

Returns:

Type Description
T

A validated model instance populated from the XML data.

Source code in fhircraft/fhir/resources/base/mixins/xml.py
@classmethod
def model_validate_xml(
    cls: Type[T],
    xml_data: str,
    *,
    strict: bool | None = None,
    context: Any = None,
) -> T:
    """
    Deserialize a FHIR XML string into a model instance.

    Args:
        xml_data: The XML string to deserialize.
        strict: Whether to validate strictly.
        context: Additional context forwarded to model_validate.

    Returns:
        A validated model instance populated from the XML data.
    """
    root_el = xml.fromstring(xml_data)
    data = cls._parse_xml_to_dict(root_el)
    inner = next(iter(data.values()), {})
    return cls.model_validate(inner, strict=strict, context=context)  # type: ignore[attr-defined]

T module-attribute

T = TypeVar('T', bound='FHIRXMLMixin')

FHIRBaseModel

Path: fhircraft.fhir.resources.base.models.FHIRBaseModel

Bases: BaseModel, ABC, FHIRContextMixin, FHIRXMLMixin, FHIRPolymorphicMixin, FHIRPathMixin

Abstract base class for all FHIR resource and data-type models.

Extends Pydantic's BaseModel with FHIR-specific behaviour: - Hierarchical parent-context tracking (_parent / _index) - Polymorphic serialization and deserialization - XML serialization and deserialization - Profile-slice construction and introspection - FHIRPath expression evaluation (via FHIRPathMixin)

This class is abstract and may not be instantiated directly. All concrete FHIR types are generated subclasses that define _type.

Methods:

Name Description
model_post_init

Wire up parent-context tracking after construction.

model_validate

Validate obj and return a model instance.

model_validate_json

Deserialize json_data and return a validated model instance.

model_construct

Construct a model instance without running validation.

model_copy

Return a copy of this instance with parent context reset.

model_post_init

model_post_init(context: Any) -> None

Wire up parent-context tracking after construction.

Source code in fhircraft/fhir/resources/base/models.py
def model_post_init(self, context: Any) -> None:
    """Wire up parent-context tracking after construction."""
    self._set_resource_context()

model_validate classmethod

model_validate(obj: Any, *, strict: bool | None = None, from_attributes: bool | None = None, context: Any = None, extra: ExtraValues | None = None, by_alias: bool | None = None, by_name: bool | None = None) -> Self

Validate obj and return a model instance.

Source code in fhircraft/fhir/resources/base/models.py
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: Any = None,
    extra: ExtraValues | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate *obj* and return a model instance."""
    if by_alias is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate does not support by_alias. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    if extra is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate does not support extra. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    if by_name is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate does not support by_name. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    return super().model_validate(
        obj, strict=strict, from_attributes=from_attributes, context=context
    )

model_validate_json classmethod

model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = False, context: Any = None, extra: ExtraValues | None = None, by_alias: bool | None = None, by_name: bool | None = None) -> Self

Deserialize json_data and return a validated model instance.

Source code in fhircraft/fhir/resources/base/models.py
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = False,
    context: Any = None,
    extra: ExtraValues | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Deserialize *json_data* and return a validated model instance."""
    if by_alias is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate_json does not support by_alias. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    if extra is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate_json does not support extra. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    if by_name is not None:
        warnings.warn(
            "FHIRBaseModel.model_validate_json does not support by_name. Ignoring.",
            UserWarning,
            stacklevel=2,
        )
    return super().model_validate_json(json_data, strict=strict, context=context)

model_construct classmethod

model_construct(set_defaults: bool = True, *args: Any, **kwargs: Any) -> Self

Construct a model instance without running validation.

Parameters:

Name Type Description Default
set_defaults bool

When True (default), fields with a default value or factory are pre-populated.

True

Returns:

Type Description
Self

An unvalidated instance of the model.

Source code in fhircraft/fhir/resources/base/models.py
@classmethod
def model_construct(
    cls, set_defaults: bool = True, *args: Any, **kwargs: Any
) -> Self:
    """
    Construct a model instance without running validation.

    Args:
        set_defaults: When True (default), fields with a default value or
            factory are pre-populated.

    Returns:
        An unvalidated instance of the model.
    """
    instance = super().model_construct(*args, **kwargs)
    if not set_defaults:
        instance._set_resource_context()
        return instance

    for field_name, field in cls.model_fields.items():
        if getattr(instance, field_name, None) is not None:
            continue
        if field.default not in (PydanticUndefined, None):
            setattr(instance, field_name, copy(field.default))
        elif field.default_factory not in (PydanticUndefined, None):
            setattr(instance, field_name, field.default_factory())  # type: ignore[call-arg]

    instance._set_resource_context()
    return instance

model_copy

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self

Return a copy of this instance with parent context reset.

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Optional field updates to apply to the copy.

None
deep bool

Whether to perform a deep copy.

False

Returns:

Type Description
Self

A copied instance with no parent context.

Source code in fhircraft/fhir/resources/base/models.py
def model_copy(
    self, *, update: Mapping[str, Any] | None = None, deep: bool = False
) -> Self:
    """
    Return a copy of this instance with parent context reset.

    Args:
        update: Optional field updates to apply to the copy.
        deep: Whether to perform a deep copy.

    Returns:
        A copied instance with no parent context.
    """
    copied: Self = BaseModel.model_copy(self, update=update, deep=deep)  # type: ignore[arg-type]
    copied._set_resource_context()
    return copied

FHIRList

Path: fhircraft.fhir.resources.base.models.FHIRList

FHIRList(items: Iterable[Any] | None = None, parent: FHIRBaseModel | None = None)

Bases: list

Custom list wrapper that maintains parent context on mutations.

This list automatically propagates _parent, _root_resource, _resource, and _index context to FHIRBaseModel items when they are added via append, extend, insert, or setitem.

Parameters:

Name Type Description Default
items Iterable[Any] | None

Initial items for the list.

None
parent FHIRBaseModel | None

The parent FHIRBaseModel instance that owns this list.

None

Methods:

Name Description
append

Append item and propagate context.

extend

Extend list and propagate context to new items.

insert

Insert item and propagate context.

Source code in fhircraft/fhir/resources/base/models.py
def __init__(
    self, items: Iterable[Any] | None = None, parent: FHIRBaseModel | None = None
):
    """Initialize FHIRList with items and context.

    Args:
        items: Initial items for the list.
        parent: The parent FHIRBaseModel instance that owns this list.
    """
    super().__init__(items or [])
    self._parent = parent
    self._propagate_context()

append

append(item: Any)

Append item and propagate context.

Source code in fhircraft/fhir/resources/base/models.py
def append(self, item: Any):
    """Append item and propagate context."""
    super().append(item)
    if isinstance(item, FHIRBaseModel):
        object.__setattr__(item, "_parent", self._parent)
        object.__setattr__(item, "_index", len(self) - 1)

extend

extend(items: Iterable[Any])

Extend list and propagate context to new items.

Source code in fhircraft/fhir/resources/base/models.py
def extend(self, items: Iterable[Any]):
    """Extend list and propagate context to new items."""
    start_index = len(self)
    super().extend(items)
    for offset, item in enumerate(items):
        if isinstance(item, FHIRBaseModel):
            object.__setattr__(item, "_parent", self._parent)
            object.__setattr__(item, "_index", start_index + offset)

insert

insert(index: SupportsIndex, item: Any)

Insert item and propagate context.

Source code in fhircraft/fhir/resources/base/models.py
def insert(self, index: SupportsIndex, item: Any):
    """Insert item and propagate context."""
    super().insert(index, item)
    if isinstance(item, FHIRBaseModel):
        object.__setattr__(item, "_parent", self._parent)
        object.__setattr__(item, "_index", index)
    # Re-index all items after insertion point
    for i in range(int(index) + 1, len(self)):
        if isinstance(self[i], FHIRBaseModel):
            object.__setattr__(self[i], "_index", i)

FHIRModelKind

Path: fhircraft.fhir.resources.base.models.FHIRModelKind

Bases: str, Enum

Enumeration of FHIR StructureDefinition kinds.

FHIRSliceModel

Path: fhircraft.fhir.resources.base.models.FHIRSliceModel

Bases: FHIRBaseModel

Base class for representation of FHIR profiled slices as Pydantic objects.

Expands the FHIRBaseModel class with slice-specific methods.

Base64BinaryBase

Path: fhircraft.fhir.resources.base.primitives.Base64BinaryBase

Base64BinaryBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR base64Binary types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

BooleanBase

Path: fhircraft.fhir.resources.base.primitives.BooleanBase

BooleanBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR boolean types

Parameters:

Name Type Description Default
value bool | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

CanonicalBase

Path: fhircraft.fhir.resources.base.primitives.CanonicalBase

CanonicalBase(__value: Any | None = None, **data)

Bases: UriBase

A release-independent base metaclass for FHIR canonical types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

CodeBase

Path: fhircraft.fhir.resources.base.primitives.CodeBase

CodeBase(__value: Any | None = None, **data)

Bases: StringBase

A release-independent base metaclass for FHIR code types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

DateBase

Path: fhircraft.fhir.resources.base.primitives.DateBase

DateBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR date types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

DateTimeBase

Path: fhircraft.fhir.resources.base.primitives.DateTimeBase

DateTimeBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR dateTime types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

DecimalBase

Path: fhircraft.fhir.resources.base.primitives.DecimalBase

DecimalBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR decimal types

Parameters:

Name Type Description Default
value float | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

FHIRPrimitiveModel

Path: fhircraft.fhir.resources.base.primitives.FHIRPrimitiveModel

FHIRPrimitiveModel(__value: Any | None = None, **data)

Bases: FHIRBaseModel

Base class for FHIR primitive types.

FHIR primitives are represented as Pydantic models with a single value field that holds the actual primitive value. This design allows us to attach extensions to primitive values while still treating them as simple types in most contexts.

Parameters:

Name Type Description Default
value Any | None

The actual value

None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

IdBase

Path: fhircraft.fhir.resources.base.primitives.IdBase

IdBase(__value: Any | None = None, **data)

Bases: StringBase

A release-independent base metaclass for FHIR id types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

InstantBase

Path: fhircraft.fhir.resources.base.primitives.InstantBase

InstantBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR instant types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

Integer64Base

Path: fhircraft.fhir.resources.base.primitives.Integer64Base

Integer64Base(__value: Any | None = None, **data)

Bases: IntegerBase

A release-independent base metaclass for FHIR integer64 types (R5)

Parameters:

Name Type Description Default
value int | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

IntegerBase

Path: fhircraft.fhir.resources.base.primitives.IntegerBase

IntegerBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR integer types

Parameters:

Name Type Description Default
value int | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

MarkdownBase

Path: fhircraft.fhir.resources.base.primitives.MarkdownBase

MarkdownBase(__value: Any | None = None, **data)

Bases: StringBase

A release-independent base metaclass for FHIR markdown types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

OidBase

Path: fhircraft.fhir.resources.base.primitives.OidBase

OidBase(__value: Any | None = None, **data)

Bases: UriBase

A release-independent base metaclass for FHIR oid types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

PositiveIntBase

Path: fhircraft.fhir.resources.base.primitives.PositiveIntBase

PositiveIntBase(__value: Any | None = None, **data)

Bases: IntegerBase

A release-independent base metaclass for FHIR positiveInt types

Parameters:

Name Type Description Default
value int | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

StringBase

Path: fhircraft.fhir.resources.base.primitives.StringBase

StringBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR string types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

TimeBase

Path: fhircraft.fhir.resources.base.primitives.TimeBase

TimeBase(__value: Any | None = None, **data)

Bases: FHIRPrimitiveModel

A release-independent base metaclass for FHIR time types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

UnsignedIntBase

Path: fhircraft.fhir.resources.base.primitives.UnsignedIntBase

UnsignedIntBase(__value: Any | None = None, **data)

Bases: IntegerBase

A release-independent base metaclass for FHIR unsignedInt types

Parameters:

Name Type Description Default
value int | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

UriBase

Path: fhircraft.fhir.resources.base.primitives.UriBase

UriBase(__value: Any | None = None, **data)

Bases: StringBase

A release-independent base metaclass for FHIR uri types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

UrlBase

Path: fhircraft.fhir.resources.base.primitives.UrlBase

UrlBase(__value: Any | None = None, **data)

Bases: UriBase

A release-independent base metaclass for FHIR url types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

UuidBase

Path: fhircraft.fhir.resources.base.primitives.UuidBase

UuidBase(__value: Any | None = None, **data)

Bases: UriBase

A release-independent base metaclass for FHIR uuid types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)

XhtmlBase

Path: fhircraft.fhir.resources.base.primitives.XhtmlBase

XhtmlBase(__value: Any | None = None, **data)

Bases: StringBase

A release-independent base metaclass for FHIR xhtml types

Parameters:

Name Type Description Default
value str | None
None
Source code in fhircraft/fhir/resources/base/primitives.py
def __init__(self, __value: Any | None = None, **data):
    if __value is not None:
        data.setdefault("value", __value)
    super().__init__(**data)