> ## Documentation Index
> Fetch the complete documentation index at: https://openloop.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Integration flow

> Intake end to end: create the patient, fetch the questionnaire, submit answers keyed by link_id, and store the encounter id the submit returns.

By the end of this page you will know the whole journey — which call comes next, which record
links to which, and the two places an intake can fail silently.

If you are staging your build, start with *The first leg* below and ignore the rest for now.

## What you'll do

**1. Create the patient**

`POST /v0.1/patients` with a phone in E.164 — the response carries the patient id.

**2. Select the active questionnaire**

`GET /v0.1/questionnaires?status=active`, then choose by `status`, never by list position.

**3. Submit the intake**

`POST /v0.1/questionnaire-responses` with a `subject` and `status: "completed"`. The platform
creates the encounter and returns its id.

**4. Take payment**

`POST /v0.1/checkouts/sessions` with the price's `provider_price_id`.

**5. Receive the outcome**

Order status and tracking arrive as prescription webhook events at an endpoint you register
with OpenLoop (by arrangement) — see *Order status and tracking*. There is no order read.

## The short answer on orders

**You never create an order, and you cannot read one.** A clinician reviews the intake and
prescribes; the charting note that records the prescription is what triggers the medication
order, and the platform then hands it to the pharmacy.

So your integration takes payment and then **listens**. OpenLoop sends a signed prescription webhook
event to an HTTPS endpoint you give your implementation contact (by arrangement — there is no
self-serve registration): `prescription.created`, `prescription.ordered`, `prescription.shipped`
and `prescription.cancelled`. Each event carries the order's `data.status` and
`data.timestamps.*`, plus `data.carrier` and `data.tracking_ref` once it ships.
There is no partner order read; order status and tracking arrive as these events. Payment state is
**not** on them — read it from the billing events or `GET /v0.1/subscriptions` / `GET /v0.1/invoices`
(see *Payments and checkout*). *Order status and tracking* and *Prescription events* have the event
attributes.

> [!WARNING]
>
> **Key the events to your patient on `data.emr_patient_id`, your `/v0.1` patient id, when the event
> carries it.** It is the `id` that `GET /v0.1/patients/{id}` takes, omitted when the id isn't known,
> never `null`. Without it the event has only `data.patient_ref`, an opaque OpenLoop reference that is
> not guaranteed to be the `/v0.1` patient id, and no email. How a tenant whose patients exist only
> through `POST /v0.1/patients` correlates such an event is agreed with your implementation contact
> when the endpoint is registered.

## The short answer on encounters

**You do not create the encounter, and you do not send us an encounter id.** Submit the intake
with a `subject` reference and `status: "completed"`, and the platform creates the intake
encounter for you and returns its id on the response.

Two consequences worth internalising before you build:

