# FHIR API reference

Source: https://www.flexpa.com/docs/records
Description: Reference for the Flexpa API, a FHIR R4 API for claims, coverage and clinical records from medical record systems, health insurers, and national exchanges.

## Records

The Flexpa API is based on the HL7® FHIR® standard that gives you access to health insurance claims, plan details, and medical records from our [network of medical record systems, health insurers, and national exchanges](https://www.flexpa.com/docs/network).

Every resource available conforms to the FHIR R4 standard.

### How it works

1. Patients consent to transfer health data through Flexpa Consent to your application
2. Your server exchanges the consent for an access token
3. Use these tokens to make authenticated requests to Flexpa's FHIR API endpoints
4. Receive standardized FHIR-compliant health data that you can use in your application

### What you need

To use the Flexpa API effectively, you'll need:

- A pair of [API Keys](https://www.flexpa.com/docs/guides/quickstart#set-api-keys) ([talk to our team](https://www.flexpa.com/demo))
- A backend server to securely manage tokens and make API requests
- Understanding of [FHIR](https://www.flexpa.com/docs/fhir/introduction) resources (recommended)

You can use the API in [test mode](https://www.flexpa.com/docs/test-mode) to explore endpoints with sample data before going live with real patient data.

*Image: Flexpa API*

*Base URL*

```bash
https://api.flexpa.com
```

Getting started?

Looking for a demo?

---

### API Keys

The Flexpa API uses a two-layer authentication system.
API Keys are used for securely identifying your application to Flexpa and for OAuth token requests.

API Keys come in pairs: a **Publishable Key** and a **Secret Key**.

Publishable keys have the prefix `pk_test_` for test mode and `pk_live_` for live mode.
They are used in client-side code, like in the [Consent](https://www.flexpa.com/docs/consent) authorization step.

Secret keys have the prefix `sk_test_` and `sk_live_`. They are used only in server-side code and must be kept secure.

API Key Authorization Header

Authorization: Basic {'${base64_encoded_credentials}'}

Required for OAuth token requests.

----

### Access Tokens

The Flexpa API issues three kinds of access tokens, each for a different caller. Access tokens are [JWTs](https://jwt.io/introduction) that contain claims about the token's identity and permissions.

All three are sent in an `Authorization: Bearer` header.

#### Differences

| If you need to... | Use this token type |
|-------------------|---------------------|
| Access a specific patient's data | [Patient Access Token](#patient-access-token) |
| Make application-level API calls without patient context | [Application Access Token](#application-access-token) |
| Access API endpoints like `/fhir/metadata` | Either token type works |
| Read the patient's records as their own agent through the MCP server | [Personal Access Token](#personal-access-token), issued to the agent |

Authorization header

Authorization: Bearer eyJhbGc...

Required for all [FHIR API](#fhir-api) requests.

| | Application Access Token | Patient Access Token | Personal Access Token |
|---|---|---|---|
| **Who gets it** | Your application | Your application, for one patient | A personal OAuth client, such as a Claude or ChatGPT connector, for one patient |
| **How it is obtained** | Client Credentials grant on the [Token Endpoint](https://www.flexpa.com/docs/consent#token) with your secret key | [Exchange](https://www.flexpa.com/docs/consent#exchange) of the authorization code from Flexpa Consent | Exchange of the authorization code from Flexpa Consent, by a client registered through `/oauth/register` |
| **Audience (`aud`)** | `https://api.flexpa.com/` | `https://api.flexpa.com/` | `https://api.flexpa.com/mcp/consent`, the [MCP server](https://www.flexpa.com/docs/guides/agents) resource (live mode) |
| **Lifetime and refresh** | 30 minutes; no refresh | 24 hours; refresh token valid 90 days | 24 hours; a refresh token only when the patient approved `offline_access`, valid 90 days and renewed on each refresh |
| **What it can read** | Application-level resources, such as the [Provider Directory](#provider-directory) | That patient's records through the [FHIR API](#fhir-api) | That patient's records through `/mcp/consent` only; the FHIR API and other routes reject it |
| **How to revoke** | It cannot be revoked; it expires | [Revoke](https://www.flexpa.com/docs/consent#revoke) with the token and your publishable key, alone or with your secret key | [Revoke](https://www.flexpa.com/docs/consent#revoke) with the token and the client's `client_id` |

### Patient Access Token

Patient Access Tokens are created when a patient authorizes your application through [Flexpa Consent](https://www.flexpa.com/docs/consent) and you complete the [exchange](https://www.flexpa.com/docs/consent#exchange) step. These tokens are tied to a specific patient's identity and grant access to that patient's health data.

- Used for accessing patient-specific health records
- Tied to a specific patient identity - all API responses are automatically filtered
- Valid for 24 hours
- Obtained from the [exchange](https://www.flexpa.com/docs/consent#exchange) step
- Can be refreshed with a refresh token, regardless of [usage](https://www.flexpa.com/docs/guides/usage)
- You can inspect token details using the [introspect](https://www.flexpa.com/docs/consent#introspect) endpoint

**JWT claims**

- `jti`:
A unique identifier for the JWT (JSON Web Token). Generated as a random UUID to identify this specific token.

- `sub`:
Subject identifier. Contains the [Consent](https://www.flexpa.com/docs/consent#consent-1) ID.

- `patient`:
FHIR Patient resource identifier in the format `Patient/id`. This claim is specific to Patient Access Tokens.

- `client_id`:
OAuth 2.0 client identifier of the application that requested the token.

- `iat`:
Time at which the JWT was issued, in seconds since Unix epoch.

- `exp`:
Expiration time in seconds since Unix epoch. Patient Access Tokens expire 24 hours after issuance.

- `iss`:
Identifies the issuer of the JWT. Always "https://api.flexpa.com", the `issuer` in the [authorization server metadata](https://api.flexpa.com/.well-known/oauth-authorization-server).

- `aud`:
Identifies the intended audience of the JWT. Always "https://api.flexpa.com/".

---

### Application Access Token

Application Access Tokens operate at the application level without any patient context. You obtain these through the OAuth 2.0 Client Credentials flow, using your application's API keys.

- Used for accessing application-level resources without patient context
- Valid for 30 minutes
- Obtained through Client Credentials grant flow on the [Token Endpoint](https://www.flexpa.com/docs/consent#token)
- Cannot be refreshed (request a new token when needed)
- Used to access the [Provider Directory](#provider-directory)
- **Live mode keys only**: Application access tokens can only be created using live mode API keys

**JWT claims**

- `jti`:
A unique identifier for the JWT (JSON Web Token). Generated as a random UUID to identify this specific token.

- `sub`:
Subject identifier. For Application Tokens, this matches the client_id (application ID).

- `client_id`:
OAuth 2.0 client identifier of the application that requested the token.

- `iat`:
Time at which the JWT was issued, in seconds since Unix epoch.

- `exp`:
Expiration time in seconds since Unix epoch. Application Access Tokens expire 30 minutes after issuance.

- `iss`:
Identifies the issuer of the JWT. Always "https://api.flexpa.com", the `issuer` in the [authorization server metadata](https://api.flexpa.com/.well-known/oauth-authorization-server).

- `aud`:
Identifies the intended audience of the JWT. Always "https://api.flexpa.com/".

---

### Personal Access Token

Personal Access Tokens are issued to a patient's own agent, a personal OAuth client registered through `/oauth/register`, after the patient approves it in Flexpa Consent. Each authorization creates its own Consent, so revoking one agent's access leaves the others in place.

- Used only at the Consent [MCP server](https://www.flexpa.com/docs/guides/agents), `https://api.flexpa.com/mcp/consent`
- Valid for 24 hours
- Can be refreshed only when the patient approved `offline_access`
- Stop working as soon as the Consent is revoked, even before they expire

**JWT claims**

- `jti`:
A unique identifier for the JWT. Generated as a random UUID for each token; a refresh replaces it, so the previous access token stops working.

- `sub`:
Subject identifier. Contains the [Consent](https://www.flexpa.com/docs/consent#consent-1) ID.

- `client_id`:
The personal OAuth client's `client_id`, returned by `/oauth/register`. Not an application ID.

- `scope`:
The space-delimited scopes the patient approved. Always includes `patient/*.rs`, which permits reading and searching the patient's records.

- `iat`:
Time at which the JWT was issued, in seconds since Unix epoch.

- `exp`:
Expiration time in seconds since Unix epoch. Personal Access Tokens expire 24 hours after issuance.

- `iss`:
Identifies the issuer of the JWT: "https://api.flexpa.com", the `issuer` in the [authorization server metadata](https://api.flexpa.com/.well-known/oauth-authorization-server), in live and test mode.

- `aud`:
Identifies the intended audience of the JWT: the `resource` the client names when it requests the token, "https://api.flexpa.com/mcp/consent", in live and test mode.

A Personal Access Token has no `patient` claim and no `mode` claim. Its mode is the mode of the Consent that `sub` names, as for a Patient Access Token: a test mode token reads only test mode records. Like the other access tokens, it is signed with ES256 and has the `at+jwt` type.

---

### Patient authorizations

Patient Authorizations are the secure permissions granted by patients to access their health data. These authorizations are what enable the creation of Patient Access Tokens.

A Consent can include identity and endpoint authorizations. For a portal connection, the patient completes these steps in [Consent](https://www.flexpa.com/docs/consent):

1. They select their medical record system or health insurer
2. They authenticate with that organization
3. They explicitly consent to share specific data with your application
4. Flexpa creates a Patient Authorization that maintains this consent

Patient Authorizations can be configured as either:

- **ONE_TIME**: A single 24-hour window of access after which the authorization and all associated data are deleted
- **MULTIPLE**: Ongoing access that refreshes regularly without requiring the patient to re-authorize

Each Patient Authorization has a unique lifecycle with different states which you can track via the [introspect](https://www.flexpa.com/docs/consent#introspect) endpoint. When a patient chooses to revoke access, you can use the [revoke](https://www.flexpa.com/docs/consent#revoke) endpoint. By default it revokes the whole consent, including its active Patient Authorizations, and deletes the associated data. To revoke only some Patient Authorizations, pass their IDs in `patient_authorization_ids`. Flexpa then revokes and deletes the data of only those, and the consent's tokens keep working for the rest.

**Warning:**
A patient's access can lapse at the endpoint without the authorization changing state. Detect this through the [`refresh_expired`](https://www.flexpa.com/docs/records/webhooks#refresh_expired) and [`sync_failed`](https://www.flexpa.com/docs/records/webhooks#sync_failed) webhooks rather than by polling authorization state.

**Authorization states**

- `CREATED`:
The initial state when a patient authorization record is created but before the authentication process has begun.

- `AUTHORIZING`:
The patient has started authentication but has not finished.

- `AUTHORIZED`:
The patient has successfully authenticated and granted consent, but the authorization has not yet been exchanged for an access token.

- `EXCHANGED`:
The public token has been exchanged for an access token, and the patient's data is being synchronized. For MULTIPLE usage authorizations, the authorization remains in this state across subsequent token refreshes.

- `ERRORED`:
An error occurred during the authorization or data synchronization process.

- `ABANDONED`:
The patient started the authorization process but did not complete it. This could be due to various reasons like timeout, closing the window, or navigation away.

- `BOUNCED`:
The authorization process was rejected by the upstream system, possibly due to invalid credentials or other issues.

- `REVOKED`:
The authorization is no longer usable. This happens when the patient or your application calls the [revoke](https://www.flexpa.com/docs/consent#revoke) endpoint, when the patient reconnects the same source through a new [consent](https://www.flexpa.com/docs/consent#consent-1) and the older authorization is superseded (identity/IAL2 authorizations are exempt), or when an endpoint reports during a sync that the patient revoked consent upstream.

- `EXPIRED`:
The authorization's refresh window has elapsed (for example an identity/IAL2 authorization that can no longer be refreshed without the patient re-verifying their identity) and it can no longer be used to obtain new access tokens.

---

### Request ID

Each API request has an associated request identifier.
You can find this value in the response headers, under `X-Request-Id`.
If you need help debugging a request, please include the Request Id when [contacting support](https://www.flexpa.com/docs/support).

---

### Sync job states

When a patient authorizes access to their health data through Flexpa Consent, a synchronization process is initiated to retrieve and cache their records from the connected source. This process is managed through a Sync Job, which allows you to track the status of data retrieval.

Sync Jobs are automatically created after a successful patient authorization and progress through several states as data is retrieved, processed, and made available through the Flexpa API.

**Note:**
During the initial sync period (most syncs complete in under a minute, but patients with large record sets on slower endpoints can take several minutes), FHIR API requests may return a 429 status code. Once the sync is complete (status: `COMPLETED`), patient data becomes available for querying. You can monitor the current sync state through the `sync.state` property returned in the exchange response or via the introspect endpoint.

**Sync job states**

- `CREATED`:
The sync job has been created after successful patient authorization. This is its initial state.

- `WAITING`:
The sync job is queued for processing and will begin retrieving data from the connected source soon.

- `ACTIVE`:
The sync job is currently retrieving and processing the patient's health data from their connected source.

- `FAILED`:
The sync job encountered an error and was unable to complete. Data from an earlier successful sync stays available through the [FHIR API](#fhir-api). A failed sync alone does not mean the patient must re-authorize. When Flexpa can no longer refresh the authorization, it sends a [`refresh_expired`](https://www.flexpa.com/docs/records/webhooks#refresh_expired) webhook, and the patient must re-consent.

- `COMPLETED`:
The sync job has successfully retrieved and processed all available patient data, which is now available through the [FHIR API](#fhir-api).

## FHIR API

All FHIR API requests must be made with a [Patient Access Token](#patient-access-token) or an [Application Access Token](#application-access-token) in the Authorization header.

FHIR API routes begin with the `/fhir/` subpath of the URL.
Flexpa's FHIR API is designed to provide a consistent, reliable, and developer-friendly experience when working with health data. Our architecture offers several key benefits:

- **Consistent API Experience**: We normalize the behavior of FHIR operations across connected sources, providing uniform support for features like [Patient $everything](https://www.flexpa.com/docs/fhir/introduction#patient-everything-operation).

- **Enhanced Search Capabilities**: Flexpa supports comprehensive search functionality, including consistent implementation of parameters like `patient` and powerful features like `_include` across all data sources.

- **Standardized Data Model**: We dynamically adapt to differences among upstream FHIR implementations and transform the data to provide a consistent experience, including:
  - Creating MedicationRequest resources from pharmacy claim data in ExplanationOfBenefit resources ([learn more](https://www.flexpa.com/docs/fhir/medication-request#flexpa-enhancements))
  - Generating US Core clinical resources (Encounter, Condition, Procedure) from claims data ([learn more](https://www.flexpa.com/docs/records/claims-to-clinical))
  - Generating InsurancePlan resources for supported Medicare Advantage Part C Coverage from CMS PBP reference data ([learn more](https://www.flexpa.com/docs/fhir/insurance-plan))
  - Normalizing code systems and adding human-readable display values
  - Enhancing resource references for better data connectivity
  - Filling in missing information where available from other sources

Explore these powerful features to enhance your development experience:
- [Wildcard Parameters](#wildcard-parameters)
- [Search Result Parameters](#search-result-parameters)
- [Pagination](#pagination)
- [Referenced Resources](#referenced-resources)
- [Code Systems](#/docs/fhir/code-systems)
- [Errors](#errors)

---

### Read

A read is the most basic operation in FHIR. It allows you to retrieve the current version of a single resource by its ID.

For a full list of available Resources, please refer to the [FHIR Resources documentation](https://www.flexpa.com/docs/fhir/introduction).

**Note:**
Many resources returned by the API will contain references to other resources.
For more information on how to handle references, see the [Referenced Resources](#referenced-resources) section.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must presented with a [Patient Access Token](#patient-access-token) or an [Application Access Token](#application-access-token)

**Request path parameters**

- `id` (string):
The logical id of the resource to be retrieved - used as the last URL path segment

**Response fields**

- `resourceType` (string):
Reads return an individual resource, so the resource type is expected to correspond to the resource you are reading

**Error codes**

- `transient` (429 status code):
The API is expected to return a 429 status code until the data is ready to be retrieved.
This error is returned by the API while in the [initial sync period](https://www.flexpa.com/docs/records#sync-job-states). Most syncs complete in under a minute, but patients with large record sets on slower endpoints can take several minutes.

The 429 response includes an `X-Retry-After` header (a non-standard header whose value is a suggested wait time in seconds, currently `3`). When implementing your own retry logic, read this header and wait the indicated number of seconds before retrying.

You will need to implement retry logic to handle this error. If you are using the [Node SDK](https://www.flexpa.com/docs/records/node-sdk) which we demonstrate in our [Quickstart guide](https://www.flexpa.com/docs/guides/quickstart), retry logic is already built in and you don't need to implement it yourself.

- `processing` (422 status code): The API returns a 422 when an error occurs processing the request against the Endpoint, or when a Patient Access Token is required but missing for a wildcard.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl https://api.flexpa.com/fhir/Coverage/123 \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Coverage/123", {
  headers: {
    "content-type": "application/json",
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const resource = await response.json();
```

```json
{
  "resourceType": "Coverage",
  "id": "123"
}
```

---

### Search

Searches on Flexpa API follow the RESTful style of the FHIR specification by submitting a GET HTTP request to the base URL of the resource with parameters to define the exact search criteria to filter the response.

**Note:**
Many resources returned by the API will contain references to other resources.
For more information on how to handle references, see the [Referenced Resources](#referenced-resources) section.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must presented with a [Patient Access Token](#patient-access-token) or an [Application Access Token](#application-access-token)

**Request parameters**

- `_include` (string):
The referenced resources to include in the search response.
Only applies to [relative references](#relative-references).
The value of the `searchInclude` parameter has the format `[Resource]:[field]`, for example `Patient:general-practitioner`.
For more information on available `searchInclude` parameters, please refer to the [CapabilityStatement](#search-include).

- `_revinclude` (string):
Like `_include` but intstead of including the resources referenced within the searched-for resource, include resources that may _reference_ the searched resource.
The value of the `searchRevInclude` parameter has the format `[Resource]:[field]`, for example `Provenance:target`.

- `[searchParam]` (string):
To filter the search results server-side, you can use any of the available search parameters for the resource type you are searching for.
For more information on available `searchParam` parameters, please refer to the [CapabilityStatement](#search-param).

- `_lastUpdated` (date):
Filter by `meta.lastUpdated`, the time Flexpa last stored a new version of the resource. This is not the clinical date of the record.
To get only the resources that changed since your last pull, use the `ge` prefix with the time of that pull, for example `Observation?_lastUpdated=ge2026-10-01T00:00:00Z`.
A sync can store a new version of some resources, such as `Binary` and `Provenance`, even when nothing clinical changed. These resources come back in each incremental pull, so update the copies you already have by resource `id` instead of adding new copies.
`_since` on [Patient $everything](#patient-everything) applies the same filter.

**Note:**
To list every resource's supported search parameters and `_include` values, read the unauthenticated [CapabilityStatement](#capability-statement): `curl https://api.flexpa.com/fhir/metadata`, then look at `rest[0].resource[].searchParam` and `searchInclude` for the resource type.

**Note:**
Search results can also be modified by certain search result parameters.
For more information on available search result parameters, see the [Search Result Parameters](#search-result-parameters) section.

**Response fields**

- `resourceType` (string):
Searches return a `Bundle` resource type

- `entry` (array):
An array of FHIR resources expected to match the resource type of the search

**Error codes**

- `transient` (429 status code):
The API is expected to return a 429 status code until the data is ready to be retrieved.
This error is returned by the API while in the [initial sync period](https://www.flexpa.com/docs/records#sync-job-states). Most syncs complete in under a minute, but patients with large record sets on slower endpoints can take several minutes.

The 429 response includes an `X-Retry-After` header (a non-standard header whose value is a suggested wait time in seconds, currently `3`). When implementing your own retry logic, read this header and wait the indicated number of seconds before retrying.

You will need to implement retry logic to handle this error. If you are using the [Node SDK](https://www.flexpa.com/docs/records/node-sdk) which we demonstrate in our [Quickstart guide](https://www.flexpa.com/docs/guides/quickstart), retry logic is already built in and you don't need to implement it yourself.

- `processing` (422 status code): The API returns a 422 when an error occurs processing the request against the Endpoint, or when a Patient Access Token is required but missing for a wildcard.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl https://api.flexpa.com/fhir/ExplanationOfBenefit \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const searchUrl = "https://api.flexpa.com/fhir/ExplanationOfBenefit";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const searchBundle = await response.json();
```

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/Patient?_include=Patient:general-practitioner";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/Condition?onset-age=gt54";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

*Response*

```json
{
  "resourceType": "Bundle",
  "id": "22f61d0877b54b2a8a2feb57bfe2c462",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "123"
      }
    },
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "456"
      }
    }
  ]
}
```

```json
{
  "resourceType" : "Bundle",
  "entry" : [
    {
      "resource" : {
        "resourceType" : "Patient",
        "id" : "123",
        "generalPractitioner" : {
          "reference" : "Practitioner/456"
        }
      }
    },
    {
      "resource" : {
        "resourceType" : "Practitioner",
        "id" : "456",
        "name" : "Dr. Adam Smith"
      }
    }
  ]
}
```

```json
{
  "resourceType": "Bundle",
  "id": "22f61d0877b54b2a8a2feb57bfe2c462",
  "entry": [
    {
      "resource": {
        "resourceType": "Condition",
        "id": "123",
        "onset": {
          "age": {
            "value": 55,
          }
        }
      }
    },
    {
      "resource": {
        "resourceType": "Condition",
        "id": "456",
        "onset": {
          "age": {
            "value": 68,
          }
        }
      }
    }
  ]
}
```

---

### Patient $everything

Unique to the Patient resource, the [Patient $everything ](https://hl7.org/fhir/R4/operation-patient-everything.html) returns all [patient-compartmentalized](https://hl7.org/fhir/R4/compartmentdefinition-patient.html) resources, as well as any Organization, Location, Practitioner, and Medication resources that are present in the patient's FHIR data.

You will need to make additional [search](#search) requests for any non-patient compartmentalized resources, for example:
- [Location](https://www.flexpa.com/docs/fhir/location)
- [Device](https://www.flexpa.com/docs/fhir/device)
- [PractitionerRole](https://www.flexpa.com/docs/fhir/practitioner-role)
- [InsurancePlan](https://www.flexpa.com/docs/fhir/insurance-plan)

**Note:**
Without `_count`, this request returns one large Bundle. The client should be prepared to handle a potentially large single response, or send `_count` to page through the record instead.

With a Patient Access Token, Flexpa also checks each signed attachment download link in the response. A link to a Binary that does not belong to the Consent is replaced with `Binary/{id}`. This check reads Binary metadata, so a single Bundle with many attachments takes longer to return. An Application Access Token skips this check. To keep responses fast, send `_count` (for example `_count=100`) and follow the `next` link until it is absent.

**Note:**
`$everything` starts from the Patient resource. If the source did not return a Patient resource for the patient ID, the request fails with a `422` and an OperationOutcome with code `not-found`, even when other resources reference that patient ID. In this case, use type-level [search](#search) requests, which do not need a stored Patient resource. With a Patient Access Token, for example, call `GET /fhir/ExplanationOfBenefit`. With an Application Access Token, add `patient=<Patient ID>`, for example `GET /fhir/ExplanationOfBenefit?patient=<Patient ID>`. Without it, the search returns resources for all patients of your application.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with a [Patient Access Token](#patient-access-token) when using a wildcard `$PATIENT_ID` or otherwise an [Application Access Token](#application-access-token)

**Request query parameters**

- `_type` (code):
Restrict the returned resources to one or more comma-separated FHIR resource types. Forwarded to the upstream FHIR server.

- `_since` (instant):
Return only resources updated after the given timestamp. Forwarded to the upstream FHIR server.

- `_count` (integer):
The number of resources to return per page. Forwarded to the upstream FHIR server.

With the wildcard `$PATIENT_ID`, sending `_count` returns the record one page at a time instead of as one Bundle. Follow the `next` link until it is absent. Each page has a `self` link, and every page but the last has a `next` link. Pages have no `first` link and no `total`. Pages walk the master Patient, then each linked Patient, so a page can hold fewer resources than `_count`, and can be empty after access control filtering while still carrying a `next` link. `_count` must be a whole number. Values below 20 are raised to 20, so a page can also hold more resources than requested, and values above 1000 are lowered to 1000. Referenced resources such as Practitioner, Organization, and Location can appear on more than one page, so deduplicate on resource type and ID. If a linked Patient is missing or the server fails while reading it, its page returns an OperationOutcome entry with `search.mode` of `outcome`, plus a `next` link if another record follows. Check each page for these entries before treating the record as complete. Request the same page again to retry.

- `start` (date):
The HL7 R4 `$everything` start date — return resources from this clinical date onward. Forwarded to the upstream FHIR server.

- `end` (date):
The HL7 R4 `$everything` end date — return resources up to this clinical date. Forwarded to the upstream FHIR server.

**Response fields**

- `Response` (Bundle):
Patient $everything returns a Bundle that contains all resources that reference the Patient resource.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$everything' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$everything", {
  headers: {
    "content-type": "application/json",
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const response = await response.json();
```

```json
{
  "resourceType": "Bundle",
  "entry": [
    { "resource": {"resourceType": "Patient", ...} },
    { "resource": {"resourceType": "Coverage", ...} },
    { "resource": {"resourceType": "ExplanationOfBenefit", ...} },
  ]
}
```

**Note:**
This example makes use of the `$PATIENT_ID` [wildcard parameter](#wildcard-parameters) which requires a [Patient Access Token](#patient-access-token).
When using with an [Application Access Token](#application-access-token), replace the wildcard parameter with a specific Patient ID.

---

### Patient $summary

The `$summary` operation generates an [International Patient Summary (IPS)](https://hl7.org/fhir/uv/ips/) document for the patient. The IPS is a standards-based clinical summary designed for unscheduled or cross-border care, returning a FHIR Bundle of type `document` with a [Composition](https://hl7.org/fhir/R4/composition.html) resource that organizes the patient's key health information into 14 standardized sections.

The generated IPS document includes:
- **PDF rendering** — a [DocumentReference](https://www.flexpa.com/docs/fhir/document-reference) containing a rendered PDF of the patient summary is automatically included in the Bundle, suitable for display in systems that do not support FHIR
- **Status-based filtering** — only clinically relevant resources (e.g., active medications, completed immunizations, final lab results)
- **Section narratives** — each section contains a human-readable XHTML table
- **Empty section handling** — sections with no data include `emptyReason` of `unavailable`; sections excluded via `_section` include `emptyReason` of `withheld`
- **Confidentiality tagging** — the Bundle carries a `meta.security` high water mark reflecting the most restrictive confidentiality code across included resources

Use the `_section` query parameter to restrict which IPS sections appear in the summary. This is useful when patients want to share only specific categories of health data — for example, sharing allergies and medications with a new provider but withholding social history. Values can be LOINC section codes or short aliases. When `_section` is omitted, all available sections are returned.

| Alias | LOINC code | Section |
|-------|------------|---------|
| `allergies` | 48765-2 | Allergies |
| `medications` | 10160-0 | Medications |
| `problems` | 11450-4 | Problem list |
| `immunizations` | 11369-6 | Immunizations |
| `procedures` | 47519-4 | Procedures |
| `results` | 30954-2 | Results |
| `vitalsigns` | 8716-3 | Vital signs |
| `socialhistory` | 29762-2 | Social history |
| `devices` | 46264-8 | Devices |
| `planofcare` | 18776-5 | Plan of treatment |
| `functionalstatus` | 47420-5 | Functional status |
| `pastillness` | 11348-0 | History of past illness |
| `pregnancy` | 10162-6 | Pregnancy history |
| `advancedirectives` | 42348-3 | Advance directives |

**Note:**
The IPS is more compact than `$everything` — it returns a curated clinical summary rather than the full patient compartment. Use `$everything` when you need all available data, and `$summary` when you need a structured clinical overview. When `_section` is provided, excluded sections remain in the Composition (preserving the IPS structure) but contain no entries and are marked as `withheld`. Only resources referenced by included sections are present in the Bundle. Patient, Composition, and author resources are always retained.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with a [Patient Access Token](#patient-access-token) when using a wildcard `$PATIENT_ID` or otherwise an [Application Access Token](#application-access-token)

**Request query parameters**

- `_section` (string):
One or more LOINC section codes or aliases to include. Repeat for multiple sections. When omitted, all sections are returned.

**Response fields**

- `Response` (Bundle):
A Bundle of type `document` containing a Composition resource, referenced clinical resources organized into IPS sections, and a DocumentReference with a rendered PDF of the summary. The Composition always includes all 14 sections — sections with data contain `entry` references; sections without data or excluded by `_section` contain an `emptyReason`.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$summary' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$summary", {
  headers: {
    "content-type": "application/json",
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const data = await response.json();
```

*Filtered request*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$summary?_section=allergies&_section=medications' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch(
  "https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$summary?_section=allergies&_section=medications",
  {
    headers: {
      "content-type": "application/json",
      "authorization": `Bearer ${ACCESS_TOKEN}`,
    },
  }
);

const data = await response.json();
```

```json
{
  "resourceType": "Bundle",
  "type": "document",
  "timestamp": "2026-02-19T00:00:00.000Z",
  "meta": {
    "security": [{ "system": "http://terminology.hl7.org/CodeSystem/v3-Confidentiality", "code": "N" }]
  },
  "entry": [
    {
      "resource": {
        "resourceType": "Composition",
        "title": "International Patient Summary",
        "type": { "coding": [{ "system": "http://loinc.org", "code": "60591-5" }] },
        "section": [
          {
            "title": "Allergies",
            "code": { "coding": [{ "system": "http://loinc.org", "code": "48765-2" }] },
            "entry": [{ "reference": "AllergyIntolerance/allergy-1" }]
          },
          {
            "title": "Medications",
            "code": { "coding": [{ "system": "http://loinc.org", "code": "10160-0" }] },
            "entry": [{ "reference": "MedicationRequest/med-1" }]
          },
          {
            "title": "Vital Signs",
            "code": { "coding": [{ "system": "http://loinc.org", "code": "8716-3" }] },
            "emptyReason": {
              "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/list-empty-reason", "code": "unavailable" }]
            }
          }
        ]
      }
    },
    { "resource": { "resourceType": "Patient", "..." : "..." } },
    { "resource": { "resourceType": "Organization", "..." : "..." } },
    { "resource": { "resourceType": "AllergyIntolerance", "..." : "..." } },
    { "resource": { "resourceType": "MedicationRequest", "..." : "..." } },
    {
      "resource": {
        "resourceType": "DocumentReference",
        "status": "current",
        "type": { "coding": [{ "system": "http://loinc.org", "code": "60591-5", "display": "Patient summary Document" }] },
        "content": [{ "attachment": { "contentType": "application/pdf", "data": "base64..." } }]
      }
    }
  ]
}
```

**Note:**
This example makes use of the `$PATIENT_ID` [wildcard parameter](#wildcard-parameters) which requires a [Patient Access Token](#patient-access-token).
When using with an [Application Access Token](#application-access-token), replace the wildcard parameter with a specific Patient ID.

---

### Patient $pdf

The `$pdf` operation returns a comprehensive patient health export as a downloadable PDF. Unlike [`$summary`](#patient-summary) which generates a curated IPS document, `$pdf` maps all resources directly from [`$everything`](#patient-everything) — every resource type returned is rendered; nothing is silently dropped. Pass `_type` to narrow the export to specific resource types.

When called with a wildcard `$PATIENT_ID`, the response is a **stitched PDF** — one branded section per connected source, merged into a single file:
- Payer and provider connections contribute a structured FHIR data section, plus any attached clinical documents (`DocumentReference`) from that source
- TEFCA QHIN connections contribute C-CDA clinical documents stitched into one PDF per facility

**Sections included (structured FHIR)**

| Section | Source resource types |
|---|---|
| Demographics | `Patient` |
| Care Team | `CareTeam` |
| Insurance | `Coverage` |
| Allergies | `AllergyIntolerance` |
| Active Problems | `Condition` (active/unknown) |
| Medications | `MedicationRequest`, `MedicationDispense`, `MedicationStatement`, `MedicationAdministration` |
| Care Plan | `CarePlan` |
| Goals | `Goal` |
| Vital Signs | `Observation` (vital-signs) |
| Lab Results | `DiagnosticReport` (LAB) + standalone `Observation` (laboratory) |
| Imaging & Radiology | `DiagnosticReport` (RAD), `ImagingStudy` |
| Encounters | `Encounter` |
| Appointments | `Appointment` |
| Claims | `ExplanationOfBenefit` |
| Immunizations | `Immunization` |
| Procedures | `Procedure` |
| Devices | `Device`, `DeviceUseStatement` |
| Family History | `FamilyMemberHistory` |
| Flags & Alerts | `Flag` |
| Orders & Referrals | `ServiceRequest` |
| Documents | `DocumentReference` (metadata; attached content rendered in the section below) |
| Social History | `Observation` (social-history) |
| History of Past Illness | `Condition` (inactive/resolved) |
| Questionnaires | `QuestionnaireResponse` |
| Related Persons | `RelatedPerson` |
| Other Records | Any resource type not matched above — grouped by type, rendered generically |

**DocumentReference rendering**

Clinical documents are stored as `DocumentReference` resources. Document content is sourced from `content[].attachment.data` (inline base64) when present, or fetched from `content[].attachment.url` (a signed URL on `binary.flexpa.com`) as a fallback. The renderer dispatches by content type:

| Content type | Handling |
|---|---|
| `text/xml`, `application/xml`, `application/hl7-v3+xml` | Parsed as C-CDA and rendered section-by-section. Supports CDA R2-based documents including C-CDA 1.1, 2.0, and 2.1. C-CDA documents that wrap an embedded PDF (`nonXMLBody`) are passed through directly. If the document is malformed, a placeholder noting the parse failure is rendered instead of dropping the document. |
| `application/pdf` | Passed through as-is — no re-rendering |
| `text/html` | Rendered with structure preserved — tables are tab-delimited, list items become bullets, block elements produce line breaks |
| `text/plain` | Rendered verbatim |
| `application/rtf`, `text/rtf` | Plain text extracted from RTF control sequences, tables preserved as tab-delimited rows |
| Any other type | A placeholder is rendered noting the content type and original URL (if present). The document is never silently dropped. |

In practice, documents arrive as `application/xml` (C-CDA), `application/pdf`, or `application/rtf`. All content types are rendered — nothing is silently dropped.

The response has `Content-Type: application/pdf` and `Content-Disposition: attachment; filename="{patientId}.pdf"`.

**Query parameters**

- `patient-authorization-id` (string):
Scope the export to a single patient authorization. When provided, only resources tagged with that authorization are included — useful for generating a per-payer, per-provider, or per-TEFCA-connection PDF.

The authorization must belong to the consent in the bearer token. Returns `404` if not found.

For payer and provider connections: renders a structured FHIR data PDF for that connection only.

For TEFCA QHIN connections: renders C-CDA clinical documents from that QHIN, stitched into one PDF per facility. When used with `_format=zip`, each facility becomes a separate file.

- `_format` (string):
When set to `zip`, returns a ZIP archive instead of a single stitched PDF. Each connected source produces one or more files:

  - Payer and provider connections: one file named `oauth-{endpointName}.pdf`
  - IAL1 self-attested identity connections: one file named `ial1-{connectionName}.pdf`
  - TEFCA QHIN connections: one file per facility, named `ial2-{facilityName}.pdf`

- `_type` (string):
Restrict the export to specific FHIR resource types. Accepts a comma-delimited list (`_type=Condition,MedicationRequest`) or repeated parameters (`_type=Condition&_type=MedicationRequest`). Sections whose source resource types are all excluded are omitted from the PDF.

Supported values are the source resource types in the sections table above: `AllergyIntolerance`, `Appointment`, `CarePlan`, `CareTeam`, `Condition`, `Coverage`, `Device`, `DeviceUseStatement`, `DiagnosticReport`, `DocumentReference`, `Encounter`, `ExplanationOfBenefit`, `FamilyMemberHistory`, `Flag`, `Goal`, `ImagingStudy`, `Immunization`, `MedicationAdministration`, `MedicationDispense`, `MedicationRequest`, `MedicationStatement`, `Observation`, `Procedure`, `QuestionnaireResponse`, `RelatedPerson`, and `ServiceRequest`. Any other value returns `400`.

Demographics always render, so `Patient` is not an accepted value. Excluded resources remain available as reference targets, which means filtering to `DiagnosticReport` still renders its inline lab results and filtering to `MedicationRequest` still resolves medication names.

The reverse also holds. Observations that a `DiagnosticReport` would normally render inline are reported in their own section when `Observation` is requested without `DiagnosticReport`, so no result is lost to a filter that excludes the report carrying it.

Documents are included or excluded whole. `DocumentReference` controls whether a source's attached clinical documents are rendered, and there is no filtering of the sections inside a C-CDA. TEFCA QHIN connections contribute only C-CDA documents, so a filter that omits `DocumentReference` drops those sources entirely and lowers `X-PDF-Sources-Total` to match. Requesting one of them explicitly with `patient-authorization-id` under such a filter returns `404`.

Omitting `_type` leaves the export unchanged: every resource type is rendered, including TEFCA documents.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with a [Patient Access Token](#patient-access-token) when using a wildcard `$PATIENT_ID` or otherwise an [Application Access Token](#application-access-token)

**Response**

- `application/pdf` (binary):
A PDF binary containing the patient's health export. When using a wildcard `$PATIENT_ID`, sections from each connected source are stitched into a single file.

- `application/zip` (binary):
Returned when `_format=zip`. A ZIP archive where each connected source produces one or more files: payer/provider as `oauth-{endpointName}.pdf`, IAL1 self-attested identity as `ial1-{connectionName}.pdf`, TEFCA QHIN as `ial2-{facilityName}.pdf` (one per facility).

**Response headers**

- `X-PDF-Sources-Total` (integer):
Total number of connected sources (patient authorizations) included in the export. Sources that a `_type` filter excludes entirely are not counted.

- `X-PDF-Sources-Failed` (integer):
Number of sources that could not be rendered. A value greater than zero means the PDF may be incomplete.

- `X-PDF-Sources-Failed-Names` (string):
Comma-separated display names of any sources that failed to render. Omitted when `X-PDF-Sources-Failed` is `0`.

- `X-PDF-Resource-Count` (integer):
Total number of FHIR resources included across all rendered sources, after any `_type` filter is applied. Use this to verify that the export covers the data you expect without parsing the PDF itself.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  --output health-export.pdf
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf", {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const filename = response.headers.get('content-disposition')?.match(/filename="(.+?)"/)?.[1] ?? 'export.pdf';
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
```

*Single authorization*

```bash
ACCESS_TOKEN=patient-access-token
PA_ID=pat-auth-id

curl "https://api.flexpa.com/fhir/Patient/\$PATIENT_ID/\$pdf?patient-authorization-id=$PA_ID" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  --output health-export.pdf
```

```js
const PA_ID = "pat-auth-id";

const response = await fetch(
  `https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf?patient-authorization-id=${PA_ID}`,
  {
    headers: { "authorization": `Bearer ${ACCESS_TOKEN}` },
  }
);
```

*Filter by resource type*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf?_type=Condition,MedicationRequest' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  --output medications-and-problems.pdf
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch(
  "https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf?_type=Condition,MedicationRequest",
  {
    headers: { "authorization": `Bearer ${ACCESS_TOKEN}` },
  }
);

const resourceCount = response.headers.get('X-PDF-Resource-Count');
```

*ZIP archive*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf?_format=zip' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  --output health-export.zip
# Archive contains e.g.:
#   oauth-BlueCross.pdf
#   ial1-MyChart.pdf
#   ial2-General Hospital.pdf
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$pdf?_format=zip", {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});

const filename = response.headers.get('content-disposition')?.match(/filename="(.+?)"/)?.[1] ?? 'health-export.zip';
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
```

---

### Patient $health-cards-issue

The `$health-cards-issue` operation creates a SMART Health Card containing the patient's health data as a verifiable credential. This operation generates a digitally signed JWT that packages the patient's FHIR data according to the [SMART Health Cards specification](https://spec.smarthealth.cards/).

The operation always uses the patient's complete data set (equivalent to Patient/$everything), ensuring comprehensive health information is included in the credential.

**Note:**
The health card is returned as a signed JWT string within a Parameters resource, not as a raw SMART Health Card file. The JWT can be converted to a QR code or shared directly as a verifiable credential.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with a [Patient Access Token](https://www.flexpa.com/records#patient-access-token)

**Request path parameters**

- `id` (string):
The identifier of the patient - use `$PATIENT_ID` to automatically reference the authenticated patient

**Request body**

- `resourceType` (string):
Must be `Parameters`

- `parameter` (array):
Array containing exactly one parameter object

  - `name` (string):
Must be `credentialType`

  - `valueUri` (string):
Must be `Patient/$everything` (currently the only supported credential type)

**Response fields**

- `Response` (Parameters):
Returns FHIR Parameters resource containing the SMART Health Card

  - `parameter` (array):
Array containing exactly one parameter object

    - `name` (string):
Will be `verifiableCredential`

    - `valueString` (string):
The signed SMART Health Card as a JWT string

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$health-cards-issue' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "resourceType": "Parameters",
    "parameter": [
      {
        "name": "credentialType",
        "valueUri": "Patient/$everything"
      }
    ]
  }'
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$health-cards-issue", {
  method: 'POST',
  headers: {
    "content-type": "application/json",
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
  body: JSON.stringify({
    resourceType: "Parameters",
    parameter: [
      {
        name: "credentialType",
        valueUri: "Patient/$everything"
      }
    ]
  })
});

const result = await response.json();
```

```json
{
  "resourceType": "Parameters",
  "parameter": [
    {
      "name": "credentialType",
      "valueUri": "Patient/$everything"
    }
  ]
}
```

```json
{
  "resourceType": "Parameters",
  "parameter": [
    {
      "name": "verifiableCredential",  
      "valueString": "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiIsImtpZCI6IjNLZmRnLVh3UC03Z..."
    }
  ]
}
```

---

### Patient $expunge

The `$expunge` operation deletes all resources in a specific Patient resource [compartment](https://hl7.org/fhir/R4/compartmentdefinition.html).
This operation performs a "hard" delete, meaning all data, including resource history, is permanently removed from the server.

Once the data is deleted, any subsequent FHIR requests to retrieve the data will return a 404 status code.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with a [Patient Access Token](#patient-access-token)

**Request parameters**

- `patientId` (string):
The ID of the patient whose data you want to delete.
This ID must match the patient ID of the access token and can be retrieved with a [search](https://www.flexpa.com/docs/records#search) request for the Patient resource.
There is an option to use the [patient wildcard parameter](https://www.flexpa.com/docs/records#wildcard-parameters) to automatically match the patient ID in the access token.

**Response fields**

- `Response` (OperationOutcome):
The Patient $expunge operation returns an OperationOutcome resource, indicating the success or failure of the expunge request.

**Error codes**

- `transient` (429 status code):
The API is expected to return a 429 status code until the data is ready to be retrieved.
The API returns this error during the [initial sync period](https://www.flexpa.com/docs/records#sync-job-states). Most syncs complete in under a minute, but patients with large record sets on slower endpoints can take several minutes.

Data cannot be expunged until the initial sync period has passed.

*Request*

```bash
ACCESS_TOKEN=patient-access-token
curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$expunge' \
      -H "Authorization: Bearer $ACCESS_TOKEN" \
      -X POST
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Patient/$PATIENT_ID/$expunge", {
  headers: {
    "content-type": "application/json",
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
  method: 'POST'
});

const response = await response.json();
```

```json
{
  "resourceType": "OperationOutcome",
  "id": "accepted",
  "issue": [
    {
      "severity": "information",
      "code": "informational",
      "details": {
        "text": "Accepted"
      },
      "diagnostics": "expunge-patient-15c72fcc-267e-4372-a85e-26fa20b01634"
    }
  ]
}
```

---

### ViewDefinition $run

The ViewDefinition $run operation does the heavy lifting of parsing FHIR data for you. Define the data your application needs, and get it back as JSON or CSV that's ready to use.

**When to use this:**
- You need specific fields from ExplanationOfBenefit, Patient, or other resources
- You want data in a format that more closely matches your backend systems and is easier to work with
- You don't want to deal with storing or processing FHIR, you just want directly actionable healthcare data

The operation accepts a [ViewDefinition](https://build.fhir.org/ig/FHIR/sql-on-fhir-v2/StructureDefinition-ViewDefinition.html) resource that specifies what to extract, then queries the data and returns the structured response.

**Note:**
**Need help getting started?** We're FHIR experts and can help you craft a ViewDefinition that extracts exactly the data you need. Reach out to your Flexpa contact or our support team.

**Error codes**

- `transient` (429 status code):
With a [Patient Access Token](#patient-access-token), the API returns a 429 while the patient's initial [sync](#sync-job-states) is still running. Retry the request, or wait for the [`sync_completed` webhook](https://www.flexpa.com/docs/records/webhooks#sync_completed) before calling.

*Request*

```bash
curl -X POST "https://api.flexpa.com/fhir/ViewDefinition/\$run" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "resourceType": "Parameters",
    "parameter": [
      {
        "name": "viewResource",
        "resource": {
          "resourceType": "ViewDefinition",
          "name": "patient_basics",
          "status": "active",
          "resource": "Patient",
          "select": [{
            "column": [
              { "name": "id", "path": "id" },
              { "name": "family_name", "path": "name.first().family" },
              { "name": "given_name", "path": "name.first().given.first()" },
              { "name": "birth_date", "path": "birthDate" }
            ]
          }]
        }
      }
    ]
  }'
```

#### Request body

The request body is a FHIR [Parameters](https://hl7.org/fhir/R4/parameters.html) resource containing the operation parameters.

- `viewResource` (ViewDefinition, required):
The ViewDefinition resource specifying what fields to extract. Must be provided inline (not by reference).

- `patient` (Reference):
Optional. Filter results to a specific patient (e.g., `Patient/123`). Primarily for use with Application Access Tokens.

- `group` (Reference[]):
Optional. Filter results to patients in one or more Groups. Can be repeated. Not supported for patient-scoped tokens.

- `_format` (code):
Output format: `json` (default) or `csv`. When `_format` is omitted, the response format falls back to the request's `Accept` header (e.g. `Accept: text/csv` returns CSV); otherwise it defaults to `json`.

- `_limit` (integer):
Maximum number of output rows to return.

- `_since` (instant):
Filter to resources updated since this timestamp.

- `header` (boolean):
For CSV output, whether to include the header row. Defaults to `true`.

#### Query parameters

- `_count` (string):
Number of source resources to process per page.

- `_offset` (string):
Pagination offset for source resources.

#### Response

**JSON response** (default):

Returns an object with `rows` (array of extracted data), optional `link` (pagination), and `resourceCount` (number of source resources processed). When more pages exist, a `Link` header in RFC 5988 format with `rel="next"` is also returned (in addition to the body `link` array).

**CSV response** (`_format=csv`):

Returns plain CSV text. Pagination info is in response headers:
- `Link`: RFC 5988 format with `rel="next"` (returned for both JSON and CSV)
- `X-Next-Link`: Direct URL to next page (CSV only)
- `X-Resource-Count`: Number of source resources (CSV only)

*Response*

```json
{
  "rows": [
    {
      "id": "a85f4c92-...",
      "family_name": "Smith",
      "given_name": "John",
      "birth_date": "1985-03-15"
    }
  ],
  "resourceCount": 1
}
```

```csv
id,family_name,given_name,birth_date
a85f4c92-...,Smith,John,1985-03-15
```

For complete ViewDefinition syntax and FHIRPath expressions, see our [Parsing FHIR guide](https://www.flexpa.com/docs/guides/parsing-fhir).

---

### Capability Statement

CapabilityStatement is a conformance FHIR Resource that is used to understand the exact capabilities that a FHIR server makes available.
The CapabilityStatement resource is used to describe the features and capabilities of a FHIR server in a machine-readable way.
[CapabilityStatement](https://www.hl7.org/fhir/CapabilityStatement.html) is a base FHIR resource.

Flexpa's CapabilityStatement is available at the `/fhir/metadata` route.
View it [here](https://api.flexpa.com/fhir/metadata).

**Note:**
https://api.flexpa.com/fhir/metadata is an unauthenticated route. You do not need to provide an `access_token` to access this route.

#### Helpful capabilities
We've highlighted the following capabilities to provide extra convenience to developers when querying data.
The following examples are defined per-resource.
- [`interaction`](#interaction) is an array of objects that describe the valid operations that can be performed on the resource.
- [`searchInclude`](#search-include) is an array of strings that describe the valid values that can be used with the `_include` search param.
- [`searchParam`](#search-param) is an array of objects that describe the valid params that the server accepts in a URL query string.
- `operation` is an array of objects that describe the FHIR operations supported on the resource. Currently only the [Patient](https://www.flexpa.com/docs/fhir/patient) resource declares this array, exposing the [`$everything`](#patient-everything) and [`$summary`](#patient-summary) operations.

*Request*

```bash
curl https://api.flexpa.com/fhir/metadata
```

```js
const response = await fetch("https://api.flexpa.com/fhir/metadata");
const flexpaCapabilityStatement = await response.json();
```

```json
{
  "resourceType": "CapabilityStatement",
  "url": "https://api.flexpa.com/fhir/metadata",
  "title": "Flexpa Capability Statement",
  "date": "...", // current server date (YYYY-MM-DD), regenerated on every request
  "publisher": "Flexpa",
  "rest": [
    {
      "mode": "server",
      "resource": [
        { "type": "Patient", ... },
        { "type": "Coverage", ... },
        { "type": "ExplanationOfBenefit", ... },
        ...
      ]
    }
  ]
}
```

#### Interaction

All the FHIR resources that Flexpa supports have both a `read` and `search-type` operation, which means that they can be both [read](https://www.flexpa.com/docs/records#read) and [searched](https://www.flexpa.com/docs/records#search).
You can find the `interaction` array in the CapabilityStatement resource.

```json
{
  "resourceType": "CapabilityStatement",
  "url": "https://api.flexpa.com/fhir/metadata",
  "rest": [
    {
      "mode": "server",
      "resource": [
        {
          "type": "Practitioner",
          "interaction": [
            {
              "code": "read",
            },
            {
              "code": "search-type",
            }
          ]
        }
      ]
    }
  ]
}
```

#### Search include

The `searchInclude` array describes the valid values that can be used with the `_include` search param.
Each value is a string with the format `[Resource]:[field]`, where `[Resource]` is the resource type and `[field]` is the field name.
For example, to include the `care-team` field of an [ExplanationOfBenefit](https://www.flexpa.com/docs/fhir/explanation-of-benefit) resource in the search response, you would use the value `ExplanationOfBenefit:care-team`.

For the search to successfully return a [CareTeam](https://www.flexpa.com/docs/fhir/care-team) resource, the following conditions must be met:
1. A `care-team` field must be present in the [ExplanationOfBenefit](https://www.flexpa.com/docs/fhir/explanation-of-benefit) resource.
2. The `care-team` field must contain a [relative reference](#relative-references) to a [CareTeam](https://www.flexpa.com/docs/fhir/care-team) resource.

To use the `_include` search param, refer to the [Search](#search) section.

```json
{
  "resourceType": "CapabilityStatement",
  "url": "https://api.flexpa.com/fhir/metadata",
  "rest": [
    {
      "mode": "server",
      "resource": [
        {
          "type": "ExplanationOfBenefit",
          "searchInclude": [
            "ExplanationOfBenefit:care-team",
          ]
        }
      ]
    }
  ]
}
```

#### Search param

The `searchParam` array describes the valid params that the server accepts in a URL query string.
These params can be used to filter the search results.
The name of the param can be accessed in the `name` property of each `searchParam` object in the CapabilityStatement resource.

To filter search results with a `searchParam`, refer to the [Search](#search) section.

```json
{
  "resourceType": "CapabilityStatement",
  "url": "https://api.flexpa.com/fhir/metadata",
  "rest": [
    {
      "mode": "server",
      "resource": [
        {
          "type": "Condition",
          "searchParam": [
            {
              "name": "onset-age",
              "definition": "http://hl7.org/fhir/SearchParameter/Condition-onset-age",
              "type": "quantity"
            }
          ]
        }
      ]
    }
  ]
}
```

---

### Wildcard parameters

Flexpa API supports wildcard parameters that can be used in URL query parameters in FHIR API requests.

Wildcards are used as tokens directly in the URL of the API request you make to Flexpa.
They are replaced with real values by the API using context provided by the required [Patient Access Token](#authentication).

We currently support one parameter `$PATIENT_ID`, which references the `patient_id` belonging to the `access_token`.
Flexpa will replace this token with the correct `patient_id` when you make an API request to Flexpa.

**Warning:**
`$PATIENT_ID` resolves to a single Patient ID — the master Patient on a [patient linking](https://www.flexpa.com/docs/guides/patient-linking) consent. [`$everything`](#patient-everything), [`$summary`](#patient-summary), and [`$pdf`](#patient-pdf) reach every connection on the consent only when you pass the wildcard; substitute the literal ID and they return that Patient's data alone. A search filtered on the wildcard matches only the resolved Patient and can come back empty — with a [Patient Access Token](#patient-access-token), omit the patient filter to reach every exchanged Patient Authorization, including dependents a single connection returns.

*Wildcard in Patient Read*

```bash
ACCESS_TOKEN=patient-access-token

curl 'https://api.flexpa.com/fhir/Patient/$PATIENT_ID' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

---

### Search result parameters

Flexpa supports search result parameters as a way to modify search results. The following search result query parameters can be used in your [search](#search) request:

- `_total` (string):
The `_total` query parameter will include in the bundle the number of resources that match the search parameters. It is not always visible on the bundle. The possible values for the `_total` search result paramter are:
  - `none`: Flexpa will not include the total in the response
  - `accurate`: Flexpa will provide the exact total of matching resources, if available. Note that this may be more server intensive.
  - `estimate`: Flexpa will provide a rough estimate of the number of matching resources, if available.

- `_sort` (string):
The `_sort` parameter is used to sort results in priority order based on a comma-separated list of search parameters, for example `status,-date,category`.
If the `_sort` value starts with `-`, then the results are returned in decreasing order, otherwise they are returned in increasing order.

- `_summary` (string):
The `_summary` parameter returns a portion of a resource's elements in order to help optimize queries for only the essential information.
Supported values for `_summary` are `true`, which returns only elements that are marked `summary` in the resource's definition, and `count` which will return only the count of matching resources, but no other resource details.

- `_elements` (string):
The `_elements` parameter returns a specified subset of a resource's elements. Specified elements are given as a list of comma separated values, for example `_elements=identifier,active,link`.
However, *more* than only requested elements may be returned, including mandatory elements or modifier elements that have values.

- `_count` (string):
The `_count` parameter limits the number of results per page. See [Pagination](#pagination) for more information.

*Request*

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/ExplanationOfBenefit?patient=$PATIENT_ID&_total=accurate";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/ExplanationOfBenefit?patient=$PATIENT_ID&_sort=-status";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/ExplanationOfBenefit?patient=$PATIENT_ID&_summary=count";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

```js
const ACCESS_TOKEN="patient-access-token";

const searchUrl = "https://api.flexpa.com/fhir/Condition?patient=$PATIENT_ID&_elements=clinicalStatus";

const response = await fetch(searchUrl, {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const searchBundle = await response.json();
```

*Response*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [...],
  "total": 11,
  "link": [...]
}
```

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "status": "draft",
        ...
      },
      ...
    },
    {
      "resource": {
        "status": "active",
        ...
      },
      ...
    },
    {
      "resource": {
        "status": "active",
        ...
      },
      ...
    },
  ],
  "link": [...]
}
```

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "total": 11,
  "link": [...]
}
```

```json
{
  "resourceType": "Bundle",
  "id": "22f61d0877b54b2a8a2feb57bfe2c462",
  "entry": [
    {
      "resource": {
        "resourceType": "Condition",
        "clinicalStatus": {
            "coding": [
                {
                    "system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
                    "code": "active"
                }
            ]
        }
      }
    },
    {
      "resource": {
        "resourceType": "Condition",
        "clinicalStatus": {
            "coding": [
                {
                    "system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
                    "code": "active"
                }
            ]
        }
      }
    }
  ]
}
```

---

### Pagination

Flexpa supports pagination on the results of a FHIR [search](#search) request.
Pagination can reduce the load on both the client and server.

You can leverage pagination using the following query parameters in your [search](#search) request:
- `_count` to control the page size
- `_offset` to control the page number

In the Flexpa API, the default page size is 20, and the maximum allowed page size is 1000.

Alternatively, if a search result is paginated, the Bundle includes a [`link`](https://www.hl7.org/fhir/http.html#paging) array that references other pages in relation to the current page:
- `self` is the URL of the current page. Always present in `link`.
- `first` is the URL of the first page. Always present in `link`.
- `next` is the URL of the next page. Only present in `link` if there is a next page.
- `previous` is the URL of the previous page. Only present in `link` if there is a previous page.

For example, to access the next page of resources, make a GET request to the URL indicated by `"relation": "next"`.

**Warning:**
Offset paging cannot go past an `_offset` of 10,000. A request past that limit returns a `422`, and this includes `next` links that use `_offset`. To page through larger results, add `_sort=_lastUpdated` (ascending, with no other sort) to your first request, do not set `_offset`, and do not set `_count` below 20. The `next` links then use a cursor with no depth limit, for example `GET /fhir/Observation?_sort=_lastUpdated&_count=1000`.

*Request*

```bash
ACCESS_TOKEN=patient-access-token

curl https://api.flexpa.com/fhir/Condition?_count=3 \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```js
const ACCESS_TOKEN="patient-access-token"

const response = await fetch("https://api.flexpa.com/fhir/Condition?_count=3", {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const bundle = await response.json();
```

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [ ... ],
  "link": [
    {
        "relation": "self",
        "url": "https://api.flexpa.com/fhir/Condition?_count=3&_offset=6&_tag=..."
    },
    {
        "relation": "first",
        "url": "https://api.flexpa.com/fhir/Condition?_count=3&_offset=0&_tag=..."
    },
    {
        "relation": "next",
        "url": "https://api.flexpa.com/fhir/Condition?_count=3&_offset=9&_tag=..."
    },
    {
        "relation": "previous",
        "url": "https://api.flexpa.com/fhir/Condition?_count=3&_offset=3&_tag=..."
    },
  ]
}
```

---

### Referenced resources

Many resources returned by the API will contain references to other resources.
A reference is a string that points to the location where the referenced resource can be retrieved.
For instance, a [Patient](https://www.flexpa.com/docs/fhir/patient) may contain a reference to an [Organization](https://www.flexpa.com/docs/fhir/organization) or a [Practitioner](https://www.flexpa.com/docs/fhir/practitioner).

References can be categorized into one of three types, each of which require a different approach to resolve:
- [Relative](#relative-references)
- [Internal](#internal-references)
- [Absolute](#absolute-references)

#### Relative references
Relative references are relative to the base resource.
They can be identified by the structure `[resourceType]/[id]`.
You can resolve a relative reference by appending the value of the `reference` string to the base URL in a subsequent GET request.

**Note:**
Alternatively, you can conveniently resolve relative references in a single API request by using the `_include` parameter on a [Search](#search) operation.
For more information on available `searchInclude` parameters, please refer to the [CapabilityStatement](#search-include).

#### Internal references
Internal references point to a "contained" resource that is directly embedded within the base resource.
They can be identified by a `#` prefix.
You can access the contained resource in the `contained` field by filtering for the matching `id`.

**Note:**
Contained resources in FHIR do not need to be complete resources.
For example, a contained resource may only contain a `name` field and this is considered valid FHIR.

#### Absolute references
Absolute references are standalone URLs.
They can be identified by any valid URI prefix, but are typically prefixed by either `http`, `https` or `urn`.
You _may_ be able request more data using the URL in its entirety.
Note that this request will be to a FHIR API separate from Flexpa's.

**Warning:**
Following URLs to external servers is always risky.
Please consider the security implications of doing so and take the appropriate steps to mitigate unintended access to malicious servers, such as an allowlist of trusted servers for example.
Alternatively, the most conservative approach is to avoid following absolute references altogether.

For more information on references in FHIR, please refer to the [FHIR References documentation](https://hl7.org/fhir/R4/references.html).

*Resolving References*

```js
const patient = {
  "resourceType" : "Patient",
  "generalPractitioner" : {
    "reference" : "Practitioner/123"
  }
};

const ACCESS_TOKEN="patient-access-token";

const response = await fetch("https://api.flexpa.com/fhir/Practitioner/123", {
  headers: {
    "authorization": `Bearer ${ACCESS_TOKEN}`,
  },
});
const practitioner = await response.json();
```

```js
const patient = {
  "resourceType" : "Patient",
  "generalPractitioner" : {
    "reference" : "#p1"
  },
  "contained" : [
    {
      "resourceType" : "Practitioner",
      "id" : "p1",
      "name" : "Dr. Adam Smith"
    }
  ]
}

const practitionerRef = patient.generalPractitioner.reference.split("#")[1];
const practitioner = patient.contained.find((resource) => resource.id === practitionerRef);
```

```js
const patient = {
  "resourceType" : "Patient",
  "generalPractitioner" : {
    "reference" : "https://other.fhir.server.com/Practitioner/external-123"
  }
}

const practitionerRef = patient.generalPractitioner.reference;
if (isSecureUrl(practitionerRef)) {
  const response = await fetch(practitionerRef);
  const practitioner = await response.json();
}
```

*Resolved Resource*

```js
{
  "resourceType" : "Practitioner",
  "id" : "123",
  "name" : "Dr. Adam Smith"
}
```

```js
{
  "resourceType" : "Practitioner",
  "id" : "p1",
  "name" : "Dr. Adam Smith"
}
```

```js
{
  "resourceType" : "Practitioner",
  "id" : "external-123",
  "name" : "Dr. Adam Smith"
}
```

---

### Errors

When a request is unsuccessful, Flexpa API attempts to return an `OperationOutcome` FHIR R4 Resource.
If the [Endpoint](https://www.flexpa.com/docs/network/directory) connected by the patient during authorization returns an `OperationOutcome` Flexpa API returns it directly.
If the endpoint does not return an `OperationOutcome`, Flexpa API substitutes the actual response with a Flexpa-generated `OperationOutcome` to represent the error.

Your application code should be prepared to handle the following `issue.code` values:

**Error codes**

- `processing` (4xx status code): The generic code for client-side (4xx) errors that are not specifically `not-supported` (404) or `forbidden` (403); commonly returned with a 422 status code. This is expected to be final (e.g., there is no point resubmitting the same content unchanged).

- `transient` (429 status code): The API returns a 429 status code while syncing data from the source. This happens during the initial sync period. Most syncs complete in under a minute, but patients with large record sets on slower endpoints can take several minutes. During this time, data cannot be expunged.

- `throttled` (429 status code): The request was rate limited. Wait for the number of seconds in the `Retry-After` header before retrying — see [Rate Limits](#rate-limits).

- `not-supported` (404 status code): The interaction, operation, resource or profile is not supported.

- `forbidden` (403 status code): The user does not have the rights to perform this action.

- `exception` (500+ status code): An unexpected internal error has occurred.

```json
{
  "resourceType": "OperationOutcome",
  "issue": [{
    "severity": "error",
    "code": "not-supported"
  }],
};
```

---

### Rate limits

To protect the stability of the API, requests are rate limited. When your application exceeds the available request quota, the Flexpa API responds with a `429 Too Many Requests` status code and an `OperationOutcome` with an `issue.code` of `throttled`.

Every rate limited response carries a backoff signal in its headers:

**Response headers**

- `Retry-After` (seconds): How long to wait before retrying the request.

- `X-RateLimit-Reset` (seconds): Seconds until the current rate limit window resets to its full quota.

- `X-RateLimit-Limit` (number): Total quota units in the current window, when known.

- `X-RateLimit-Remaining` (number): Quota units remaining in the current window, when known.

Treat a `throttled` `429` as retryable: wait at least `Retry-After` seconds, then retry the request. Retrying sooner — or retrying without any backoff — extends the throttle window and delays recovery. Other `4xx` responses are final and should not be retried unchanged.

A `429` with an `issue.code` of `transient` is not a rate limit — it indicates an initial [sync](#sync-job-states) is still in progress (see [Errors](#errors)).

These are the current limits. They may change, so drive backoff from the response headers rather than from this table.

| Request | Limit |
| --- | --- |
| [FHIR API](#fhir-api) reads, searches and operations | 50,000 quota units per minute. A read costs 1 unit. A search costs 20, plus 1 for each resource its `_include` adds. |
| [`Patient/$everything`](#patient-everything) | 100 requests per minute per consent with a patient access token. 110 requests per minute per application and mode with an application access token. |
| [`Patient/$summary`](#patient-summary) | 100 requests per minute |
| [`Patient/$pdf`](#patient-pdf) | 100 requests per minute |
| [`GET /oauth/authorize`](https://www.flexpa.com/docs/consent#authorization) | 50 requests per minute |
| [`POST /oauth/token`](https://www.flexpa.com/docs/consent#token) | 150 requests per minute |
| [`GET /rest/consent`](https://www.flexpa.com/docs/consent#consent-1) | 60,000 requests per minute |
| [`GET /smart/health-links/stats`](https://www.flexpa.com/docs/smart-health-links#shl-statistics) | 30 requests per minute |
| [MCP](https://www.flexpa.com/docs/guides/mcp-registry) | 120 requests per minute, and 60 calls per minute per capability |

`Patient/$everything`, `Patient/$summary` and `Patient/$pdf` also draw from the FHIR API quota.

For `Patient/$everything`, `Patient/$summary`, `Patient/$pdf`, `GET /rest/consent` and `GET /rest/consent/:consentId`, requests count against the token that makes them, not the IP address they come from. Each consent has its own limit, so calls for many patients from one server do not share one limit. All of an application's servers share one limit per mode, so `TEST` requests never count against `LIVE`.

```bash
HTTP/2 429
retry-after: 26
x-ratelimit-reset: 26
x-ratelimit-limit: 50000
x-ratelimit-remaining: 0
```

```json
{
  "resourceType": "OperationOutcome",
  "id": "too-many-requests",
  "issue": [
    {
      "severity": "error",
      "code": "throttled",
      "details": {
        "text": "Too Many Requests"
      }
    }
  ]
}
```

## Transforms

Flexpa's transform pipeline processes FHIR data from connected sources, delivering a more consistent, comprehensive, and usable dataset. Most of these transforms are applied to all data retrieved through the Flexpa API without any configuration needed. A few transforms (such as NPI enrichment) are currently limited-availability and must be enabled for your application.

Our transform architecture offers several key benefits:

- **Consistent Resource Structure**: Consistent formats for resources returned by different sources

- **Enhanced Provider Information**: Resources enriched with detailed provider data through NPI resolution (limited availability — enabled per application)

- **Standardized Identifiers**: Deterministic UUIDv5 identifiers ensuring consistent identification and preventing collisions

- **Improved Reference Integrity**: Standardized references between resources for easier data navigation

The sections below highlight the most significant transforms in our pipeline:
- [Code systems](#code-systems)
- [Tags](#tags)
- [Identifiers](#identifiers)
- [References](#references)
- [NPIs](#npis)
- [Conditions](#conditions)
- [Deduplication](#deduplication)
- [Validation](#validation)

---

### Code systems

Healthcare data sources reference coding systems inconsistently in their FHIR implementations. Flexpa's code system normalization transform resolves these inconsistencies so you can match on a single canonical URI per code system. This transform:

1. **Resolves system URIs**: Maps nonstandard URIs, OIDs, and common variants (e.g., wrong case, `http` vs `https`, trailing `.html`) to canonical URIs
2. **Disambiguates by code format**: Distinguishes ICD-10-CM (diagnosis) from ICD-10-PCS (procedure) when both appear under a generic ICD-10 URI, and corrects CPT codes miscategorized under ICD-10 URIs
3. **Standardizes code values**: Reformats NDC codes to the standard 5-4-2 hyphenated format with zero-padding (e.g., `1234-5678-90` → `01234-5678-90`)

#### Benefits

- **Simplified queries**: Match on canonical URIs without accounting for endpoint-specific variations
- **Accurate classification**: Diagnosis and procedure codes are assigned to the correct code system
- **Consistent formats**: Code values like NDC follow a single standard format

#### How it works

A set of global rules fixes common OID and URI variants for SNOMED, LOINC, RxNorm, CPT, ICD-10-CM, and HCPCS across all resource types in the bundle.
On ExplanationOfBenefit resources, additional rules resolve endpoint-specific and legacy URI variants, disambiguate codes like ICD-10-CM and ICD-10-PCS based on code format, and reformat NDC code values.

The [terminology](https://www.flexpa.com/docs/fhir/code-systems) reference lists all supported code systems and their canonical URIs.

*Before code system normalization*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "diagnosis": [{
    "diagnosisCodeableConcept": {
      "coding": [{
        "system": "urn:oid:2.16.840.1.113883.6.90",
        "code": "M54.5"
      }]
    }
  }],
  "procedure": [{
    "procedureCodeableConcept": {
      "coding": [{
        "system": "http://hl7.org/fhir/sid/icd-10",
        "code": "0SRC0J9"
      }]
    }
  }],
  "item": [{
    "productOrService": {
      "coding": [{
        "system": "http://hl7.org/fhir/sid/ndc",
        "code": "1234-5678-90"
      }]
    }
  }]
}
```

*After code system normalization*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "diagnosis": [{
    "diagnosisCodeableConcept": {
      "coding": [{
        "system": "http://hl7.org/fhir/sid/icd-10-cm",
        "code": "M54.5"
      }]
    }
  }],
  "procedure": [{
    "procedureCodeableConcept": {
      "coding": [{
        "system": "http://www.cms.gov/Medicare/Coding/ICD10",
        "code": "0SRC0J9"
      }]
    }
  }],
  "item": [{
    "productOrService": {
      "coding": [{
        "system": "http://hl7.org/fhir/sid/ndc",
        "code": "01234-5678-90"
      }]
    }
  }]
}
```

---

### Tags

Flexpa adds standardized tags to all FHIR resources to provide consistent tracking and identification information. These tags help trace the origin of resources and provide additional context for your application.

Each resource is automatically tagged with the following metadata:

1. **Consent ID**: Unique identifier of the consent (OAuth authorization) that this data belongs to
2. **Patient Authorization ID**: Unique identifier of the patient authorization that sourced this data
3. **Endpoint ID**: Identifier of the health plan or provider endpoint that supplied the data
4. **Application ID**: Your application's identifier within the Flexpa system
5. **Patient Authorization Mode**: Whether the authorization was in `TEST` or `LIVE` mode
6. **Authorization Type**: The method used for authorization (e.g., `OAUTH`)

#### Benefits

- **Traceability**: Easily identify the source of each resource in your system
- **Filtering**: Filter and organize resources by their origin or authorization type
- **Auditing**: Maintain a clear data lineage for compliance and record-keeping
- **Operational Insights**: Track which endpoints and authorization methods are providing your data

#### How It Works

The tags are added during data processing as part of the Flexpa transform pipeline and require no configuration. They're stored in the resource's `meta.tag` array as standard FHIR Coding objects, each with a Flexpa-specific system URI.

Each tag uses a specific system URL that identifies its purpose. You can use these system URLs to query for specific tags or filter resources programmatically.

**System URLs**

- `https://fhir.flexpa.com/identifiers/ConsentId`:
Identifies the consent (OAuth authorization) that this data belongs to

- `https://fhir.flexpa.com/identifiers/PatientAuthorizationId`:
Identifies the unique patient authorization that sourced this data

- `https://fhir.flexpa.com/identifiers/EndpointId`:
Indicates which health plan or provider endpoint supplied the data. Resources that are not sourced from a single endpoint omit this tag, including data retrieved natively over TEFCA (tagged `IAL2`) and the master Patient resource Flexpa creates to link a patient's records across connections. Use `PatientAuthorizationId` to attribute TEFCA data to its connection.

- `https://fhir.flexpa.com/identifiers/ApplicationId`:
Identifies your application within the Flexpa system

- `https://fhir.flexpa.com/identifiers/PatientAuthorizationMode`:
Indicates if the authorization was in `TEST` or `LIVE` mode

- `https://fhir.flexpa.com/identifiers/AuthorizationType`:
The patient authorization's type, for example `OAUTH` or `IAL2`. Records retrieved natively over nationwide exchange (TEFCA) are tagged `IAL2`. Records from a SMART on FHIR source are tagged `OAUTH`, including Epic sites reached through a nationwide exchange consent, since TEFCA is used there only to locate records.

*Before Tagging Transform*

```json
{
  "resourceType": "Patient",
  "id": "example-patient-id",
  "meta": {
    "lastUpdated": "2023-05-15T14:30:00Z"
  },
  "name": [
    {
      "family": "Smith",
      "given": ["John"]
    }
  ]
}
```

*After Tagging Transform*

```json
{
  "resourceType": "Patient",
  "id": "example-patient-id",
  "meta": {
    "lastUpdated": "2023-05-15T14:30:00Z",
    "tag": [
      {
        "system": "https://fhir.flexpa.com/identifiers/ConsentId",
        "code": "f7e23a91-bc45-4d12-9e8f-1a2b3c4d5e6f"
      },
      {
        "system": "https://fhir.flexpa.com/identifiers/PatientAuthorizationId",
        "code": "8a350181-3115-49d7-a6aa-8e05b1cab08a"
      },
      {
        "system": "https://fhir.flexpa.com/identifiers/EndpointId",
        "code": "a5c22966-244d-4f36-b43a-4d4a619f89cc",
        "display": "flexpa-sandbox"
      },
      {
        "system": "https://fhir.flexpa.com/identifiers/ApplicationId",
        "code": "062ca646-8d42-4753-9cd1-b39b234dd559"
      },
      {
        "system": "https://fhir.flexpa.com/identifiers/PatientAuthorizationMode",
        "code": "TEST"
      },
      {
        "system": "https://fhir.flexpa.com/identifiers/AuthorizationType",
        "code": "OAUTH"
      }
    ]
  },
  "name": [
    {
      "family": "Smith",
      "given": ["John"]
    }
  ]
}
```

---

### Identifiers

The Identifiers transform systematically replaces all resource IDs with deterministic UUIDv5 identifiers to ensure consistent and collision-free data handling across sources and authorizations. This transform:

1. **Preserves Original IDs**: For payer and provider connections, stores the original source ID in the resource's `identifier` array with the system `{endpoint FHIR base URL}/{ResourceType}/SourceResourceId` (payer and provider connections only, not TEFCA (IAL2) resources, which have no endpoint)
2. **Creates Deterministic IDs**: Generates new IDs using UUIDv5 namespacing that remains consistent across syncs
3. **Updates References**: Updates all references within the bundle to use the new IDs
4. **Maintains Relationships**: Preserves the referential integrity between resources

#### Benefits

- **Consistency**: Eliminates ID collisions between different sources using the same ID formats
- **Determinism**: Same resource from the same source will always get the same ID
- **Traceability**: For payer and provider connections, original IDs are preserved in the `identifier` array for tracking
- **Interoperability**: Standardized ID format works across different systems and integrations

#### How It Works

The Identifiers transform uses UUIDv5 to deterministically generate UUIDs.
The input for the UUID is formed by concatenating, in order, the source (the endpoint ID, or the identity provider for identity-based flows such as TEFCA/IAL2), the resource type, and the original source ID.
A separate UUID is generated for the Patient resource belonging to the consenting patient and used as the namespace.

This approach ensures that:

- The same resource will always receive the same ID when synced again
- Resources from different patients remain distinct even if their original IDs were identical
- References between resources remain intact with the updated IDs

**Note:**
When working with FHIR data from Flexpa, always use the resource's ID for references rather than trying to reconstruct references from original identifiers.

*Before Identifiers Transform*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "id": "123456",
  "patient": {
    "reference": "Patient/98765"
  },
  "provider": {
    "reference": "Practitioner/PROV001"
  }
}
```

*After Identifiers Transform*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "id": "a1b2c3d4-e5f6-5a5a-b5c5-d5e5f5a5b5c5",
  "identifier": [
    {
      "system": "https://api.payer.com/fhir/ExplanationOfBenefit/SourceResourceId",
      "value": "123456"
    }
  ],
  "patient": {
    "reference": "Patient/f9e8d7c6-b5a4-5b5b-c5d5-e5f5a5b5c5d5"
  },
  "provider": {
    "reference": "Practitioner/c9b8a7d6-e5f4-5c5c-d5e5-f5a5b5c5d5e5"
  }
}
```

---

### References

The References transform ensures that all FHIR references between resources are properly structured, resolvable, and consistent. This transform:

1. **Updates Resource IDs**: Ensures all references point to the new UUIDv5 IDs created by the [Identifiers](#identifiers) transform
2. **Resolves NPI References**: Expands NPI identifiers into proper resource references as part of the [NPIs](#npis) transform
3. **Handles Different Reference Types**: Works with all reference formats including relative, internal, and absolute references
4. **Preserves Source URLs**: Maintains original reference information by adding `source` and `fullUrl` metadata

#### Benefits

- **Complete Navigation**: Users can follow references between resources without broken links
- **Consistent Referencing**: All references follow a standardized format
- **Traceability**: Original source URLs are preserved for auditing and debugging
- **Proper FHIR Structure**: References comply with FHIR specifications

#### How It Works

The References transform operates in multiple stages.

First, during the Identifiers transform, all references within resources are updated to use the new UUIDv5 IDs.

Second, during the NPI transform, identifiers with NPIs are expanded into full references to Provider resources.

Finally, during sourcing, `fullUrl` and `source` metadata are added to preserve origin information.

**Note:**
References between resources are a key part of the FHIR standard. Flexpa ensures that all references work properly so you can navigate between related resources.

*Before References Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "123456",
        "patient": {
          "reference": "Patient/98765"
        },
        "provider": {
          "identifier": {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        }
      }
    }
  ]
}
```

*After References Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "fullUrl": "https://api.payer.com/ExplanationOfBenefit/123456",
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "a1b2c3d4-e5f6-5a5a-b5c5-d5e5f5a5b5c5",
        "meta": {
          "source": "https://api.payer.com/ExplanationOfBenefit/123456"
        },
        "patient": {
          "reference": "Patient/f9e8d7c6-b5a4-5b5b-c5d5-e5f5a5b5c5d5"
        },
        "provider": {
          "reference": "Practitioner/c9b8a7d6-e5f4-5c5c-d5e5-f5a5b5c5d5e5",
          "identifier": {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        }
      }
    },
    {
      "fullUrl": "https://api.payer.com/Practitioner/PROV001",
      "resource": {
        "resourceType": "Practitioner",
        "id": "c9b8a7d6-e5f4-5c5c-d5e5-f5a5b5c5d5e5",
        "meta": {
          "source": "https://api.payer.com/Practitioner/PROV001"
        },
        "identifier": [
          {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        ],
        "name": [
          {
            "family": "Smith",
            "given": ["John", "A"],
            "prefix": ["Dr."]
          }
        ]
      }
    }
  ]
}
```

---

### NPIs

The National Provider Identifier (NPI) transform enhances FHIR bundles by enriching provider information using NPI references found in the data.

**Note:**
NPI enrichment is currently a limited-availability capability that must be enabled for your application.

While enabled, when an NPI is detected in a FHIR resource Flexpa will:

1. Identify NPIs within the bundle
2. Look up detailed provider information from those NPIs using the National Plan & Provider Enumeration System (NPPES)
3. Expand NPI references in the bundle to include full provider details
4. Backfill provider information such as names, addresses, specialties, and contact information

This transform works with both Practitioner and Organization resources, enhancing references in resources like Patient, Coverage, and ExplanationOfBenefit.

Flexpa adds NPPES data next to what the [Endpoint](https://www.flexpa.com/docs/network/directory) sent and does not replace it. Practitioner names, and addresses, telecom, and contact entries for both resource types, can therefore appear twice. When the Endpoint already sent an Organization name, the NPPES name is added to `alias`.

#### Benefits

- **Richer Data**: Adds comprehensive provider details that may be missing in the original data
- **Consistent Provider Information**: Standardizes provider data across different payers and sources
- **Improved User Experience**: Enables applications to display detailed provider information without additional lookups

#### How It Works

When enabled for your application, the NPI transform runs during data processing and works in three phases—**reference expansion**, **data backfilling**, and **resource resolution**.

- **Reference Expansion** – Converts bare NPI identifiers into full FHIR references and, when needed, creates the corresponding Practitioner or Organization resource.
- **Data Backfilling** – Enriches those provider resources with names, addresses, telecom details, and specialties sourced from NPPES.
- **Resource Resolution** – Revisits the bundle and rewires related resources so they point to the newly enriched provider entries, ensuring every resource has a proper, navigable reference path.

*Before NPI Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "eob-12345",
        "provider": {
          "identifier": {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        }
      }
    }
  ]
}
```

*After NPI Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "a1b2c3d4-e5f6-5a5a-b5c5-d5e5f5a5b5c5",
        "provider": {
          "reference": "Practitioner/c9b8a7d6-e5f4-5c5c-d5e5-f5a5b5c5d5e5",
          "identifier": {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        }
      }
    },
    {
      "resource": {
        "resourceType": "Practitioner",
        "id": "c9b8a7d6-e5f4-5c5c-d5e5-f5a5b5c5d5e5",
        "identifier": [
          {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        ],
        "name": [
          {
            "family": "Smith",
            "given": ["John", "A"],
            "prefix": ["Dr."]
          }
        ],
        "address": [
          {
            "line": ["123 Main St"],
            "city": "Anytown",
            "state": "CA",
            "postalCode": "12345"
          }
        ],
        "telecom": [
          {
            "system": "phone",
            "value": "555-123-4567"
          }
        ],
        "qualification": [
          {
            "code": {
              "coding": [
                {
                  "system": "http://nucc.org/provider-taxonomy",
                  "code": "207R00000X",
                  "display": "Internal Medicine"
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
```

---

### Medications

**Note:**
**Preview**: This transform is in preview and is available to enterprise partners.

The Medications transform enhances FHIR bundles by creating MedicationRequest resources from pharmacy claims data found in ExplanationOfBenefit resources. This transform:

1. Identifies pharmacy claims in ExplanationOfBenefit resources
2. Extracts medication information from these claims
3. Creates structured MedicationRequest resources with proper references
4. Maintains bidirectional linkage between the source claims and derived medication requests

This process ensures that medication information is consistently available as MedicationRequest resources, even when the original payer API doesn't directly expose this data in that format.

#### Safety Notice

MedicationRequest resources derived from pharmacy claims may not indicate medications that were actually dispensed or taken. Claims may have been denied or partially fulfilled. Check the associated ExplanationOfBenefit resources (in `supportingInformation`) for claim adjudication status.

#### Benefits

- **Improved Medication Data Access**: Provides a standardized way to access medication information through the MedicationRequest resource type
- **Connected Resources**: Maintains proper references between medication requests and their source claims
- **Consistent Experience**: Creates a uniform experience across different payers, regardless of their underlying API implementation

#### How It Works

The Medications transform occurs automatically during data processing and includes:

- **Pharmacy Claim Identification**: Detects pharmacy claims in ExplanationOfBenefit resources by checking for pharmacy claim types
- **Medication Information Extraction**: Pulls medication codes, dates, and other details from the claims' `productOrService` fields
- **Resource Creation**: Generates MedicationRequest resources with `status: "unknown"` (indicating that the fulfillment status is unknown) and `intent: "order"` (indicating it was a medication order)
- **Reference Management**: Creates explicit bidirectional references:
  - Adds `supportingInformation` reference from MedicationRequest to source ExplanationOfBenefit
  - Adds `prescription` reference from ExplanationOfBenefit to the MedicationRequest
  - Includes `derivation-reference` extension to clearly mark resources created through this transform
- **Deduplication**: When multiple claims contain the same medication code, creates a single MedicationRequest with references to all source claims

*Before Medications Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
        "type": {
          "coding": [
            {
              "system": "http://terminology.hl7.org/CodeSystem/claim-type",
              "code": "pharmacy"
            }
          ]
        },
        "item": [
          {
            "productOrService": {
              "coding": [
                {
                  "system": "http://hl7.org/fhir/sid/ndc",
                  "code": "12345-6789-01",
                  "display": "Medication Name 20mg"
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
```

*After Medications Transform*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "ExplanationOfBenefit",
        "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
        "type": {
          "coding": [
            {
              "system": "http://terminology.hl7.org/CodeSystem/claim-type",
              "code": "pharmacy"
            }
          ]
        },
        "item": [
          {
            "productOrService": {
              "coding": [
                {
                  "system": "http://hl7.org/fhir/sid/ndc",
                  "code": "12345-6789-01",
                  "display": "Medication Name 20mg"
                }
              ]
            }
          }
        ],
        "prescription": {
          "reference": "MedicationRequest/b7c8d9e0-f1a2-3456-bcde-789012345678"
        }
      }
    },
    {
      "resource": {
        "resourceType": "MedicationRequest",
        "id": "b7c8d9e0-f1a2-3456-bcde-789012345678",
        "status": "unknown",
        "intent": "order",
        "medicationCodeableConcept": {
          "coding": [
            {
              "system": "http://hl7.org/fhir/sid/ndc",
              "code": "12345-6789-01",
              "display": "Medication Name 20mg"
            }
          ]
        },
        "subject": {
          "reference": "Patient/c1d2e3f4-5678-90ab-cdef-1234567890ab"
        },
        "authoredOn": "2023-01-15",
        "supportingInformation": [
          {
            "reference": "ExplanationOfBenefit/a1b2c3d4-e5f6-7890-abcd-ef1234567890"
          }
        ],
        "extension": [
          {
            "url": "http://hl7.org/fhir/StructureDefinition/derivation-reference",
            "extension": [
              {
                "url": "reference",
                "valueReference": {
                  "reference": "ExplanationOfBenefit/a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}
```

---

### Conditions

The Conditions transform automatically adds **chronicity** and **clinical classification** data to FHIR Condition resources using two datasets from AHRQ's [Healthcare Cost and Utilization Project (HCUP)](https://hcup-us.ahrq.gov/). For every Condition with an ICD-10-CM code, Flexpa:

1. Classifies the condition as **Chronic**, **Not Chronic**, or **Unknown** using the [Chronic Condition Indicator Refined (CCIR)](https://hcup-us.ahrq.gov/toolssoftware/chronic_icd10/chronic_icd10.jsp) dataset
2. Maps the condition to one or more of **552 CCSR clinical categories** across 22 body systems using the [Clinical Classifications Software Refined (CCSR)](https://hcup-us.ahrq.gov/toolssoftware/ccsr/ccs_refined.jsp) dataset

#### Benefits

- **Filter by chronicity**: Identify chronic conditions without maintaining your own lookup tables
- **Group by body system**: Query conditions by clinical domain (e.g., circulatory, respiratory, endocrine)

#### How It Works

- **Chronicity extension**: Added to `Condition.extension` using `http://hl7.org/fhir/StructureDefinition/condition-related` with a `valueCoding` from system `https://api.flexpa.com/fhir/StructureDefinition/condition-chronicity`. Codes: `C` (Chronic), `NC` (Not Chronic), `U` (Unknown).
- **CCSR category codings**: Appended to `Condition.code.coding` with system `https://hcup-us.ahrq.gov/toolssoftware/ccsr/ccs_refined.jsp`. Each coding includes the CCSR category code and description.
- **Body system categories**: Appended to `Condition.category` as CodeableConcepts with the same CCSR system URI. Body systems are derived from the 3-letter prefix of each CCSR category code (e.g., `END` for Endocrine).

*Before*

```json
{
  "resourceType": "Condition",
  "code": {
    "coding": [
      {
        "system": "http://hl7.org/fhir/sid/icd-10-cm",
        "code": "E11.9",
        "display": "Type 2 diabetes mellitus without complications"
      }
    ]
  }
}
```

*After*

```json
{
  "resourceType": "Condition",
  "code": {
    "coding": [
      {
        "system": "http://hl7.org/fhir/sid/icd-10-cm",
        "code": "E11.9",
        "display": "Type 2 diabetes mellitus without complications"
      },
      {
        "system": "https://hcup-us.ahrq.gov/toolssoftware/ccsr/ccs_refined.jsp",
        "code": "END002",
        "display": "Diabetes mellitus without complication"
      },
      {
        "system": "https://hcup-us.ahrq.gov/toolssoftware/ccsr/ccs_refined.jsp",
        "code": "END005",
        "display": "Diabetes mellitus, Type 2"
      }
    ]
  },
  "category": [
    {
      "coding": [
        {
          "system": "https://hcup-us.ahrq.gov/toolssoftware/ccsr/ccs_refined.jsp",
          "code": "END",
          "display": "Endocrine, Nutritional and Metabolic Diseases"
        }
      ],
      "text": "Endocrine, Nutritional and Metabolic Diseases"
    }
  ],
  "extension": [
    {
      "url": "http://hl7.org/fhir/StructureDefinition/condition-related",
      "valueCoding": {
        "system": "https://api.flexpa.com/fhir/StructureDefinition/condition-chronicity",
        "code": "C",
        "display": "Chronic"
      }
    }
  ]
}
```

---

### Deduplication

Flexpa deduplicates on **identity**, not on **meaning**. A resource is stored once no matter how many times it is synced. A clinical concept is left alone no matter how many resources describe it.

#### One copy per source resource

Every resource Flexpa syncs is written under a stable ID derived from the source system and the source resource, so re-syncing the same connection updates the existing resource instead of creating a second copy. Resources generated by Flexpa use deterministic UUIDv5 IDs derived from their source, which makes the [claims to clinical](https://www.flexpa.com/docs/records/claims-to-clinical) pipeline idempotent across re-syncs.

Each source gets its own resources, so two payers never write to the same resource. [Patient/$everything](#patient-everything) fetches every linked patient in parallel and matches on resource type and ID before returning the Bundle, which guarantees a given stored resource appears exactly once even when two fetches reach it. When paged with `_count`, each page is returned as it is read, so a resource can appear on more than one page.

#### Repeated concepts are preserved

Flexpa does not collapse the same clinical concept across separate source resources. The same code can appear on many ExplanationOfBenefits. If a patient has an A1C test five times in a year, five ExplanationOfBenefits carry that procedure code, and if a chronic condition is billed at every visit, its diagnosis code appears on every one of those claims. All of them are returned, because each is a distinct billed event with its own date, provider, and payment detail. Merging them would destroy the frequency, timing, and attribution that make the data useful.

This means a patient's records can contain many resources that describe the same underlying condition, medication, or test. That is expected, and it preserves the meaning each resource carries about the event it came from.

Those resources are also load-bearing. A Condition generated from a claim is referenced by the ExplanationOfBenefit and Encounter it was derived from, so the five Conditions for one chronic diagnosis are what tie that diagnosis to the five specific visits where it was billed. Collapsing them into one would break those references and erase which encounter each diagnosis belonged to.

#### Deduplicate at read time

When your application needs a unique list, such as a distinct problem list or a formulary, deduplicate on the field you care about when you read the data. Grouping by code system plus code value is usually the right key.

#### Generated resources are deduplicated at creation

Each ExplanationOfBenefit produces its own set of generated resources, and repetition **within that one claim** is collapsed, since a payer often lists the same code more than once on a single claim:

- **Encounters** are generated exactly one per non-pharmacy EOB, and the participants on that Encounter are deduplicated by provider reference and role code
- **Conditions** are deduplicated by code system and code, so a diagnosis listed as both principal and secondary produces one Condition
- **Procedures** are deduplicated by base procedure code and service date, so the same code on two different dates stays two Procedures
- **Provenance** is generated one per EOB, tying every resource generated from that claim back to it

Nothing is collapsed across claims. Two EOBs that carry the same diagnosis produce two Encounters and two Conditions, each traceable to its own claim through its Provenance.

For more information on how these resources are derived and which keys each one uses, see [Claims to clinical](https://www.flexpa.com/docs/records/claims-to-clinical).

---

### Validation

The Validation transform uses the FHIR $validate operation to validate incoming resources and automatically fix common issues in a non-destructive way. Flexpa automatically:

1. Validates resources ingested by our pipeline
2. Applies non-destructive corrective fixes, such as marking required fields with a `data-absent-reason` when they are unknown

#### Benefits

- **Semantic Clarity**: Clearly communicates when data is truly missing from a source system
- **Integrity**: Maintains data accuracy without accidental data loss
- **Interoperability**: Improves compatibility with downstream FHIR systems and consumers

#### How it works

1. **$validate Operation**: Each incoming Bundle is sent to the FHIR `$validate` endpoint.
2. **Parse OperationOutcome**: The resulting `OperationOutcome` is inspected for structural `error` issues.
3. **Auto-correction**: Common issues are fixed non-destructively (e.g., convert scalars to arrays).
4. **Add `data-absent-reason`**: Missing required fields are annotated with the standard `data-absent-reason` extension and a value of `unknown`

*Before Validation*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "id": "example-id",
  "type": {
    "coding": [
      {
        "system": "http://terminology.hl7.org/CodeSystem/claim-type",
        "code": "pharmacy"
      }
    ]
  }
  // Missing required provider field
}
```

*After Validation*

```json
{
  "resourceType": "ExplanationOfBenefit",
  "id": "example-id",
  "type": {
    "coding": [
      {
        "system": "http://terminology.hl7.org/CodeSystem/claim-type",
        "code": "pharmacy"
      }
    ]
  },
  "provider": {
    "extension": [
      {
        "url": "http://hl7.org/fhir/StructureDefinition/data-absent-reason",
        "valueCode": "unknown"
      }
    ]
  }
}
```

## Provider directory

The Provider Directory is a searchable database of healthcare providers in the United States, powered by the National Plan and Provider Enumeration System (NPPES) data. You can use this directory to search for providers by NPI, name, specialty, location, and other criteria.

The Provider Directory is available through the FHIR API and allows you to:

- Search for providers using FHIR's standard search capabilities
- Retrieve detailed provider information including specialties, practice locations, and contact details
- Access provider data without requiring patient consent

Access to the Provider Directory requires an [Application Access Token](#application-access-token), which you can obtain through the [Token Endpoint](https://www.flexpa.com/docs/consent#token).

---

### Practitioner

Individual healthcare providers can be accessed through the Practitioner resource. Each provider's National Provider Identifier (NPI) is carried in `identifier` (use the `identifier` search parameter to look up a provider by NPI). The resource `id` is a Flexpa-assigned UUID used for read-by-id and references. Each Practitioner includes details about their credentials, contact information, and practice locations.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](#application-access-token)

**Request parameters**

- `_project` (string):
Static value `01956cb0-e18e-747a-8dba-265e83e1ade2` to search provider directory. Excluding this parameter will also return patient-specific records.

- `name` (string):
Search by provider name (first, last, or full name)

- `identifier` (token):
Search by NPI (e.g., `identifier=http://hl7.org/fhir/sid/us-npi|1234567890`)

- `address` (string):
Search by address components (city, state, postal code)

**Note:**
Flexpa supports all Practitioner SearchParameters defined in the [FHIR R4 specification](https://www.hl7.org/fhir/R4/practitioner.html#search), including active, email, family, given, phone, telecom, and more.

*Request*

```bash
APP_TOKEN=your-application-access-token

curl "https://api.flexpa.com/fhir/Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|1234567890&_project=01956cb0-e18e-747a-8dba-265e83e1ade2" \
  -H "Authorization: Bearer $APP_TOKEN"
```

```bash
APP_TOKEN=your-application-access-token

curl "https://api.flexpa.com/fhir/Practitioner?name=smith&_project=01956cb0-e18e-747a-8dba-265e83e1ade2" \
  -H "Authorization: Bearer $APP_TOKEN"
```

*Response*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "Practitioner",
        "id": "a57a6cb4-63d8-461e-b4e2-9423080c8a99",
        "identifier": [
          {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "1234567890"
          }
        ],
        "name": [
          {
            "family": "Smith",
            "given": ["John", "A"],
            "prefix": ["Dr."]
          }
        ],
        "telecom": [
          {
            "system": "phone",
            "value": "555-123-4567",
            "use": "work"
          }
        ],
        "address": [
          {
            "line": ["123 Main St"],
            "city": "San Francisco",
            "state": "CA",
            "postalCode": "94105",
            "country": "US"
          }
        ],
        "gender": "male",
        "qualification": [
          {
            "code": {
              "coding": [
                {
                  "system": "http://nucc.org/provider-taxonomy",
                  "code": "390200000X"
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
```

---

### Organization

Healthcare organizations such as hospitals, clinics, and group practices can be accessed through the Organization resource. The resource `id` is a Flexpa-assigned identifier; an organization's National Provider Identifier (NPI) is exposed in `identifier` and is matched via the `identifier` search parameter. Each organization includes details about their type, contact information, and locations.

**Request headers**

- `Authorization` (string):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](#application-access-token)

**Request parameters**

- `_project` (string):
Static value `01956cb0-e18e-747a-8dba-265e83e1ade2` to search provider directory. Excluding this parameter will also return patient-specific records.

- `name` (string):
Search by organization name

- `identifier` (token):
Search by NPI (e.g., `identifier=http://hl7.org/fhir/sid/us-npi|1234567890`)

- `address` (string):
Search by address components (city, state, postal code)

**Note:**
Flexpa supports all Organization SearchParameters defined in the [FHIR R4 specification](https://www.hl7.org/fhir/R4/organization.html#search), including active, address-city, address-state, address-postalcode, email, phone, and more.

*Request*

```bash
APP_TOKEN=your-application-access-token

curl "https://api.flexpa.com/fhir/Organization?identifier=http://hl7.org/fhir/sid/us-npi|2345678901&_project=01956cb0-e18e-747a-8dba-265e83e1ade2" \
  -H "Authorization: Bearer $APP_TOKEN"
```

```bash
APP_TOKEN=your-application-access-token

curl "https://api.flexpa.com/fhir/Organization?name=medical%20center&_project=01956cb0-e18e-747a-8dba-265e83e1ade2" \
  -H "Authorization: Bearer $APP_TOKEN"
```

*Response*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
    {
      "resource": {
        "resourceType": "Organization",
        "id": "cc6b3b49-45f2-4178-81e3-74dea09cfd83",
        "identifier": [
          {
            "system": "http://hl7.org/fhir/sid/us-npi",
            "value": "2345678901"
          }
        ],
        "active": true,
        "type": [
          {
            "coding": [
              {
                "system": "http://nucc.org/provider-taxonomy",
                "code": "103T00000X"
              }
            ]
          }
        ],
        "name": "Bay Area Medical Center",
        "telecom": [
          {
            "system": "phone",
            "value": "555-987-6543",
            "use": "work"
          },
          {
            "system": "email",
            "value": "contact@bayareamedical.example.com",
            "use": "work"
          }
        ],
        "address": [
          {
            "line": ["456 Healthcare Blvd"],
            "city": "San Francisco",
            "state": "CA",
            "postalCode": "94107",
            "country": "US"
          }
        ]
      }
    }
  ]
}
```

## FAQ

#### Which FHIR version does the API support?

The API supports FHIR R4.

#### Does the API support CORS?

No, the API does not support CORS.

The [Quickstart repository](https://www.flexpa.com/docs/guides/quickstart) contains a simple example of a server making requests - replicating that behavior for both the Link operations and subsequent FHIR requests is important for security.

---

### Apply

At Flexpa, our API is core to everything we do. If you're excited to work with us, applying by API is the best way to get our attention.

Find out more about how we work in the [Flexpa OS](https://os.flexpa.com).

**Parameters**

- `name` (string):
Your name

- `email` (string):
Your email address

- `why` (string):
Why do you want to work at Flexpa?

- `location` (string):
Your location

- `resume` (string):
A link to your resume

- `phone` (string):
A phone number where we can reach you

- `github` (string):
A link to your GitHub profile

- `linkedin` (string):
A link to your LinkedIn profile

- `website` (string):
A link to your personal website

- `twitter` (string):
A link to your Twitter profile

*Request*

```bash
curl -X POST https://api.flexpa.com/apply \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Fizz Buzz",
    "email": "fizz@example.com",
    "why": "I want to work at Flexpa because...",
    "location": "Foobar, USA",
    "resume": "https://www.dropbox.com/s/123456789/resume.pdf",
    "phone": "555-555-5555",
    "github": "@fizzbuzz",
    "linkedin": "https://www.linkedin.com/in/fizz-buzz-123456789/",
    "website": "https://www.example.com/",
    "twitter": "@fizzbuzz"
  }'
```

```js
await fetch("https://api.flexpa.com/apply", {
  method: "POST",
  headers: {
    "content-type": "application/json",
  },
  body: JSON.stringify({
    name: "Frederick Banting",
    email: "fred@utoronto.ca",
    why: "I want to work at Flexpa because...",
    location: "Toronto, ON",
    phone: "555-555-5555",
    resume: "https://www.dropbox.com/s/123456789/resume.pdf",
    github: "@frederickbanting",
    linkedin: "https://www.linkedin.com/in/frederick-banting-123456789/",
    website: "https://www.frederickbanting.com/",
    twitter: "@frederickbanting"
  }),
});
```

## Next steps
