Pydantic and FastAPI¶
Every model derives from pydantic.BaseModel (through
fhir_core.fhirabstractmodel.FHIRAbstractModel), so everything you know
from Pydantic V2 applies: model_copy, model_json_schema,
model_fields, validators, and so on.
Using FHIR types as fields¶
To use a FHIR resource as a field of your own model, annotate it with the
matching type from fhir.resources.fhirtypes (<Name>Type).
These types handle the circular references between FHIR models and pick the
right class for polymorphic Resource values.
>>> from typing import List
>>> from pydantic import BaseModel
>>> from fhir.resources.fhirtypes import ObservationType, PatientType
>>> class PatientSummary(BaseModel):
... patient: PatientType
... observations: List[ObservationType] = []
>>> s = PatientSummary(patient={"resourceType": "Patient", "id": "p1"})
>>> type(s.patient).__name__
'Patient'
>>> s.model_dump_json()
'{"patient":{"resourceType":"Patient","id":"p1"},"observations":[]}'
R4B and STU3 have their own fhirtypes modules
(fhir.resources.R4B.fhirtypes, fhir.resources.STU3.fhirtypes).
FastAPI¶
Because the models are plain Pydantic models, they work directly as FastAPI request bodies and response models (#46):
from fastapi import FastAPI, HTTPException
from fhir.resources.patient import Patient
app = FastAPI()
db: dict[str, Patient] = {}
@app.post("/Patient", response_model=Patient, status_code=201)
def create_patient(patient: Patient) -> Patient:
db[patient.id] = patient
return patient
@app.get("/Patient/{pid}", response_model=Patient)
def read_patient(pid: str) -> Patient:
if pid not in db:
raise HTTPException(404)
return db[pid]
FastAPI then validates incoming FHIR JSON and documents the full resource schema in the OpenAPI page.
Tip
FastAPI serializes response_model values with Pydantic’s default
settings. If you need summary_only or exclude_comments, or the
application/fhir+json media type, return a response yourself:
from fastapi import Response
@app.get("/Patient/{pid}")
def read_patient(pid: str, _summary: bool = False):
body = db[pid].model_dump_json(summary_only=_summary)
return Response(body, media_type="application/fhir+json")
Introspecting a model¶
Useful helpers on every model class:
>>> from fhir.resources.patient import Patient
>>> Patient.get_resource_type()
'Patient'
>>> Patient.elements_sequence()[:6]
['id', 'meta', 'implicitRules', 'language', 'text', 'contained']
>>> field = Patient.model_fields["birthDate"]
>>> field.title
'The date of birth for the individual'
>>> field.json_schema_extra["summary_element_property"]
True
JSON Schema¶
model_json_schema() works, but the result for a resource is very large
because it inlines the whole graph of referenced data types.