Metadata-Version: 2.5
Name: haau3
Version: 0.5.2
Summary: Python SDK for the haau3 platform API: appointment slots from SMART Scheduling Links publishers, Medicare Advantage and ACA Marketplace plan benefits, medication list reconciliation, RxNorm, LOINC and ICD-10-CM terminology, the CMS National Provider Directory and FHIR Questionnaires, as typed calls.
Project-URL: Homepage, https://platform.haau3.com
Project-URL: Documentation, https://docs.haau3.com
Project-URL: Repository, https://github.com/haau3/haau3-python
Project-URL: Issues, https://github.com/haau3/haau3-python/issues
Project-URL: Changelog, https://github.com/haau3/haau3-python/blob/main/CHANGELOG.md
Author-email: haau3 <hello@haau3.com>
License-Expression: MIT
License-File: LICENSE
Keywords: aca-marketplace,appointment-scheduling,fhir,fhir-r4,haau3,healthcare,healthcare-api,icd-10-cm,insurance-plan,loinc,medical-benefits,medicare-advantage,medication-reconciliation,npi,provider-directory,python,rxnorm,scheduling,sdk,smart-scheduling-links,terminology
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: Trio
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Healthcare Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: anyio<5,>=4.16.0
Requires-Dist: httpx2<3,>=2.0.0
Requires-Dist: typing-extensions<5,>=4.12
Description-Content-Type: text/markdown

# haau3

