Defining and publishing a custom FHIR field: from Patient.extension to a resolvable canonical URL

August 14, 2025

The clinic has recorded Lin’s name. The follow-up nurse also wants to note “afternoons are a good time to call”, and another institution opening the record next week needs to understand the option. FHIR calls a patient record a Patient resource. To create one locally, try the Python example for creating, reading, and updating a patient. The nurse chose “afternoon” for Lin. The two institutions also have to agree that this field means a convenient callback window, which options are allowed, and which code represents each one. Those shared rules are what I mean by a field definition.

How do we record “afternoons are a good time to call” so another institution can understand it?

The follow-up team says Lin prefers afternoon calls. First check the existing Patient fields: telecom can record a phone number and its use, while communication can record a language for communication. Suppose both organizations need a convention they can filter by morning or afternoon and no existing specification fits. Then they can add an extension. Add the following member to the patient JSON and PUT the whole patient resource back. The example shows only the new part.12

{
  "extension": [{
    "url": "https://hospital.example/fhir/StructureDefinition/contact-window",
    "valueCodeableConcept": {
      "coding": [{
        "system": "https://hospital.example/fhir/CodeSystem/contact-period",
        "code": "pm",
        "display": "下午"
      }]
    }
  }]
}

What confused me most in examples like this was all the fields that look like web addresses. Do I have to build a website? What should each address return? Following pm in this record is easier than memorizing terms:

QuestionWhere to find the answerFollow-up example
What does the new field mean and where may it appear?extension.url refers to the extension’s canonical identifier and corresponds to a StructureDefinitionA patient may record a convenient callback window, with a CodeableConcept value
Which dictionary contains pm?coding.system identifies the CodeSystemThe hospital’s callback-period code system defines am, pm, and their meanings
Which codes may be selected for this field?A value set, ValueSet, lists or selects permitted codes by rule and is bound in the structure definitionOnly am and pm might be permitted. The patient instance carries the selected code and its system
Does this hospital allow at most one period for each patient?A profile, a local specification constraining a resource type, can state cardinality and other requirementsConstrain this particular extension in Patient.extension to at most one occurrence. Other extensions follow their own rules

These definitions are specification materials exchanged during implementation, often called artifacts. A hospital can allocate stable canonical URLs under a domain it controls, publish definitions on a website, or give partners an implementation guide package for their validators. Software can recognize definitions from an installed package without fetching a URL every time a patient is created. If a partner requests a machine-readable definition over HTTP, return the corresponding FHIR resource JSON: resourceType: StructureDefinition for the field, or resourceType: ValueSet for the value set. To obtain the selectable items in an expanded value set, a terminology service can provide ValueSet/$expand. The example domain is illustrative.23

The definition has type.code. Which field goes in the patient record?

Returning to Lin’s callback window, the example has two things named code. In the extension definition, "type": [{"code": "CodeableConcept"}] tells software how to read the value’s structure. In the patient record, "code": "pm" is the actual choice the follow-up team made for Lin. Extract the part of the definition that controls the value type and you’ll see this entry.24

{
  "path": "Extension.value[x]",
  "type": [{"code": "CodeableConcept"}]
}

[x] means one of several types may be selected. In the patient record, the field name changes to match the chosen type. Each row below imagines a separate follow-up extension and shows only the member that stores its value.

What the follow-up team wants to recordDefinition’s type.codeInstance field and value
Anything to remember before calling?string"valueString": "先发短信" (text first)
May we leave a message?boolean"valueBoolean": true
How many days until the next contact?Quantity"valueQuantity": {"value": 3, "unit": "天"} (days)
Which period is convenient?CodeableConcept"valueCodeableConcept": {"coding": [{"system": "https://hospital.example/fhir/CodeSystem/contact-period", "code": "pm"}]}

We want to filter callback periods by morning or afternoon, so we use the last row. Even if the display wording for “afternoon” changes, a receiver can recognize the same option as long as its code system and code stay the same. Checking the structure of valueCodeableConcept and checking whether pm is permitted are also separate steps. The resource model answers the first. The value set bound to the extension answers the second.3

Where do the callback-window rules live, and how do we generate shareable FHIR definitions?

Lin’s chosen pm is already in her patient record. To give a partner the same rules, create guide/input/fsh/contact-window.fsh under the project root. This source file defines the field meaning, codes, and permitted choices. We’ll use FHIR Shorthand (FSH) to write the rules. The SUSHI compiler reads the source and writes machine-readable JSON definitions to guide/fsh-generated/resources/. Paths in the directory tree are local to this example project.5

app.py                          # 可选,已有的患者服务
guide/
  sushi-config.yaml             # 规定标识的公共前缀和 FHIR 版本
  input/fsh/contact-window.fsh   # 字典、值集、扩展的源文件
  fsh-generated/resources/      # 编译器输出的 JSON,供发布或装入验证工具

