-
Notifications
You must be signed in to change notification settings - Fork 1
[GPCAPIM-305]: Create common Pydantic FHIR types #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
davidhamill1-nhs
wants to merge
48
commits into
main
Choose a base branch
from
feature/GPCAPIM-305_common_fhir_package
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
48 commits
Select commit
Hold shift + click to select a range
a0bfa0a
Bring Pydantic in to tools.
davidhamill1-nhs 3de16a9
First step towards using Pydantic.
davidhamill1-nhs 4f2a258
Remove unused helper functions.
davidhamill1-nhs d8d1554
Use Pydantic FHIR types in SDS client.
davidhamill1-nhs 4359fc4
Use Pydantic FHIR types in tests.
davidhamill1-nhs faa30e9
Apply review comment for PR 275 from JW - move response behaviour out…
davidhamill1-nhs 07c3717
Build Pydantic Parameter type.
davidhamill1-nhs 5384442
Remove unused TypedDict FHIR types.
davidhamill1-nhs 0c9cdf2
import fhir resources from package __init__
davidhamill1-nhs f923cf0
Restructure files.
davidhamill1-nhs 9764e00
Add docs.
davidhamill1-nhs c7b1113
Add/restructure unit tests.
davidhamill1-nhs 83e723c
Tidy up TODO.
davidhamill1-nhs b51aeb9
Export response class from module __init__.py
davidhamill1-nhs 62e7bb6
Correct typing.
davidhamill1-nhs 3922a42
Tidying up.
davidhamill1-nhs a48a423
Clean up error handling.
davidhamill1-nhs c379388
Rename expression to better express what is being returned.
davidhamill1-nhs 90f09b8
Verify certs as aprt of contract testing.
davidhamill1-nhs 34f6599
Actually mirror headers back.
davidhamill1-nhs 324e47d
Only mirror trace id header
davidhamill1-nhs 4282ba7
Only mirror trace id header
davidhamill1-nhs dd454d2
correct the import statement to reflect the changes to the structure.
davidhamill1-nhs c1544b1
URL needs to point at correct version.
davidhamill1-nhs 1131cae
No need to return empty string here.
davidhamill1-nhs 006f3be
Remove unnecessary import.
davidhamill1-nhs 84caa3b
Correct doc string to accurately document behaviour.
davidhamill1-nhs 8e452a5
Resolve import issues from merge coflict resolutions.
davidhamill1-nhs 21be3ef
Correct version in docstring.
davidhamill1-nhs dcaeb9b
I messed up the merge conflict resolution.
davidhamill1-nhs dad9d76
typo.
davidhamill1-nhs 58484e2
Merge remote-tracking branch 'origin/main' into feature/GPCAPIM-305_c…
davidhamill1-nhs e2ec5f4
API name is not required for unit tests.
davidhamill1-nhs 0d8db54
Don't remove apim's pytest library.'
davidhamill1-nhs 43ad610
Provide correct commands for test runs.
davidhamill1-nhs 2a4cf54
Pull out nested elements.
davidhamill1-nhs afd113e
update poetry lock.
davidhamill1-nhs 61a71b2
Correct typing ignore.
davidhamill1-nhs 36305e8
Pull out nested elements.
davidhamill1-nhs 43542d8
Make explicit what the API will accept, even if not required.
davidhamill1-nhs 193b8a4
Pull out nested elements.
davidhamill1-nhs a75613a
Pull out nested elements.
davidhamill1-nhs 167cb3d
Pull out nested elements.
davidhamill1-nhs d256768
Remove duplicate identifiers.
davidhamill1-nhs f0c2149
Removed mixed uses of versions.
davidhamill1-nhs 053b993
Bring the JWT fields in to the fold.
davidhamill1-nhs d98453c
Remove duplicated call to fixture.
davidhamill1-nhs cb16bda
Remove unnecessary type declaration.
davidhamill1-nhs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,5 +2,6 @@ asid | |
| fhir | ||
| getstructuredrecord | ||
| gpconnect | ||
| searchset | ||
| proxygen | ||
| usefixtures | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| # FHIR Types in Gateway API | ||
|
|
||
| ## What is FHIR? | ||
|
|
||
| FHIR (Fast Healthcare Interoperability Resources) is the HL7 standard for exchanging healthcare information as structured resources over HTTP APIs. | ||
|
|
||
| Read more on the standards: [R4](https://hl7.org/fhir/R4/overview.html) and [STU3](https://hl7.org/fhir/STU3/overview.html). | ||
|
|
||
| In this codebase, the FHIR package provides strongly typed Python models for request validation, response parsing, and safe serialization. | ||
|
|
||
| ## FHIR versions in Clinical Data Sharing APIs | ||
|
|
||
| Two FHIR versions are used: | ||
|
|
||
| - STU3: used only for inbound Gateway API operation messages with `resourceType` Parameters (the Access Record Structured request payload). | ||
| - R4: used for all other typed resources in this module, including PDS FHIR resources such as Patient. | ||
|
|
||
| Version behaviour in the current flow: | ||
|
|
||
| - Inbound request body is validated as STU3 Parameters. | ||
| - Outbound provider response body is returned without transformation (mirrored payload). | ||
| - PDS, SDS, and internal typed handling use R4 resource models. | ||
|
|
||
| ## How Pydantic is used | ||
|
|
||
| This package uses Pydantic to make FHIR payload handling explicit and safe: | ||
|
|
||
| - Model validation: model_validate(...) is used to parse inbound JSON into typed models. | ||
| - Field aliasing: FHIR JSON names like `resourceType`, `fullUrl`, `lastUpdated` are mapped with `Field(alias=...)`. | ||
| - Type constraints: `Annotated`, `Literal`, and `min_length` constraints enforce schema-like rules. | ||
| - Runtime guards: validators check that `resourceType` and identifier system values match expected FHIR semantics. | ||
| - Polymorphism: the Resource base type dispatches to the correct subclass from `resourceType`. | ||
| - Serialization: `model_dump()`/`model_dump_json()` default to exclude_none=True to avoid emitting empty FHIR fields. | ||
|
|
||
| Typical patterns in this code: | ||
|
|
||
| - Parse JSON from API input or upstream systems into typed models. | ||
| - Access domain properties (for example, `Patient.nhs_number`) instead of raw dictionary traversal. | ||
| - Serialize models back to canonical FHIR JSON with aliases preserved. | ||
|
|
||
| ## Example usage | ||
|
|
||
| The example below shows how to load a simple FHIR R4 Patient payload and obtain the GP ODS code. | ||
|
|
||
| ```python | ||
| from fhir.r4 import Patient | ||
|
|
||
davidhamill1-nhs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| payload = { | ||
| "resourceType": "Patient", | ||
| "identifier": [ | ||
| { | ||
| "system": "https://fhir.nhs.uk/Id/nhs-number", | ||
| "value": "9000000009", | ||
| } | ||
| ], | ||
| "generalPractitioner": [ | ||
| { | ||
| "type": "Organization", | ||
| "identifier": { | ||
| "system": "https://fhir.nhs.uk/Id/ods-organization-code", | ||
| "value": "A12345", | ||
| }, | ||
| } | ||
| ], | ||
| } | ||
|
|
||
| patient = Patient.model_validate(payload) | ||
|
|
||
| nhs_number = patient.nhs_number | ||
| gp_ods_code = patient.gp_ods_code | ||
|
|
||
| print(nhs_number) # 9000000009 | ||
| print(gp_ods_code) # A12345 | ||
| ``` | ||
|
|
||
| If `generalPractitioner` is missing, `patient.gp_ods_code` returns `None`. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,3 @@ | ||
| """FHIR data types and resources.""" | ||
| from .resources.resource import Resource | ||
|
|
||
| from fhir.bundle import Bundle, BundleEntry | ||
| from fhir.general_practitioner import GeneralPractitioner | ||
| from fhir.human_name import HumanName | ||
| from fhir.identifier import Identifier | ||
| from fhir.operation_outcome import OperationOutcome, OperationOutcomeIssue | ||
| from fhir.parameters import Parameter, Parameters | ||
| from fhir.patient import Patient | ||
|
|
||
| __all__ = [ | ||
| "Bundle", | ||
| "BundleEntry", | ||
| "HumanName", | ||
| "Identifier", | ||
| "OperationOutcome", | ||
| "OperationOutcomeIssue", | ||
| "Parameter", | ||
| "Parameters", | ||
| "Patient", | ||
| "GeneralPractitioner", | ||
| ] | ||
| __all__ = ["Resource"] |
This file was deleted.
Oops, something went wrong.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| from abc import ABC | ||
| from dataclasses import dataclass | ||
| from typing import ClassVar | ||
|
|
||
| from pydantic import model_validator | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class Identifier(ABC): | ||
| """ | ||
| A FHIR Identifier element. See https://hl7.org/fhir/R4/datatypes.html#Identifier. | ||
| Attributes: | ||
| system: The namespace for the identifier value. | ||
| value: The value that is unique within the system. | ||
| """ | ||
|
|
||
| _expected_system: ClassVar[str] = "__unknown__" | ||
|
|
||
| value: str | ||
| system: str | ||
|
|
||
| @model_validator(mode="after") | ||
| def validate_system(self) -> "Identifier": | ||
| if self.system != self._expected_system: | ||
| raise ValueError( | ||
| f"Identifier system '{self.system}' does not match expected " | ||
| f"system '{self._expected_system}'." | ||
| ) | ||
| return self | ||
|
|
||
| @classmethod | ||
| def __init_subclass__(cls, expected_system: str) -> None: | ||
| cls._expected_system = expected_system |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import pytest | ||
| from pydantic import BaseModel, ValidationError | ||
|
|
||
| from fhir.elements.identifier import Identifier | ||
|
|
||
|
|
||
| class TestIdentifierInitSubclass: | ||
| def test_subclass_sets_expected_system(self) -> None: | ||
| class _Custom(Identifier, expected_system="https://example.com"): | ||
| pass | ||
|
|
||
| assert _Custom._expected_system == "https://example.com", ( | ||
| "_expected_system should be set by __init_subclass__" | ||
| ) | ||
|
|
||
| def test_multiple_subclasses_have_independent_expected_system(self) -> None: | ||
| class _A(Identifier, expected_system="system-a"): | ||
| pass | ||
|
|
||
| class _B(Identifier, expected_system="system-b"): | ||
| pass | ||
|
|
||
| assert _A._expected_system == "system-a", ( | ||
| "_A._expected_system should be 'system-a'" | ||
| ) | ||
| assert _B._expected_system == "system-b", ( | ||
| "_B._expected_system should be 'system-b'" | ||
| ) | ||
|
|
||
| def test_subclass_without_expected_system_raises(self) -> None: | ||
| with pytest.raises(TypeError): | ||
|
|
||
| class _Bad(Identifier): # type: ignore[call-arg] | ||
| pass | ||
|
|
||
|
|
||
| class TestIdentifierModelValidate: | ||
| def test_valid_system_passes_validation(self) -> None: | ||
| class _TestId(Identifier, expected_system="https://example.com"): | ||
| pass | ||
|
|
||
| class _Container(BaseModel): | ||
| identifier: _TestId | ||
|
|
||
| result = _Container.model_validate( | ||
| {"identifier": {"system": "https://example.com", "value": "abc-123"}} | ||
| ) | ||
|
|
||
| assert result.identifier.system == "https://example.com", ( | ||
| "system should match the expected system" | ||
| ) | ||
| assert result.identifier.value == "abc-123", "value should be 'abc-123'" | ||
|
|
||
| def test_invalid_system_fails_validation(self) -> None: | ||
| class _TestId(Identifier, expected_system="expected-system"): | ||
| pass | ||
|
|
||
| class _Container(BaseModel): | ||
| identifier: _TestId | ||
|
|
||
| with pytest.raises( | ||
| ValidationError, | ||
| match="Identifier system 'invalid-system' does not match expected " | ||
| "system 'expected-system'.", | ||
| ): | ||
| _Container.model_validate( | ||
| {"identifier": {"system": "invalid-system", "value": "some-value"}} | ||
| ) | ||
|
|
||
| def test_missing_value_fails_validation(self) -> None: | ||
| class _TestId(Identifier, expected_system="sys"): | ||
| pass | ||
|
|
||
| class _Container(BaseModel): | ||
| identifier: _TestId | ||
|
|
||
| with pytest.raises(ValidationError): | ||
| _Container.model_validate({"identifier": {"system": "sys"}}) | ||
|
|
||
| def test_missing_system_fails_validation(self) -> None: | ||
| class _TestId(Identifier, expected_system="sys"): | ||
| pass | ||
|
|
||
| class _Container(BaseModel): | ||
| identifier: _TestId | ||
|
|
||
| with pytest.raises(ValidationError): | ||
| _Container.model_validate({"identifier": {"value": "v"}}) |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's this change about?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pydantic don't publish a wheel for musllinux 1.2 but does for 1.1; a flask dependency needs 1.2. Pip allows passing multiple platform options.