Serving a FHIR API in Python: which resource models can I reuse, and which APIs must I implement?

August 14, 2025

I saw a line of Python in a hospital integration example: client.post(FHIR_SERVER_URL, json=data). It sent data to a URL. What did the other end of that URL actually do, and could I implement it myself? Further down, the code imported Patient directly. Since the Python library already knew what a patient record looked like, had it implemented storage and queries too?

Suppose a clinic registers a fictional patient named Lin. A follow-up application first needs to read the record, then later record whether the patient prefers morning or afternoon phone calls. Let’s have two programs exchange the record on our own computer before adding the follow-up field.

How does an app create, read, and update the same patient record through a FHIR API?

FHIR (Fast Healthcare Interoperability Resources) is a healthcare data exchange standard. A separately identifiable, readable piece of data is called a resource. A Patient represents patient details, an Observation can represent a platelet measurement, and a ServiceRequest can represent a test order. A measurement can use subject.reference to point to Patient/42, letting a lab system send a value without sending a whole patient record again. This article uses R4, version 4.0.1 of the standard.12

We’ll use HTTP, the protocol browsers also use to make requests. A request specifies an action and an address, optionally with a body. JSON represents records in that body using field names and values. The API is the set of operations the program exposes. Suppose the app registers Lin, reads the record back, and later adds the given name Ann. Below I abbreviate the server-assigned ID to 42. The app follows the address returned at creation to find the same record.

sequenceDiagram
    participant A as 医院应用
    participant S as FHIR 服务
    A->>S: POST /Patient,提交姓氏 Lin
    Note over S: 校验字段,分配编号并保存
    S-->>A: 201 Created,Location 给出 /Patient/42
    A->>S: GET /Patient/42,读取档案
    S-->>A: 200 OK,返回 Lin 的档案
    Note over A: 保留原有字段,补上名字 Ann
    A->>S: PUT /Patient/42,提交含编号 42 的完整档案
    S-->>A: 200 OK,更新成功
    A->>S: GET /Patient/42,再读一次
    S-->>A: 200 OK,返回含名字 Ann 的档案

Each pair of arrows in the diagram is a separate request and response. The service places the new record’s address in the create response’s Location field. The app can save it for the next visit. Reading a nonexistent ID can return 404. This example uses PUT to submit the full record, so the id in the body must match the ID in the address. If someone else has just updated the record, submitting an old copy may overwrite their change.3

The R4 standard package used here has 146 concrete resource types. For example, Encounter represents a clinical visit, Practitioner a healthcare professional, and DiagnosticReport groups several results into one report. Each has a resource type marker and fields defined for its own purpose.4

These paths and interactions come from FHIR. The capabilities a particular service actually supports are in the CapabilityStatement published at GET /metadata. Server IDs also have a scope: Patient/42 in system A and Patient/42 in system B could be different people. A hospital medical record number usually belongs in identifier, with the issuing authority specified alongside it.31

Does a JSON record count as “a FHIR message”?

A registration card with Lin’s name tells us who the person is, without saying what we want to do with it. Send the card as the body of POST /Patient, and the HTTP method and address say “please create a patient resource.” FHIR also defines a dedicated messaging exchange. It packages several resources into a Bundle whose type is message and whose first entry must be a MessageHeader. The example below uses the same registration card to say “we have just registered this patient,” with an event code agreed for this exercise.5

{
  "resourceType": "Bundle", "id": "6839aa33-bc26-42f0-9783-e420e0ace7b6", "type": "message",
  "entry": [
    {"fullUrl": "urn:uuid:09b696a0-0767-4ae4-ae6a-2dd60959ea56",
     "resource": {"resourceType": "MessageHeader", "id": "09b696a0-0767-4ae4-ae6a-2dd60959ea56",
       "eventCoding": {"system": "https://hospital.example/events", "code": "patient-registered"},
       "source": {"endpoint": "https://hospital.example/registration"},
       "focus": [{"reference": "urn:uuid:100fe0f2-2cb0-40b0-b873-8e7549db00b2"}]}},
    {"fullUrl": "urn:uuid:100fe0f2-2cb0-40b0-b873-8e7549db00b2",
     "resource": {"resourceType": "Patient", "name": [{"family": "Lin"}]}}
  ]
}

Following focus (who this event concerns) to the matching fullUrl on the second entry tells the receiver which patient to interpret. A service accepting such messages must also understand the agreed event and its handling. The following exercise implements only the three HTTP operations for patients, so send it the registration card itself.

Implementing the other end of the URL

The following FastAPI program gives the local machine three endpoints for creating, reading by ID, and updating a patient. It stores the same JSON in SQLite, a database backed by a disk file. A route maps a URL to a function. The Patient model comes from fhir.resources. I chose version 6.1.0 because its default models correspond to R4.6

For example, on macOS or Linux with Python 3.12, open an empty directory and run the following three lines. The first creates a project environment. The second activates it in the current terminal. In Windows PowerShell, the activation command is .\.venv\Scripts\Activate.ps1.

python -m venv .venv
source .venv/bin/activate
python -m pip install fhir.resources==6.1.0 pydantic==1.10.22 fastapi==0.115.12 uvicorn==0.34.2 httpx==0.28.1