First create the working directory. Run mkdir -p guide/input/fsh at the project root on macOS or Linux, then create two text files. Put this in guide/sushi-config.yaml:

status: draft
version: 0.1.0
canonical: https://hospital.example/fhir
fhirVersion: 4.0.1
FSHOnly: true

Put the next three snippets in guide/input/fsh/contact-window.fsh. The first names the codes, the second selects the allowed values, and the third binds the value set to a patient extension. The final required explains why the patient record only needs to state which dictionary pm belongs to.6

CodeSystem: ContactPeriod
Id: contact-period
* #am "上午"
* #pm "下午"

ValueSet: ContactWindows
Id: contact-windows
* include codes from system ContactPeriod

Extension: ContactWindow
Id: contact-window
Context: Patient
* value[x] 1..1
* value[x] only CodeableConcept
* valueCodeableConcept from ContactWindows (required)

With Node.js and npm installed, run npx --yes --package fsh-sushi@3.11.0 sushi . in guide. Open the output file whose name begins with StructureDefinition. Look at url and differential.element (the rules added to the base definition) to find the URL referenced by the patient instance and the permitted value type. A Python-only team could also maintain and publish the same standard JSON or construct it from Python models. A resource serialization library and an FSH compiler do different jobs. The server language doesn’t dictate which modeling tools a receiver can use.75

How do I actually request a definition from this URL?

The canonical address in the earlier patient example uses an example domain. To see “the address referenced by the patient returns its definition” locally, make a second build. Change the canonical line in sushi-config.yaml to canonical: http://127.0.0.1:8765/fhir and rerun the SUSHI command in guide. The compiler updates all three definitions and their references with this prefix. Still in guide, save the following code as definitions.py. In a Python 3.12 environment run python -m pip install fastapi==0.115.12 uvicorn==0.34.2. This small service publishes only the three definitions generated for the example.

import json
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()
definitions = {}
for file in Path("fsh-generated/resources").glob("*.json"):
    item = json.loads(file.read_text())
    definitions[(item["resourceType"], item["id"])] = item

@app.get("/fhir/{kind}/{name}")
def definition(kind: str, name: str):
    item = definitions.get((kind, name))
    if item is None:
        raise HTTPException(404)
    return JSONResponse(item, media_type="application/fhir+json")

Run python -m uvicorn definitions:app --port 8765. Open http://127.0.0.1:8765/fhir/StructureDefinition/contact-window in a browser. Its resourceType is StructureDefinition, and its url is exactly the address you just opened. Change the last two path segments to ValueSet/contact-windows for the selection rules, or CodeSystem/contact-period to see am and pm. For a patient to reference the local versions, also replace extension.url and coding.system with the local addresses from this build. When deploying to a shared environment, use stable identifiers that recipients can recognize.

💡 Tip: To compile an existing .fsh as-is entirely in Python, you need a compiler that implements the FSH language. HL7 lists SUSHI as the reference implementation. Among the tools I investigated for R4, I found no verified Python equivalent that could directly replace SUSHI. Python’s fhir.resources can construct, read, and write the resulting JSON. A team can run SUSHI only at build time and give the JSON to a Python-only service, so developers and deployment machines can use different tools.8

Footnotes

  1. Health Level Seven International. (2019). Patient. FHIR R4 v4.0.1. 资源结构、identifier、telecom 与 communication。 ↩

  2. Health Level Seven International. (2019). Defining extensions 与 Profiling FHIR. FHIR R4 v4.0.1. 扩展标识、上下文与定义的传播 · 约束资源与使用扩展。 ↩ ↩2 ↩3

  3. Health Level Seven International. (2019). Using codes in resources 与 Value set expansion. FHIR R4 v4.0.1. 代码系统、值集和绑定 · ValueSet/$expand 的返回内容。 ↩ ↩2

  4. Health Level Seven International. (2019). Data types. FHIR R4 v4.0.1. CodeableConcept、Coding 和 Quantity 的结构。 ↩

  5. FSH School. (n.d.). Project structure. FSH School Documentation. SUSHI 输入、配置文件与生成目录。 ↩ ↩2

  6. Health Level Seven International. (n.d.). FHIR Shorthand language reference. HL7. Extension、ValueSet、CodeSystem 的声明与规则。 ↩

  7. Islam, N., & contributors. (2021). fhir.resources 6.1.0. PyPI. FHIR Version Info 与 Python 模型示例。 ↩

  8. Health Level Seven International. (n.d.). FHIR Shorthand. HL7. Overview 与 SUSHI 参考编译器。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-08-14). Defining and publishing a custom FHIR field: from Patient.extension to a resolvable canonical URL. https://caiborui.com/blog/2025-08-14-zh-fhir-extension-canonical-url-entrans

@misc{borui2025-6c7db8a2,
  author = {borui},
  title = {{Defining and publishing a custom FHIR field: from Patient.extension to a resolvable canonical URL}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-08-14-zh-fhir-extension-canonical-url-entrans}
}