Skip to content
Open
Show file tree
Hide file tree
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 Mar 10, 2026
3de16a9
First step towards using Pydantic.
davidhamill1-nhs Mar 10, 2026
4f2a258
Remove unused helper functions.
davidhamill1-nhs Mar 10, 2026
d8d1554
Use Pydantic FHIR types in SDS client.
davidhamill1-nhs Mar 10, 2026
4359fc4
Use Pydantic FHIR types in tests.
davidhamill1-nhs Mar 10, 2026
faa30e9
Apply review comment for PR 275 from JW - move response behaviour out…
davidhamill1-nhs Mar 11, 2026
07c3717
Build Pydantic Parameter type.
davidhamill1-nhs Mar 11, 2026
5384442
Remove unused TypedDict FHIR types.
davidhamill1-nhs Mar 11, 2026
0c9cdf2
import fhir resources from package __init__
davidhamill1-nhs Mar 11, 2026
f923cf0
Restructure files.
davidhamill1-nhs Mar 11, 2026
9764e00
Add docs.
davidhamill1-nhs Mar 12, 2026
c7b1113
Add/restructure unit tests.
davidhamill1-nhs Mar 16, 2026
83e723c
Tidy up TODO.
davidhamill1-nhs Mar 16, 2026
b51aeb9
Export response class from module __init__.py
davidhamill1-nhs Mar 16, 2026
62e7bb6
Correct typing.
davidhamill1-nhs Mar 16, 2026
3922a42
Tidying up.
davidhamill1-nhs Mar 16, 2026
a48a423
Clean up error handling.
davidhamill1-nhs Mar 16, 2026
c379388
Rename expression to better express what is being returned.
davidhamill1-nhs Mar 16, 2026
90f09b8
Verify certs as aprt of contract testing.
davidhamill1-nhs Mar 16, 2026
34f6599
Actually mirror headers back.
davidhamill1-nhs Mar 17, 2026
324e47d
Only mirror trace id header
davidhamill1-nhs Mar 17, 2026
4282ba7
Only mirror trace id header
davidhamill1-nhs Mar 17, 2026
dd454d2
correct the import statement to reflect the changes to the structure.
davidhamill1-nhs Mar 17, 2026
c1544b1
URL needs to point at correct version.
davidhamill1-nhs Mar 17, 2026
1131cae
No need to return empty string here.
davidhamill1-nhs Mar 17, 2026
006f3be
Remove unnecessary import.
davidhamill1-nhs Mar 17, 2026
84caa3b
Correct doc string to accurately document behaviour.
davidhamill1-nhs Mar 17, 2026
8e452a5
Resolve import issues from merge coflict resolutions.
davidhamill1-nhs Mar 18, 2026
21be3ef
Correct version in docstring.
davidhamill1-nhs Mar 19, 2026
dcaeb9b
I messed up the merge conflict resolution.
davidhamill1-nhs Mar 19, 2026
dad9d76
typo.
davidhamill1-nhs Apr 1, 2026
58484e2
Merge remote-tracking branch 'origin/main' into feature/GPCAPIM-305_c…
davidhamill1-nhs Apr 1, 2026
e2ec5f4
API name is not required for unit tests.
davidhamill1-nhs Apr 1, 2026
0d8db54
Don't remove apim's pytest library.'
davidhamill1-nhs Apr 1, 2026
43ad610
Provide correct commands for test runs.
davidhamill1-nhs Apr 1, 2026
2a4cf54
Pull out nested elements.
davidhamill1-nhs Apr 1, 2026
afd113e
update poetry lock.
davidhamill1-nhs Apr 1, 2026
61a71b2
Correct typing ignore.
davidhamill1-nhs Apr 1, 2026
36305e8
Pull out nested elements.
davidhamill1-nhs Apr 1, 2026
43542d8
Make explicit what the API will accept, even if not required.
davidhamill1-nhs Apr 1, 2026
193b8a4
Pull out nested elements.
davidhamill1-nhs Apr 1, 2026
a75613a
Pull out nested elements.
davidhamill1-nhs Apr 1, 2026
167cb3d
Pull out nested elements.
davidhamill1-nhs Apr 1, 2026
d256768
Remove duplicate identifiers.
davidhamill1-nhs Apr 1, 2026
f0c2149
Removed mixed uses of versions.
davidhamill1-nhs Apr 1, 2026
053b993
Bring the JWT fields in to the fold.
davidhamill1-nhs Apr 2, 2026
d98453c
Remove duplicated call to fixture.
davidhamill1-nhs Apr 2, 2026
cb16bda
Remove unnecessary type declaration.
davidhamill1-nhs Apr 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/agents/unit_test.agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ You are an expert unit test writer for this project.
- **File Structure:**
- `gateway-api/src/**/*.py` – Files and folders that require unit tests (you READ from here)
- `gateway-api/src/**/test_*.py` – All unit tests (you WRITE to here)
- **Running tests:**
- `make test-unit` to run all unit tests
- `poetry run pytest path/to/test` from `gateway-api/` to runs specific tests.