Save this as app.py. Start by reading the three functions decorated with @app. Creation assigns an ID, reading looks it up, and updating checks it. Each write commits in a database transaction.

import sqlite3
from contextlib import closing
from uuid import uuid4

from fastapi import FastAPI, HTTPException, Response
from fhir.resources.patient import Patient

app = FastAPI()
media_type = "application/fhir+json"

def connect():
    return sqlite3.connect("patients.sqlite")

with closing(connect()) as db, db:
    db.execute("CREATE TABLE IF NOT EXISTS patient (id TEXT PRIMARY KEY, body TEXT NOT NULL)")

@app.post("/Patient")
def create(patient: Patient):
    patient.id = uuid4().hex
    body = patient.json()
    with closing(connect()) as db, db:
        db.execute("INSERT INTO patient VALUES (?, ?)", (patient.id, body))
    return Response(body, status_code=201, media_type=media_type,
                    headers={"Location": f"/Patient/{patient.id}"})

@app.get("/Patient/{patient_id}")
def read(patient_id: str):
    with closing(connect()) as db:
        row = db.execute("SELECT body FROM patient WHERE id = ?", (patient_id,)).fetchone()
    if row is None:
        raise HTTPException(404, "Patient not found")
    return Response(row[0], media_type=media_type)

@app.put("/Patient/{patient_id}")
def update(patient_id: str, patient: Patient):
    if patient.id != patient_id:
        raise HTTPException(400, "Patient.id must match the request URL")
    body = patient.json()
    with closing(connect()) as db, db:
        result = db.execute("UPDATE patient SET body = ? WHERE id = ?", (body, patient_id))
        if result.rowcount == 0:
            raise HTTPException(404, "Patient not found")
    return Response(body, media_type=media_type)

Start the service with python -m uvicorn app:app. In another terminal, enter the same directory and activate the same environment. Save the client below as client.py and run python client.py. After creation it follows Location to fetch the record, adds the given name Ann to family name Lin, then reads the same ID again. You should see Lin Ann.

import httpx

with httpx.Client(base_url="http://127.0.0.1:8000", trust_env=False,
                  headers={"Content-Type": "application/fhir+json"}) as client:
    created = client.post("/Patient", json={"resourceType": "Patient", "name": [{"family": "Lin"}]})
    created.raise_for_status()
    path = created.headers["Location"]
    patient = client.get(path).raise_for_status().json()
    patient["name"][0]["given"] = ["Ann"]
    client.put(path, json=patient).raise_for_status()
    name = client.get(path).raise_for_status().json()["name"][0]
    print(name["family"], name["given"][0])

We can now answer “Do I need to import templates for over a hundred resources?” If your workflow only uses patients, import the library’s patient model. When lab results come along, import Observation for the same FHIR version. Models can validate field structure. Storage, routes, patient identity matching, authorization, and permission to overwrite a specific revision belong to the service. This local exercise uses fictional records. If two clients update concurrently, the last write wins. A version-aware FHIR server can let clients supply the last-read version with If-Match and reject stale updates. A full server also needs a corresponding capability statement and the standard OperationOutcome error resource.3

How many endpoints should I provide myself?

If the task grows to “offer standard creation, search, and history operations across the whole hospital,” writing three routes per resource quickly loses its appeal. At the time I looked at HAPI FHIR in the Java ecosystem and wondered whether it was simply Spring Boot. They have different roles. Spring Boot configures and starts the Java application. HAPI FHIR provides healthcare resource models and components for handling FHIR requests. With its Plain Server, developers write resource handlers that connect reads and writes to existing systems. With its JPA Server, they can reuse its resource storage and search layer. Calling an existing hospital server is simpler still: Python can use a client like the one above and implement only the authorized business workflow.7

We can now retrieve Lin’s record by ID. The follow-up team also wants to record “afternoons are a good time to call.” Even if a partner can read the name, how does it know which values the new field permits? Continue with extension definitions and their URLs.

Footnotes

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

  2. Health Level Seven International. (2019). Observation: Detailed descriptions. FHIR R4 v4.0.1. Observation.subject 的引用类型。 ↩

  3. Health Level Seven International. (2019). RESTful API. FHIR R4 v4.0.1. create 和 Location · update 和版本冲突 · 服务能力声明。 ↩ ↩2 ↩3

  4. Health Level Seven International. (2019). Resource index. FHIR R4 v4.0.1. 资源分类与字母索引。数量据同版核心包中类别为 resource 的非抽象基础资源类型统计。 ↩

  5. Health Level Seven International. (2019). Messaging. FHIR R4 v4.0.1. 消息 Bundle、第一项 MessageHeader 和事件处理。 ↩

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

  7. HAPI FHIR contributors. (2025). HAPI FHIR v8.2.0. GitHub. 通用服务器模块 · JPA 存储实现。另见 HAPI FHIR Documentation 的 Plain Server 资源操作与 JPA 各层职责。 ↩

© 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). Serving a FHIR API in Python: which resource models can I reuse, and which APIs must I implement?. https://caiborui.com/blog/2025-08-14-zh-python-fhir-patient-api-extension-entrans

@misc{borui2025-a101f4c4,
  author = {borui},
  title = {{Serving a FHIR API in Python: which resource models can I reuse, and which APIs must I implement?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-08-14-zh-python-fhir-patient-api-extension-entrans}
}