The Python SDK for the [haau3 platform API](https://docs.haau3.com), as typed calls:

- **Scheduling:** open appointment slots from many SMART Scheduling Links publishers, in one FHIR
  search, each `Slot` with its `Schedule`, `Location` and provider.
- **Medical Benefits:** Medicare Advantage and ACA Marketplace plans as FHIR `InsurancePlan`,
  searchable by state or county, and which providers are in a plan's network.
- **MedList:** one reconciled medication list from one patient's FHIR medication records.

On the same key and FHIR base: RxNorm, LOINC and ICD-10-CM lookups, value sets and code
validation (Terminology), practitioners and organizations from CMS's National Provider Directory
(Provider directory), and standard FHIR Questionnaires such as the PHQ-9.

The haau3 platform API is in preview: it may change as we build, usually to add features or improve performance.

Also for TypeScript: [`@haau3/sdk`](https://www.npmjs.com/package/@haau3/sdk), and for Go:
[`github.com/haau3/haau3-go`](https://pkg.go.dev/github.com/haau3/haau3-go).

## Install

```sh
pip install haau3
```

Python 3.10 or newer. The SDK runs on a server only: it refuses to start in a browser (Pyodide),
where your API key would be public.

## Authenticate

Create an API key on [platform.haau3.com](https://platform.haau3.com), then set it as
`HAAU3_API_KEY` or pass it as `api_key`. To try the API with no key first, call the Sandbox (see
"The Sandbox" below).

Or make the key from your project's folder with the
[haau3 command line](https://github.com/haau3/haau3-cli) (Node 22 or newer): `npx haau3 login`, then
`npx haau3 keys create`, which writes it to the project's env file and never shows it. Load that
file when the program starts, such as with [python-dotenv](https://pypi.org/project/python-dotenv/)'s
`load_dotenv()`.

```python
from haau3 import Haau3

client = Haau3()  # reads HAAU3_API_KEY
```

Make one client and reuse it: it holds a pool of connections, and is safe to share between threads.

## A first call

```python
import json

# Open appointment slots of one provider, found by NPI, each with its schedule, location and provider.
page = client.search_slot_with_includes(provider_identifier="http://hl7.org/fhir/sid/us-npi|2900000227", count=1)
views = client.slot_views(page)
if views:
    view = views[0]
    # A name's text, or its given and family names when the publisher sent no text.
    names = [
        name.get("text") or " ".join([*name.get("given", []), name.get("family", "")]).strip() or None
        for practitioner in view.practitioners
        for name in practitioner.get("name", [])
    ]
    places = [location.get("name") for location in view.locations]
    print(
        json.dumps(
            {
                "start": view.slot.get("start"),
                "practitioner": names[0] if names else None,
                "location": places[0] if places else None,
                "booking_link": view.booking_link,
            },
            indent=2,
        )
    )
else:
    print("No open slots matched.")
```

An answer is the JSON the API sent, as plain dicts and lists, so it goes into `json.dumps`, a
DataFrame or a database as it is. Each is typed with HL7's R4 types (`haau3.fhir`), as a
`TypedDict`, so a type checker and your editor know every key, and `haau3.types` names each
operation's query, body and answer. FHIR elements are optional, so read them with `.get()`.

## From async code

`AsyncHaau3` has the same methods, awaited. It runs on asyncio and on trio.

```python
from haau3 import AsyncHaau3

async_client = AsyncHaau3()
plan = await async_client.read_insurance_plan("H2406-013-000")
```

Make one per event loop and reuse it, as FastAPI's lifespan does (see "Using it with FastAPI,
Django and Flask"); it must not outlive its event loop.

## One call per service

```python
# Scheduling: open appointment slots in a state, as a FHIR Bundle of Slots.
slots = client.search_slot(location_address_state="MA", count=10)

# Provider directory: a practitioner by NPI, from CMS's National Provider Directory.
practitioners = client.search_practitioner(identifier="1093209884")

# Terminology: a LOINC code's display and properties.
glucose = client.code_system_lookup(system="http://loinc.org", code="2345-7")

# Questionnaires: a form by its id, such as the PHQ-9.
phq9 = client.read_questionnaire("44249-1")

# Medical Benefits: a Medicare Advantage or ACA Marketplace plan, and which providers are in its network.
plan = client.read_insurance_plan("H2406-013-000")
network = client.check_insurance_plan_network("H3359-038-000", npi=["1518929058"])

# Pharmacy Benefits: what a medication would cost, as the CARIN pharmacy benefit check, from a FHIR
# message Bundle. It is not yet open to customers.
checked = client.process_message(message)

# MedList: one reconciled medication list from one patient's FHIR medication records. It receives
# patient data, so send it only under an executed agreement. Test data labelled as such works on every
# plan, and mark_as_test_data labels a request and every resource in it. Label only made-up data.
reconciled = client.reconcile_medications(records)

# Structured Sig: a prescription's free-text directions as a FHIR Dosage, each element coded where the
# words support it and a review flag on anything to check. Send the directions, never a patient.
from haau3 import structure_dosage_request

structured = client.structure_dosage(structure_dosage_request("Take 1 tablet by mouth twice daily"))

# The Sandbox: the same calls, answered with fixed answers and a test insurer's synthetic data. A test
# key sends every call there (see "The Sandbox" below). Its pharmacy benefit check answers its test
# members only (https://docs.haau3.com/sandbox/example-health-plan).
sandbox = Haau3(api_key=test_key)
sandbox_checked = sandbox.process_message(sandbox_message)
```

Every method, grouped by service, with its request and a link to its page on docs.haau3.com, is in
[api.md](https://github.com/haau3/haau3-python/blob/main/api.md). Each is named by its operationId
in snake_case, and so is each query parameter: `name:contains` is `name_contains`, `_count` is
`count`, `serviceTypeCode` is `service_type_code`. Each method's docstring gives both names.

## The Sandbox

The Sandbox, `https://sandbox.haau3.com`, is the API's environment to build and test against. It
serves production's operations at production's paths: each answers its documented example request
with a fixed answer, and the pharmacy benefit check is answered by a test insurer with synthetic
data. See [docs.haau3.com](https://docs.haau3.com/authentication) for what it answers and its limits.

Your key's mode picks where the client sends every call. A test key (`haau3_sk_test_…`) goes to
the Sandbox, and a live key (`haau3_sk_live_…`) to production, so `HAAU3_API_KEY` alone moves an app
from one to the other. The Sandbox also answers with no key at all. With `HAAU3_API_KEY` unset, name
it as the environment:

<!-- not run: it needs HAAU3_API_KEY unset -->
```python
sandbox = Haau3(environment="sandbox")  # or set HAAU3_ENVIRONMENT=sandbox
statement = sandbox.fhir_metadata()
print(sandbox.environment, sandbox.base_url)  # sandbox https://sandbox.haau3.com
```

A key made before test and live keys goes to production, as a live key does. These are refused when
the client is made, before anything is sent. The error says where the key came from, and its `code`
says which it is:

- a test key with `environment="production"` (`test-key-outside-sandbox`);
- a live key, or one made before test and live keys, with `"sandbox"` or with the Sandbox's address
  as the `base_url` (`live-key-in-sandbox`, `older-key-in-sandbox`);
- no key without the Sandbox named (`no-api-key`);
- an `environment` that a `base_url` on the other environment's address contradicts
  (`environment-conflicts-with-base-url`);
- a key with anything before its `haau3_sk_` prefix, such as the quotes an env file kept
  (`api-key-not-alone`).

`environment` and `base_url` on the client say what it resolved.

`sandbox_process_message` and `sandbox_metadata`, the Sandbox's first address at
`/v1/sandbox/fhir/r4`, are deprecated: call `process_message` and `fhir_metadata` instead. Until the
address goes, a client sending to the Sandbox's own host sends them to those operations there. The
raw `request()` sends a path as it is given, so a first-address path sent on a test key goes to the
Sandbox's host, which does not serve it.

## With an AI coding agent

An agent can read the docs directly:

- [docs.haau3.com/llms.txt](https://docs.haau3.com/llms.txt) lists every docs page as Markdown.
- [docs.haau3.com/skill.md](https://docs.haau3.com/skill.md) is an
  [Agent Skill](https://agentskills.io/specification) that says what the platform does and how to call
  it. `npx skills add https://docs.haau3.com` adds it to your project's coding agents.
- `https://docs.haau3.com/mcp` is an MCP server that searches the docs. To add it:
  - Claude Code: `claude mcp add --transport http haau3 https://docs.haau3.com/mcp`
  - Codex: `codex mcp add haau3 --url https://docs.haau3.com/mcp`
  - Cursor, in `.cursor/mcp.json`: `{ "mcpServers": { "haau3": { "url": "https://docs.haau3.com/mcp" } } }`
  - VS Code: `code --add-mcp '{"name":"haau3","type":"http","url":"https://docs.haau3.com/mcp"}'`

The [haau3 command line](https://github.com/haau3/haau3-cli) lets an agent act without ever seeing
a key. `npx haau3 doctor --json` checks the project's setup, and `npx haau3 test --json` makes one
call to each service, in the Sandbox when there is no key. `npx haau3 login`, then
`npx haau3 keys create`, puts a key in the project's env file after a person approves in the
browser.

## Options

| Option | Default | |
|---|---|---|
| `api_key` | `os.environ["HAAU3_API_KEY"]` | Your platform API key. A test key calls the Sandbox, a live key production. |
| `environment` | `os.environ["HAAU3_ENVIRONMENT"]`, then the key's mode | `"production"` or `"sandbox"`. Name `"sandbox"` to call it with no key. |
| `base_url` | `os.environ["HAAU3_BASE_URL"]`, then the environment's address | Where the API is, for a stand-in or a proxy. The API key is sent there only. |
| `timeout` | `65.0` | Seconds one attempt may take. |
| `max_retries` | `1` | Retries after a timeout, a network failure, a 429 or a 5xx. |
| `http_client` | a new `httpx2.Client` (`httpx2.AsyncClient` for `AsyncHaau3`) | Your own, for a proxy, certificates or connection limits. |
| `app_info` | none | Your app's name, version and URL, sent in the User-Agent after the SDK's own. |

Each call takes `timeout`, `max_retries`, `correlation_id` and `extra_headers` as keywords, for
that call only:

```python
client.search_slot(location_address_state="MA", timeout=10, max_retries=0)
```

An operation that declares a header of its own takes it as one more keyword, named from the header
and typed from the spec. `process_message` takes `payer_authorization`, sent as
`Payer-Authorization`: a member's own authorization at their insurer, `Bearer` and the access token
your app got from the member's login there. The SDK checks it against the form the API takes before
sending, refuses one the API would not take without repeating it, and holds it where nothing prints
it, a traceback's local variables included.

```python
checked = client.process_message(message, payer_authorization=f"Bearer {access_token}")
```

`http_client` passes anything [httpx2](https://github.com/pydantic/httpx2) takes: a proxy,
certificates, limits, event hooks, a transport. The SDK's own method, URL, headers, body and
timeout always win, it never follows a redirect, and it never closes a client you pass.

<!-- not run: it needs a proxy -->
```python
import httpx2

proxied = Haau3(http_client=httpx2.Client(proxy="http://proxy.internal:8080"))
```

httpx2 checks the API's certificate against your operating system's trust store, or against the
file `SSL_CERT_FILE` names. In a slim container with no CA certificates, install them, set
`SSL_CERT_FILE`, or pass `http_client=httpx2.Client(verify=ssl.create_default_context(cafile=...))`.

`app_info` names your app in the User-Agent, after the SDK's own, when you build a library, a plugin
or a command line on the SDK. It takes a `name`, and a `version` and a `url` if you have them, and
every request the client sends carries them:

```python
named = Haau3(app_info={"name": "my-plugin", "version": "1.2.0"})
# User-Agent: haau3-python/<version> (python 3.13; httpx2 <version>) my-plugin/1.2.0
```

A name and a version each take letters, digits, `-`, `.`, `_` and the other characters RFC 9110
allows in a User-Agent product, with no space or slash. A `url` is an http or https URL, sent in
parentheses after them. Anything else is refused when the client is made, before a request is sent.
A `user-agent` in a call's `extra_headers` replaces the whole User-Agent, the SDK's part included.
`AppInfo` types the dict.

A retry waits a short, growing interval, or what the API's `Retry-After` header says when that is
60 seconds or less. A longer `Retry-After` fails at once, carrying it. Nothing is cached: every call
asks the API.

An async attempt ends at its timeout exactly. A sync attempt's timeout bounds connecting and each
read, and is checked between parts of the answer, so one read that stalls can run past it by up to
the timeout again.

## Errors

Every error is a `Haau3Error`, with the `request_id` the API answered with. There are four kinds:

```python
from haau3 import AuthError, ForbiddenError, NoAnswerError, RefusedError

try:
    client.read_insurance_plan(plan_id)
except RefusedError as error:
    print(error.status)  # 400, 404, 410 and so on
    print(error.code)  # why, when the API names it: "not-the-example" from the Sandbox
    print(error.outcome)  # the OperationOutcome the API answered with
except NoAnswerError as error:
    print(error.reason)  # "timeout", "network", "rate-limited", "unavailable", "server-error" or "unreadable"
    print(error.retry_after)  # seconds, when the API said
    print(error.detail)  # for a timeout or a network failure: what failed, such as "ConnectError: Connection refused"
except ForbiddenError as error:
    # 403: the key was accepted, and it may not make this request. Why, when the API names it:
    # "test-key-outside-sandbox", "live-key-in-sandbox", "phi-agreement-required" or "not-open-to-customers"
    print(error.code)
except AuthError:
    pass  # 401: the key was missing, unknown or revoked
```

A 403 is a `ForbiddenError`, never an `AuthError`: the key was accepted, so there is nothing to
rotate. Its `code` says why when the API names it, and its message says the same in words. A test
key works only in the Sandbox (`test-key-outside-sandbox`: send a live key), and a live key does not
work there (`live-key-in-sandbox`: send a test key). The client sends each key to its own
environment, so you meet these with a `base_url` of your own, or by calling the deprecated
`sandbox_…` methods with a live key. `phi-agreement-required` means the organization
may not send patient data, and not every resource in the request is labelled as test data:
`mark_as_test_data` labels made-up data. `not-open-to-customers` means the operation is not yet
open to customers: an expected answer, not a fault in the request. Without a code, the body says what
the organization may not do.

A `RefusedError`'s `code` names the API's reason when it gives one: `not-the-example` from the
Sandbox, which answers each operation's documented example only and refuses any other request.

A client that cannot be made raises a `Haau3Error` before anything is sent, with a `code` to branch on,
which the `ClientErrorCode` type lists. The message says the same for a person and names where the
value came from, the keyword or the variable:

```python
from haau3 import Haau3, Haau3Error

try:
    configured = Haau3()
except Haau3Error as error:
    if error.code == "no-api-key":
        pass  # set HAAU3_API_KEY, or name the Sandbox to call it with no key
```

The codes are `no-api-key`, `invalid-api-key`, `api-key-not-alone`, `test-key-outside-sandbox`,
`live-key-in-sandbox`, `older-key-in-sandbox`, `invalid-environment`, `invalid-base-url`,
`environment-conflicts-with-base-url`, `invalid-app-info`, `invalid-http-client` and `in-browser`. The
two the API also answers with keep the API's names.

When `HAAU3_API_KEY` has no value but `.env.local` or `.env` in the current folder sets it, the
`no-api-key` message names that file and says how to load it. The SDK looks there only when it has no
key from `HAAU3_API_KEY`, opens only a regular file, and never keeps or shows the value.

No answer is never reported as an empty result, and an empty result is never an error. Every error
the API answered carries `attempts`, `duration_ms` and `reason_phrase` too.

An error's message never includes the body the API answered with, and the body (`outcome`) is
never printed when the error is: not by `str()`, `repr()` or a traceback, and not among a
traceback's local variables, which some error reporters record. A request body you sent is
held the same way. An error pickles, for Celery or multiprocessing, with every field but its body.

A FHIR answer is checked against the resource types its operation answers with. Anything else, a
`Bundle` where an `InsurancePlan` was asked for, say, is a `NoAnswerError` with reason
`"unreadable"`. The check is of the resource type, not of every element inside it: those are typed
as FHIR R4 declares them, and the SDK does not validate each one.

`error.to_dict()` gives an error as a dict that is safe to log: its name, its message and the fields
above that are set, and never the body or the cause.

```python
import logging

from haau3 import Haau3Error

try:
    client.read_insurance_plan(plan_id)
except Haau3Error as error:
    logging.getLogger(__name__).warning("the plan read failed", extra={"haau3": error.to_dict()})
```

## Request ids and timing

`client.with_response` has every method again, each returning a `Response`: the answer as `data`,
with the request id and timing that came with it, in the same names `request()` uses.

```python
response = client.with_response.read_insurance_plan(plan_id)
print(response.data.get("name"), response.request_id, response.duration_ms, response.attempts)
```

It carries `status` and `reason_phrase` too: the answer's own text, or the standard one (`"OK"`) when
it came with none, as HTTP/2 answers do.

Quote the `request_id` when you ask for help: it finds the request in the API's own logs.

To find a request by an id of your own, such as your job's or your trace's, pass it as
`correlation_id`. It must be a UUID, which is all the API keeps; anything else is refused before it
is sent. The API keeps it with its record of the request, and it comes back on the answer and on
every error the API answered:

```python
response = client.with_response.read_insurance_plan(plan_id, correlation_id=job_id)
print(response.correlation_id)
```

## Paging

`pages()` yields a FHIR search's first page and every page after it, following each `next` link on
the client's own host:

```python
first = client.search_insurance_plan(coverage_area_state="NC")
for page in client.pages(first):
    for entry in page.get("entry", []):
        resource = entry.get("resource")
        if resource is not None:
            print(resource.get("id"))
```

When the next page is asked for in a later request, as a web page's "Load more" does, there is no
page to hand `pages()`. `next_cursor()` reads the cursor from a page's `next` link, with no request,
and a search takes it back as `page`:

```python
from datetime import datetime, timezone

# The search, its moment chosen once and kept: the cursor belongs to it.
start = ["ge" + datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")]
first = client.search_slot_with_includes(status="free", start=start, location_address_state="TX")
cursor = client.next_cursor(first)  # None on the last page

# Later, in another request, with the same search:
if cursor:
    second = client.search_slot_with_includes(status="free", start=start, location_address_state="TX", page=cursor)
```

A cursor belongs to its search: send it with every other parameter exactly as before. A Slot,
Schedule or plan search refuses a cursor sent with its search changed (a `400`), and that includes a
parameter the API fills in for you, as the page's `self` link shows: for a Slot search, send `status`
and `start` yourself when you will page this way, since their defaults are free Slots from the moment
of the first request. A cursor does not last: the provider directory's searches say their cursors
expire, and a plan search answers `410` once the plans are updated, so start the search again.
`next_cursor()` raises a `Haau3Error` when a next link is not a URL, or carries no cursor or two. The
plain function `haau3.next_cursor()` does the same with no client.

`resources()` yields every resource the search found, across every page:

```python
for resource in client.resources(first):
    if resource["resourceType"] == "InsurancePlan":
        print(resource.get("name"))
```

It yields each entry whose search mode is `match`, or says none. A resource an `_include` or
`_revinclude` brought, and a search's own `OperationOutcome`, are not among them; `pages()` gives
every entry. From async code, `async for page in async_client.pages(first)` and `async for resource
in async_client.resources(first)`.

`matches()` gives one page's matches of a type, typed, with no request, and `resolve()` finds the
resource a reference names in that page, such as one an `_include` brought:

```python
page = client.search_healthcare_service(
    service_category="pharm",
    location_address_state="FL",
    location_address_postalcode="33131",
    include=["HealthcareService:organization", "HealthcareService:location"],
)

for pharmacy in client.matches(page, "HealthcareService"):
    organization = client.resolve(page, pharmacy.get("providedBy"), type="Organization", from_=pharmacy)
    stores = [client.resolve(page, place, type="Location", from_=pharmacy) for place in pharmacy.get("location", [])]
    print(pharmacy.get("name"), organization and organization.get("name"), [s.get("name") for s in stores if s])
```

`resolve()` follows FHIR's rules for references in a Bundle: an absolute reference is the entry with
that `fullUrl`; a relative one is resolved against the address of the entry holding it when you pass
that resource as `from_`, and otherwise is the one entry whose address ends in that type and id; `#id`
is found in `from_`'s `contained`. It is `None` when the page does not hold the resource, and raises a
`Haau3Error` when two entries could be the one meant, when the resource is not of `type`, for a `#`
reference with no `from_`, and for a `from_` that is not an entry of the page. `type` is a
resource type's name and types the result, as `matches()`'s does: `client.matches(page, "Slot")` is a
`list[fhir.Slot]`. Both are plain functions too, `haau3.resolve()` and `haau3.matches()`.

## A value a person typed

`escape_search_value()` escapes FHIR's special characters in a search value (`\`, `,`, `$` and `|`
each take a `\` before them), so the API reads what a person typed as the one value it is:

```python
import haau3

typed_city = "Austin, TX"  # what a person typed
page = client.search_slot_with_includes(location_address_city=haau3.escape_search_value(typed_city))
```

Unescaped, a comma separates values the API reads as "or", so `Austin, TX` asks for two cities, and a
trailing comma is refused with a `400`. Never escape a value you built with `,` or `|` on purpose,
such as a list of codes or a `system|code` token.

## Slots and schedules

A Slot search answers a FHIR Bundle whose matches are `Slot`s; each Slot's `Schedule`, and the
`Location` and provider the Schedule names, come in the same Bundle when the search asks for them
with `_include`. `search_slot_with_includes()` sends every include the Slot search serves, and
`slot_views()` hands you each matched Slot with what the page holds for it, side by side, each the
FHIR resource the API served:

```python
page = client.search_slot_with_includes(location_address_state="MA", count=10)

for view in client.slot_views(page):
    who = [
        name.get("text") or " ".join([*name.get("given", []), name.get("family", "")]).strip() or None
        for practitioner in view.practitioners
        for name in practitioner.get("name", [])
    ]
    where = [location.get("name") for location in view.locations]
    print(view.slot.get("start"), who[:1], where[:1], view.booking_link or view.booking_phone)
```

| Field | What it holds |
|---|---|
| `slot` | The matched `Slot`. |
| `schedule` | Its `Schedule`. Every Slot names one. |
| `locations` | Every `Location` the Schedule reaches: its Location actors, then the Locations of each `HealthcareService` it names. |
| `practitioner_roles` | The `PractitionerRole`s the Schedule names. |
| `practitioners` | The `Practitioner`s it names, then the Practitioner behind each role. |
| `healthcare_services` | The `HealthcareService`s it names. |
| `booking_link` | The Slot's booking link, from its `booking-deep-link` extension. |
| `booking_phone` | The number to book it by, from its `booking-phone` extension. |
| `patient_type` | Whom it accepts, from its `patient-type` extension, as one of HL7's four codes: `newpt`, `existptonly`, `existptfam` or `nopt` (the API never serves a `nopt` Slot). |
| `virtual` | `True` when a Location's physical type is `vi`, and `False` otherwise: a Location is physical unless it says it is virtual, and a place that is both is two Locations. |

A view is a frozen dataclass, `haau3.SlotView`, that compares by value and cannot be hashed (it
holds dicts), and each list is a tuple that keeps the order the
Schedule names them in, holds each resource once, and is empty when there is none: a Schedule may
name a Location and no provider. The three extensions are read under SMART Scheduling Links 1.0.0's
own URLs; the Slot itself keeps whatever its publisher sent. Nothing is fetched and nothing is
replaced in place. A resource the page does not hold is left out, and so is one of another type than
the reference's element allows; a contained resource is found in the entry that contains it, as FHIR
says. `resolve()` finds anything else a reference names.

`slot_views()` raises a `Haau3Error` in two cases. A Slot names a Schedule the page does not hold,
which happens when the page was searched without its includes, so the message says to search with
`search_slot_with_includes()`. Or, as `resolve()` does, two entries could each be the one a
reference names.

The helper takes every keyword `search_slot()` takes but `include` and `include_iterate`, which
Python refuses before anything is sent, and it sends nothing else, so the API's defaults hold: free
Slots, from now. To send your own includes, call `search_slot()`. A page's `next` link is followed
with `pages()`, and `slot_views()` reads each page.

`search_schedule_with_includes()` and `schedule_views()` do the same for the Schedule search: each
matched Schedule as a `haau3.ScheduleView`, with its `locations`, `practitioner_roles`,
`practitioners`, `healthcare_services` and `virtual`. A `SlotView` is a `ScheduleView` too.
`slot_views()` and `schedule_views()` are plain functions as well, for a page read elsewhere, and
from async code the helpers are awaited while the views are not.

## Reading a Parameters answer

FHIR operations answer with a `Parameters` resource whose parts are named: `$lookup`'s `display` and
`property` parts, `$structure-dosage`'s `dosage` part. `parameters()` gives every part with a name and
`parameter()` the one, both with no request, as FHIR's own SDKs read one (Firely's `Get` and
`GetSingleValue`, HAPI's `ParametersUtil`). A part holds its value in the `value[x]` its operation
names. `parameter()` raises when two parts share the name.

```python
lookup = client.code_system_lookup(system="http://loinc.org", code="2345-7")
display = client.parameter(lookup, "display")
print(display.get("valueString") if display else None)
```

Each is a client method and a plain function of the package, `haau3.parameters()`,
`haau3.parameter()` and `haau3.review_flags()`, so an answer you stored can be read with no client
and no key.

## Reading a lookup and a validation

`lookup_result()` reads a `$lookup` answer, typed: the code, its system and version, its display,
whether it is `abstract` (not for use, such as an ICD-10-CM header), every designation and every
property. A property's `type` names the FHIR type of its `value`, so checking it narrows the value.
`designations()` finds a code's names by use and language: a use by its system and code together, a
language as RFC 4647 matches one, so `en` finds `en-US`. ICD-10-CM's short title is its `SYNONYM_USE`
designation, where it differs from the display, and every code system the API holds names the display
again with `PREFERRED_FOR_LANGUAGE_USE`.

```python
from haau3 import SYNONYM_USE, designations

icd_answer = client.code_system_lookup(system="http://hl7.org/fhir/sid/icd-10-cm", code="E08.37X1")
icd_lookup = client.lookup_result(icd_answer)
print(icd_lookup.display, icd_lookup.abstract)
short_titles = designations(icd_lookup, use=SYNONYM_USE, language="en")
print(short_titles[0].value if short_titles else None)
for prop in icd_lookup.properties:
    if prop.type == "boolean":
        print(prop.code, prop.value)
```

`validation_result()` reads a `$validate-code` answer, from a code system or a value set: `result`,
`display` and `message`. A display that does not match answers `result` False with the code's own
display beside it, which means the code is valid and only the label differs.

```python
check = client.validation_result(
    client.code_system_validate_code(url="http://loinc.org", code="2345-7", display="Glucose")
)
if not check.result:
    print(check.message, check.display)
```

A part either reader does not know is kept, as the answer gave it, in the `other` tuple of the level it
was found at, and a part FHIR allows once that comes twice raises. Each is a client method and a plain
function of the package, `haau3.lookup_result()`, `haau3.validation_result()` and
`haau3.designations()`, so an answer you stored can be read with no client.

## Structured Sig

`structure_dosage_request()` builds the request `$structure-dosage` takes from the directions and,
optionally, the medication's codings, RxNorm or NDC, as a FHIR CodeableConcept. `RXNORM_SYSTEM` and
`NDC_SYSTEM` are their code systems. It is a plain function, so it builds a batch entry too
(`calls.structure_dosage(structure_dosage_request(text))`).

The answer is one `dosage` part, a FHIR `Dosage`, with a review flag on anything a person should
check. `review_flags()` reads each flag's code, display and the words of the directions it is about,
and the versions the Dosage names:

```python
from haau3 import RXNORM_SYSTEM, review_flags, structure_dosage_request

structured_answer = client.structure_dosage(
    structure_dosage_request(
        "Take 1 tablet by mouth daily",
        medication={"coding": [{"system": RXNORM_SYSTEM, "code": "311354"}]},
    )
)
part = client.parameter(structured_answer, "dosage")
if part and "valueDosage" in part:
    review = review_flags(part["valueDosage"])
    for flag in review.flags:
        print(flag.code, flag.display, flag.words)
    print(review.engine_version, review.vocabulary_version, review.rxnorm_release)
```

## Several requests in one

`batch()` sends several operations of the FHIR base as one request. Each entry comes from
`haau3.calls`, whose functions are called as the client's methods of the same name are, and gets its
own result, in the order given:

```python
from haau3 import BatchOk, calls

plan_result, counties_result = client.batch(
    calls.read_insurance_plan("H2406-013-000"),
    calls.list_insurance_plan_counties(state="NC"),
)

if isinstance(plan_result, BatchOk):
    print(plan_result.data.get("name"))  # an InsurancePlan
else:
    print(plan_result.error)  # a RefusedError or a NoAnswerError, as read_insurance_plan alone would have raised
```

A result is a `BatchOk` (`data`, `status`) or a `BatchError` (`error`), typed by position for up to
six entries; `match result: case BatchOk(data=data): ...` works too. Each also has `ok`, `True` or
`False`, which reads well in a log; `isinstance` and `match` are what tell a type checker which it
is. A list built in code works the same way:

```python
lookups = client.batch(
    *(calls.code_system_lookup(system="http://loinc.org", code=code, property="SHORTNAME") for code in codes)
)
```

Each entry is checked as the call alone is, and fails alone while the others answer. An entry that
fails is not retried. The batch itself is retried, and raises, as any call does, and
`client.with_response.batch(...)` gives its request id. The API takes up to 100 entries in up to 1
MiB and gives a batch 60 seconds, so send a longer list as several batches. Every operation on the
FHIR base can go in a batch except `fhir_batch`, `process_message` and `reconcile_medications`, which
the spec marks `x-haau3-batchable: false`.

To send a batch `Bundle` you built yourself, `fhir_batch()` takes it and returns the
`batch-response` as it is.

## Any operation by its path

`get()` and `post()` call an operation by its path: one this version of the SDK has no method for
yet, or one a tool found in the spec. Each takes the path as the spec writes it, a value for each
`{name}` in `path_params`, the `query`, the `body` (for `post()`) and the FHIR types the answer may
be in `expects`, beside every per-call option. They raise the same errors as every operation's own
method, and `with_response.get()` and `with_response.post()` return the request id and timing too:

```python
practitioner = client.get(
    "/v1/fhir/r4/Practitioner/{id}",
    path_params={"id": "Practitioner-1093209884"},
    expects=["Practitioner"],
)
metadata = client.with_response.get("/v1/fhir/r4/metadata", expects=["CapabilityStatement"])
print(metadata.request_id)
```

Each value is encoded into the path, and an error's message names the path as you wrote it, never a
value. A `{name}` with no value, or a value with no `{name}`, is refused before anything is sent.

## Any request

`request()` sends a request as you give it and returns what the API answered, whatever the status,
with its headers, request id, attempts and duration:

```python
raw = client.request("GET", "/v1/fhir/r4/metadata")
print(raw.status, raw.reason_phrase, raw.request_id)
```

## Using it with FastAPI, Django and Flask

Each of these is a complete, tested example in [examples/](https://github.com/haau3/haau3-python/tree/main/examples):

- **FastAPI** ([fastapi_app.py](https://github.com/haau3/haau3-python/blob/main/examples/fastapi_app.py)):
  an `AsyncHaau3` made in the app's lifespan, handed to each route by a dependency, and closed when
  the app stops.
- **Django** ([django_view.py](https://github.com/haau3/haau3-python/blob/main/examples/django_view.py)):
  one `Haau3` for the whole process, shared by every request and thread.
- **Flask** ([flask_app.py](https://github.com/haau3/haau3-python/blob/main/examples/flask_app.py)):
  one `Haau3` on the app. Flask runs each async view in an event loop of its own, which an
  `AsyncHaau3` must not outlive, so async views use the sync client too.
- **A script** ([plans_to_csv.py](https://github.com/haau3/haau3-python/blob/main/examples/plans_to_csv.py)):
  every page of a plan search, written to CSV, with the client as a context manager.

## Testing your code

Pass an `httpx2.Client` with a `MockTransport`, and your code calls the SDK as it always does:

```python
import httpx2

from haau3 import Haau3


def answer(request: httpx2.Request) -> httpx2.Response:
    return httpx2.Response(200, json={"resourceType": "InsurancePlan", "id": "H2406-013-000"})


test_client = Haau3(api_key="test", http_client=httpx2.Client(transport=httpx2.MockTransport(answer)))
assert test_client.read_insurance_plan("H2406-013-000").get("id") == "H2406-013-000"
```

To run code you have not changed against a stand-in API of your own, set `HAAU3_BASE_URL` to its
address: a client built with no `base_url` sends there, and nowhere else.

## Versions

The SDK is `0.y.z` while the API is in preview: a minor release may change what a method takes or
answers, and a patch release never does. [CHANGELOG.md](https://github.com/haau3/haau3-python/blob/main/CHANGELOG.md)
lists every release, and a release that takes a new version of the API's spec names that version;
`haau3.SPEC_VERSION` is the one a release was generated from.

## License

[MIT](https://github.com/haau3/haau3-python/blob/main/LICENSE)