## Unit test practices

Expand Down
10 changes: 5 additions & 5 deletions .github/instructions/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ After deploying the container locally, `make test` will run all tests and captur

Individual test suites can be run with:

- Unit tests: `make unit`
- Acceptance tests: `make acceptance`
- Integration tests: `make integration`
- Schema tests: `make schema`
- Contract tests: `make contract`
- Unit tests: `make test-unit`
- Acceptance tests: `make test-acceptance`
- Integration tests: `make test-integration`
- Schema tests: `make test-schema`
- Contract tests: `make test-contract`

The container must be running in order to successfully run any of the test suites other than the unit tests.

Expand Down
1 change: 1 addition & 0 deletions .vscode/cspell-dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ asid
fhir
getstructuredrecord
gpconnect
searchset
proxygen
usefixtures
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ build-gateway-api: dependencies
@poetry run mypy --no-namespace-packages .
@echo "Packaging dependencies..."
@poetry build --format=wheel
@pip install "dist/gateway_api-0.1.0-py3-none-any.whl" --target "./target/gateway-api" --platform musllinux_1_2_x86_64 --only-binary=:all:
@pip install "dist/gateway_api-0.1.0-py3-none-any.whl" --target "./target/gateway-api" --platform musllinux_1_2_x86_64 --platform musllinux_1_1_x86_64 --only-binary=:all:
Copy link
Copy Markdown
Contributor

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?

Copy link
Copy Markdown
Contributor Author

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.

# Copy main file separately as it is not included within the package.
@rm -rf ../infrastructure/images/gateway-api/resources/build/
@mkdir ../infrastructure/images/gateway-api/resources/build/
Expand Down
12 changes: 11 additions & 1 deletion gateway-api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ paths:
type: string
enum: ["Parameters"]
example: "Parameters"
meta:
type: object
properties:
lastUpdated:
type: string
format: date-time
example: "2026-01-12T10:00:00Z"
versionId:
type: string
example: "1"
parameter:
type: array
minItems: 1
Expand All @@ -76,7 +86,7 @@ paths:
properties:
system:
type: string
minLength: 1
enum: ["https://fhir.nhs.uk/Id/nhs-number"]
example: "https://fhir.nhs.uk/Id/nhs-number"
value:
type: string
Expand Down
130 changes: 68 additions & 62 deletions gateway-api/poetry.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions gateway-api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ flask = "^3.1.3"
types-flask = "^1.1.6"
requests = "^2.33.0"
pyjwt = "^2.12.0"
pydantic = "^2.0"

[tool.poetry]
packages = [{include = "gateway_api", from = "src"},
Expand Down
76 changes: 76 additions & 0 deletions gateway-api/src/fhir/README.md
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

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`.
23 changes: 2 additions & 21 deletions gateway-api/src/fhir/__init__.py
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"]
18 changes: 0 additions & 18 deletions gateway-api/src/fhir/bundle.py

This file was deleted.

Empty file.
33 changes: 33 additions & 0 deletions gateway-api/src/fhir/elements/identifier.py
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
88 changes: 88 additions & 0 deletions gateway-api/src/fhir/elements/test_elements.py
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"}})
21 changes: 0 additions & 21 deletions gateway-api/src/fhir/general_practitioner.py

This file was deleted.

12 changes: 0 additions & 12 deletions gateway-api/src/fhir/human_name.py

This file was deleted.

8 changes: 0 additions & 8 deletions gateway-api/src/fhir/identifier.py

This file was deleted.

14 changes: 0 additions & 14 deletions gateway-api/src/fhir/operation_outcome.py

This file was deleted.

15 changes: 0 additions & 15 deletions gateway-api/src/fhir/parameters.py

This file was deleted.

Loading
Loading