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

# Lab ordering

> Order lab tests for a patient with POST /v0.1/laboratories: patient fields, test ids, retries, errors and current gaps.

Lab ordering places an order for one or more lab tests with OpenLoop's lab network, for a patient
who already exists in your organization. It is available by arrangement: your credentials are
granted the `laboratories:write` permission when lab ordering is set up for you. Confirm with your
OLH implementation contact that it is, in each environment, before your first call.

## What you'll do

**1. Get your lab setup from your implementation contact**

The `lab_test_ids` you may order, which of them take a `collection_method`, and confirmation that your
credentials carry `laboratories:write` in staging and in production.

**2. Make sure the patient record is complete**

Name, birth date, phone, email and a full home address. The order is built from the patient
record, not from the request body.

**3. Place the order**

`POST /v0.1/laboratories` with the patient id, the test ids and an `Idempotency-Key`. Add a
collection method only for tests that support more than one.

**4. Store what comes back**

`data.order_id` and `request_id`. There is no way to read the order back on this API yet.

## Before your first order

| You need | Where it comes from |
| - | - |
| A token with the `laboratories:write` permission | Your client credentials, once your OLH implementation contact has set up lab ordering for you. See *Getting started* for the token exchange. Without the permission the call returns `403` `insufficient_permissions` |
| Your organization provisioned on the platform | Your OLH implementation contact. Until it is, the call returns `403` `organization is not provisioned for this request` |
| The lab test ids you may order, per environment | Your OLH implementation contact. Staging and production ids differ, so hold them in per-environment configuration |
| Which tests support more than one collection method | Your OLH implementation contact, alongside the test ids. Leave `collection_method` out for all other tests |
| A patient in your organization | `POST /v0.1/patients`, or a patient you already hold the id of |

## Recipe · Make sure the patient record is complete

The lab order is built from the patient record at the moment you call. Every field below must be
present, or the call returns `400` listing what is missing. The birth date and postal code must also
be in the format shown, or the call returns `400` saying the patient record has fields the lab
network cannot accept. Both messages name the fields as they appear on `POST /v0.1/patients`.

| Lab order needs | Patient field (`POST /v0.1/patients`) | Notes |
| - | - | - |
| First name | `first_name` | Optional on the patient, required for a lab order. 1 to 50 characters |
| Last name | `last_name` | 1 to 50 characters |
| Date of birth | `birth_date` | Full date, `YYYY-MM-DD`, not in the future. Checked by the lab order |
| Phone | `phone` | E.164, for example `+14155550142` |
| Email | `email` | |
| Address line | `addresses[].line[0]` | The `home` address is used; if there is none, the first address |
| City | `addresses[].city` | |
| State | `addresses[].state` | Use the two-letter state code |
| Postal code | `addresses[].postal_code` | Five digits, or ZIP+4 (`12345-6789`). Checked by the lab order |
| Gender | `gender` | Optional. Sent as `unknown` when absent |

```bash curl theme={null}
curl -X POST https://api-staging.openloophealth.com/v0.1/patients \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "first_name": "Test",
    "last_name": "Labpatient",
    "birth_date": "1980-01-01",
    "gender": "male",
    "phone": "+14155550142",
    "email": "test.labpatient@example.com",
    "addresses": [{
      "use": "home",
      "line": ["100 Example St"],
      "city": "San Francisco",
      "state": "CA",
      "postal_code": "94105",
      "country": "US"
    }]
  }'
```

Keep `data.id` from the response: it is the `patient_id` you order against.

> [!WARNING]
>
> **The lab network applies its own rules to the patient record.** First and last names are limited
> to 50 characters there, while `POST /v0.1/patients` accepts up to 100. For `walk_in_test`, the
> address must be in the lab network's service area. A record that breaks either rule is rejected
> with the `400` described under *Errors* even though the patient record accepted it, and needs
> correcting before the order can be placed.

## Recipe · Place the order

```bash curl theme={null}
curl -X POST https://api-staging.openloophealth.com/v0.1/laboratories \
  -H "authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "patient_id": "<the patient id>",
    "lab_test_ids": ["<a lab test id from your implementation contact>"]
  }'
```

```json 201 theme={null}
{
  "data": {
    "order_id": "<lab order id>",
    "junction_user_id": "<the lab network id for this patient>",
    "patient_id": "<the patient id>",
    "lab_test_ids": ["<the lab test id you sent>"],
    "status": "requisition_created"
  },
  "request_id": "..."
}
```

| Field | Required | What to send |
| - | - | - |
| `patient_id` | Yes | The `id` of a patient in your organization |
| `lab_test_ids` | Send it | 1 to 20 test ids (UUIDs) from your implementation contact. If you leave it out, the order falls back to an environment default that is not chosen for your organization, or returns `400` where there is none. Always send it |
| `collection_method` | Only for multi-method tests | `walk_in_test` (patient visits a draw site), `testkit` (kit mailed to the patient), `at_home_phlebotomy`, or `on_site_collection`. Leave it out for tests with a single collection method: the lab network uses that method and rejects the order if one is sent. For a test that supports more than one, send the method you want. `null` or an empty string is the same as leaving it out |
| `activate_by` | No | `YYYY-MM-DD`, to schedule the order to activate on a later date |
| `passthrough` | No | Your own correlation string, up to 256 characters. Not returned in the response. Do not put patient information in it |