1. **`encounter_id` is a value you store, not a resource you read.** The `201` from the submit
   and `GET /v0.1/questionnaire-responses/{id}` both carry it; encounters themselves are not
   readable on the partner surface. Store it beside the response id: it is the key that brings the
   clinician's encounter note back to you, through `data.encounter_id` on the `intake.*` and
   `charting.*` events and the `encounter_id` filter on `GET /v0.1/questionnaire-responses` (staging
   only for now). See [Encounter notes](https://openloop.mintlify.site/cookbook/encounter-notes.md).
2. **With several concurrent medications, each intake has its own response and its own
   `encounter_id`.** Keying your own records by questionnaire-response id is sufficient.

`encounter_id` **is** accepted on submit and honoured if you send it, in which case no encounter is
created for you. Use that only when attaching a response to an encounter you already
have. For the standard intake flow, omit it.

Encounters are not readable on the partner surface, and there is no create, update or delete. An encounter created by
a test submission stays in the tenant — keep test patients separate from real ones.

## The first leg — patient, intake, payment

If you are staging your integration, this is the slice to build first. It stops at payment and
needs nothing downstream of it.

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant You as Your funnel
    participant API as OpenLoop API

    You->>API: POST /v0.1/auth/token
    API-->>You: 200 { data: { access_token } }

    You->>API: POST /v0.1/patients
    API-->>You: 201 { data: { id } }

    You->>API: GET /v0.1/questionnaires?status=active
    API-->>You: 200 { items[] }
    Note over You,API: OpenLoop defines the questions. You choose how to present them

    You->>You: Render, group and order the questions as you like
    You->>API: POST /v0.1/questionnaire-responses
    Note right of You: answers is an OBJECT keyed by the item link_id, not an array
    API-->>You: 201 { data: { id, encounter_id } }

    You->>API: GET /v0.1/products/{product_id}/prices
    API-->>You: 200 { items[] with provider_price_id, billing_interval }

    You->>API: POST /v0.1/checkouts/sessions
    API-->>You: 200 { data: { provider_checkout_session_id, url } }
    Note over You,API: Redirect the patient to url. Order status arrives later as webhook events — see the full sequence
```

## Sequence — the whole journey

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant You as Your funnel
    participant API as OpenLoop API
    participant Clin as Clinical review + pharmacy

    You->>API: POST /v0.1/patients
    Note right of You: first_name, last_name, email, phone (E.164), birth_date
    API-->>You: 201 { data: { id } }

    You->>API: GET /v0.1/questionnaires?status=active
    API-->>You: 200 { items[] }
    Note over You,API: Select by status, never by list position

    You->>You: Render questions, collect answers
    You->>API: POST /v0.1/questionnaire-responses
    Note right of You: questionnaire_id, subject {id,type:Patient}, status:"completed", answers {link_id: {value_*}}
    API->>API: Creates the intake Encounter
    API-->>You: 201 { data: { id, encounter_id } }
    Note over You,API: Store the response id and encounter_id together. Encounters are not readable

    You->>API: POST /v0.1/checkouts/sessions
    Note right of You: customer_data needs email AND name; items need provider_price_id; type must match billing_interval
    API-->>You: 200 { data: { provider_checkout_session_id, url } }

    Note over You,API: There is no order endpoint for you to call

    Clin->>Clin: Clinical review and prescription (charting note creates the order), then the pharmacy fills and ships
    Clin-->>You: POST to your registered endpoint: prescription.created … prescription.shipped
    Note over Clin,You: By arrangement. data.emr_patient_id is your v0.1 patient id when known; data.tracking_ref once shipped
```

## Relational model

```mermaid theme={null}
erDiagram
    PATIENT ||--o{ QUESTIONNAIRE_RESPONSE : "subject"
    QUESTIONNAIRE ||--o{ QUESTIONNAIRE_RESPONSE : "questionnaire_id"
    QUESTIONNAIRE_RESPONSE ||--|| ENCOUNTER : "encounter_id (stored, not readable)"
    PATIENT |o--o{ PRESCRIPTION_EVENT : "emr_patient_id, when known"

    QUESTIONNAIRE_RESPONSE {
        string id
        string questionnaire_id
        object subject "id + type Patient"
        string status "completed to trigger encounter"
        string encounter_id "returned, links forward"
    }
    ENCOUNTER {
        string id "returned as encounter_id; not partner-readable"
    }
    PRESCRIPTION_EVENT {
        string id "envelope id (dedupe on it)"
        string type "prescription.created ... prescription.cancelled"
        string resource_id "data.resource_id: the prescription key"
        string emr_patient_id "data.emr_patient_id: the v0.1 patient id, when known"
        string patient_ref "data.patient_ref: opaque, not guaranteed to be the v0.1 patient id"
        string status "data.status: created|ordered|shipped|delivered|cancelled|unknown"
        string tracking_ref "data.tracking_ref: set once shipped"
    }
```

`PRESCRIPTION_EVENT` links to `PATIENT` through `data.emr_patient_id`, the patient's `/v0.1` id, when
the event carries it. An event without it has only the opaque `data.patient_ref`, and how that maps to
a `/v0.1` patient is agreed per tenant when the webhook endpoint is registered.

## Recipe 2.1 · Create the patient

`phone` must be E.164. A national format is rejected with a `400`, so normalise before you send.

```bash curl theme={null}
curl -X POST https://api-staging.openloophealth.com/v0.1/patients \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "first_name": "Jordan",
    "last_name": "Avery",
    "email": "jordan.avery@example.com",
    "phone": "+15555550142",
    "birth_date": "1990-04-12",
    "gender": "male"
  }'
```

```json Response theme={null}
{ "data": { "id": "<patient id>" }, "request_id": "..." }
```

The same body with `"phone": "(312) 555-0142"` returns `400` with
`phone: phone must be E.164 format`.

> [!TIP]
>
> Locked by check `phone-must-be-e164`.

## Recipe 2.2 · Select the active questionnaire

Select by `status`, never by list position — the order is not a contract.

```bash curl theme={null}
curl "https://api-staging.openloophealth.com/v0.1/questionnaires?status=active" \
  -H "authorization: Bearer $TOKEN"
```

```json Response theme={null}
{ "items": [ { "id": "<questionnaire id>", "title": "...", "status": "active", "items": [ ... ] } ],
  "request_id": "..." }
```

In a multi-program tenant `?status=active` returns every active form, so narrow it as
*Programs and identifiers* describes, then hold the id in your own configuration.

> [!TIP]
>
> Locked by check `select-active-questionnaire`.

## Recipe 2.3 · Submit the intake and take payment

Submit with a `subject` and `status: "completed"`, and the platform creates the intake encounter
and returns its id.

```bash curl theme={null}
curl -X POST https://api-staging.openloophealth.com/v0.1/questionnaire-responses \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "questionnaire_id": "<questionnaire id>",
    "subject": { "id": "<patient id>", "type": "Patient" },
    "status": "completed",
    "answers": { "q1": { "value_string": "210 lb" } }
  }'
```

```json Response theme={null}
{ "data": { "id": "<response id>", "encounter_id": "<encounter id>" }, "request_id": "..." }
```

The encounter itself is not readable; store `encounter_id` with the response id.

> [!TIP]
>
> Locked by check `intake-creates-encounter`.

Then take payment. `type` must match the price you are selling — `subscription` for a recurring
price — and `items` take the price's `provider_price_id`:

```bash curl theme={null}
curl -X POST https://api-staging.openloophealth.com/v0.1/checkouts/sessions \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "type": "subscription",
    "ui_mode": "hosted",
    "success_url": "https://example.com/success",
    "cancel_url": "https://example.com/cancel",
    "currency": "usd",
    "customer_data": { "email": "jordan.avery@example.com", "name": "Jordan Avery" },
    "items": [ { "provider_price_id": "<from GET /v0.1/products/{id}/prices>", "quantity": 1 } ]
  }'
```

```json Response theme={null}
{ "data": { "provider_checkout_session_id": "...", "url": "https://..." }, "request_id": "..." }
```

> [!TIP]
>
> Locked by check `checkout-session-succeeds-for-a-recurring-price`.

## What comes back

The intake submission returns the response id and the encounter id together; the response read-back repeats both.

| Field | Meaning | You key on it for |
| - | - | - |
| `data.id` | The questionnaire response id | Your own record of the intake |
| `data.encounter_id` | The intake encounter the platform created | Storing beside the response id; it is not a readable resource |
| `request_id` | Present on every response, success or failure | Support, when you report a problem |

### Verifying a submission

The API is the system of record you verify against. A submission is proven by two checks, not by
looking for the patient in the tools your care team uses:

1. The `201` carried `data.id` and `data.encounter_id`.
2. `GET /v0.1/questionnaire-responses/{id}` returns the answers you sent and the same
   `encounter_id`.

If `encounter_id` is missing or step 2 is empty, the submission failed even though it returned
`201` — re-read the validation warning on *Questionnaire workflow*. If both hold, it landed. The tools your care
team uses are fed from the platform on a per-tenant schedule and with a delay; whether a given
record type reaches them is a tenant configuration, not a signal about your call. Ask your OLH
implementation contact for your tenant's sync statement before you test against those tools.

> [!TIP]
>
> Locked by check `intake-creates-encounter`.

## Gotchas

> [!NOTE]
>
> **Response envelope varies by service — do not write one shared pagination helper.** Clinical
> resources (patients, questionnaires, questionnaire-responses, appointments)
> return `{ items, request_id }` with an `after` cursor when there is a next page. The
> product catalogue returns `{ items, pagination, request_id }`, but catalogue paging is not
> implemented yet, so do not build a cursor loop on it (see *API status*, "Response envelopes differ by endpoint"). Always log `request_id`; it is how support finds
> your call.
>
> **And the envelope also differs between a list and a single read of the same resource.**
> `GET /v0.1/patients` returns `{ items, request_id }`, each patient un-wrapped in `items[]`;
> `GET /v0.1/patients/{id}` returns `{ data: { … }, request_id }`. Branch on which call you made,
> not on the resource.

**Two silent failures to avoid.** Both come from the same condition in the platform: an intake
encounter is created only when `status === "completed"` **and** `subject.type === "Patient"` with
an id present.

* **Submitting `status: "in-progress"`** creates the response but no encounter (no `encounter_id` comes back). No error is
  returned. Submit partial intakes only if you intend this.
* **Omitting `subject`** creates an orphaned response with no patient linkage and no encounter.
  No error is returned. Some older integration examples omit `subject`; do not follow them.

In both cases you get a `201` and a response id. The absence shows as a missing `encounter_id`.

> [!TIP]
>
> Locked by check `in-progress-creates-no-encounter`.

> [!TIP]
>
> Locked by check `missing-subject-creates-no-encounter`.

## Related

> [card] [Questionnaire workflow](https://openloop.mintlify.site/cookbook/questionnaire-workflow.md)
>
> Who defines the questions, and how to return answers keyed by `link_id`

> [card] [Payments and checkout](https://openloop.mintlify.site/cookbook/payments-and-checkout.md)
>
> The next leg: create a session with `provider_price_id` for the treatment

> [card] [Not eligible](https://openloop.mintlify.site/cookbook/not-eligible.md)
>
> When this stage goes wrong: the intake was submitted and no order followed


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.