Store `data.order_id` and `request_id` together. They are what we need to find the order if you
contact us about it.

## Recipe · Retry without ordering twice

Send an `Idempotency-Key` header on every call: a UUID your client generates **once per intended
order**, stored before you send, and reused unchanged on every retry of that order.

| You send | What happens |
| - | - |
| A new key | A new order is placed |
| The same key again, for the same patient | The original order comes back with `201`. No second order is placed |
| No key, and the same patient and the same set of `lab_test_ids` (compared case-insensitively, duplicates ignored) as an earlier order placed without a key | The original order comes back with `201`. No new order is placed |
| No key, retrying an order first sent with a key | A second order is placed. A request without a key never matches one sent with a key |

So a genuinely new order for tests the patient has had before, such as a repeat panel, needs a new
key. The key is not compared against the body: never reuse one for a different order, because you
will get the first order back. Never drop the key on a retry. Either kind of match is held for two
years. Leading and trailing whitespace is trimmed from the key. A key that is then empty, or longer
than 200 characters, is not rejected: it is ignored, and the request is handled as if no key were
sent, so keep keys to 200 characters or fewer.

A `502` with `NETWORK_ERROR`, or with `PROVIDER_ERROR` and any other message, can be retried once
with the same key.

> [!WARNING]
>
> **A `502` that says an earlier request is still being processed may not clear.** If that earlier
> request is still running, the answer changes once it finishes. If the lab network did not confirm
> whether the earlier attempt placed the order, every retry under that key, or without a key for the
> same tests, keeps answering `502` and retrying does not clear it. Contact us with the `request_id`.
> Do not switch to a new key to get past it: if the earlier order was placed, a new key places a
> second one.

## Errors

Every error uses the standard envelope, `{ error: { message, error_code }, request_id }`. See
*Errors*.

| Status | `error_code` | Cause | Your move |
| - | - | - | - |
| `400` | `VALIDATION_ERROR` | The body failed validation. The message names the field | Fix the field and resend |
| `400` | `VALIDATION_ERROR` | The patient record is missing fields the lab order needs, or has a birth date or postal code the lab network cannot accept. The message lists them | Correct the patient record, then resend with the same key |
| `400` | `VALIDATION_ERROR` | `the lab provider rejected the order: check that every lab_test_id is valid for this environment and, if sent, that collection_method is supported by those tests`. Usually a test id that does not exist in this environment, or a `collection_method` sent for a single-method test or one the tests do not support. A name longer than 50 characters or a `walk_in_test` address outside the service area returns the same message | Check the test ids for this environment and the collection method, then the patient fields above. If they look right, contact us with the `request_id` |
| `401` | `UNAUTHORIZED` | The token was missing, expired or not accepted | Get a new token and resend |
| `403` | `FORBIDDEN` | `insufficient_permissions`: the token lacks `laboratories:write`. `organization is not provisioned for this request`: your organization is not set up on the platform | Contact your OLH implementation contact |
| `404` | `NOT_FOUND` | No patient with this id in your organization, or the lab network answered not found | Check the patient id. If it is right, contact us with the `request_id` |
| `502` | `PROVIDER_ERROR` or `NETWORK_ERROR` | The lab network returned an error (`PROVIDER_ERROR`), or could not be reached or did not respond in time (`NETWORK_ERROR`) | Retry once with the same `Idempotency-Key`. If it persists, contact us with the `request_id` |
| `502` | `PROVIDER_ERROR` | `a previous request for this patient is still being processed; retry later`: an earlier request for this order is still running, or the lab network did not confirm whether it placed the order | Do not switch keys. If it persists, retrying does not clear it: contact us with the `request_id` |

## What is not available yet

| Not yet available | What to do today |
| - | - |
| Reading an order back, or its status, by `order_id` | Store `order_id` from the `201`. Ask your OLH implementation contact for an order's status |
| Lab results | Results are not returned on this API yet. Agree with your OLH implementation contact how you receive them |
| A list of the lab tests you may order | Your implementation contact provides the ids per environment |
| Cancelling or changing an order | Contact your OLH implementation contact with the `order_id` |
| Requisition documents | Not available on this API yet |

## Related

> [card] [Getting started](https://openloop.mintlify.site/cookbook/getting-started.md)
>
> Hosts, credentials and the token exchange

> [card] [Integration flow](https://openloop.mintlify.site/cookbook/integration-flow.md)
>
> Creating the patient this order is placed for

> [card] [Retries and idempotency](https://openloop.mintlify.site/cookbook/retries-and-idempotency.md)
>
> How `Idempotency-Key` behaves across the API

> [card] [Errors](https://openloop.mintlify.site/cookbook/errors.md)
>
> The error envelope, `request_id`, and what each status means


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