Developer reference

HMS API v2

Send pathology and radiology orders from OPD and IPD, post the accepted charges in your HMS, and retrieve approved reports from DrPerfectReport.

Base URL https://api.drperfectreport.com/api/integration/v2 Auth X-Api-Key Currency INR

SwasthyaDesk hospital software integration

Use HMS API v2 to connect SwasthyaDesk to Dr Perfect Report. Once your hospital’s connection is configured, SwasthyaDesk can send OPD and IPD orders for lab tests and scans, track progress and retrieve approved report PDFs.

See how to set up the hospital connection

Quickstart

  1. Ask the lab administrator to configure your branch and tariff and issue an HmsIntegration key.
  2. Store the key in your HMS backend and load the catalogue. Use its branch, tariff revision and rates in your order.
  3. Submit one request and save the returned orderRef and itemRef values. Use them to reconcile charges, follow work and retrieve reports.

Send X-Api-Key with each HMS request and Content-Type: application/json when sending JSON. Import the OpenAPI download into Postman. Set DPR_HMS_KEY in your backend environment and use your lab's provisioned API host.

Shell · configure the API host
export DPR_API='https://api.drperfectreport.com'

Connection setup

A lab administrator with access to all branches uses a staff bearer token and an active plan with api_access. These are full API paths on https://api.drperfectreport.com.

Staff authentication header
Authorization: Bearer <staff-access-token>

Register the branch and billing mode

POST/api/hms-connections
Connection request
{
  "name": "Example Hospital",
  "branchId": "11111111-1111-4111-8111-111111111111",
  "hospitalCollectsPayment": true
}

Choose the active branch GUID from the lab's branch list (GET /api/branches?isActive=true). Connection creation returns 200 with id, name, branchId, hospitalCollectsPayment, catalogRevision and items. Keep the ID and revision. The branch and billing mode are selected at creation.

GET/api/hms-connections

Returns 200 with an array of the lab's connections, including their tariff and revision.

Set the contract tariff

PUT/api/hms-connections/{id}/catalog

Replace the entire tariff with up to 2,000 distinct entries, using the current catalogRevision. Each rate is nonnegative INR with up to two decimal places. Send items: [] to clear the tariff. Success returns the updated connection and revision.

Tariff request
{
  "catalogRevision": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
  "items": [
    {"itemType":"Test","itemId":"33333333-3333-4333-8333-333333333333","unitRate":350},
    {"itemType":"Test","itemId":"44444444-4444-4444-8444-444444444444","unitRate":900}
  ]
}

Issue and rotate the key

POST/api/api-keys
Key request
{
  "name": "Example Hospital HMS",
  "scope": "HmsIntegration",
  "hmsConnectionId": "99999999-9999-4999-8999-999999999999"
}

Returns 200 with key metadata and the one-time plainKey. Save the secret in the HMS backend. Optionally send an expiresAt UTC timestamp. List key metadata with GET /api/api-keys.

POST/api/api-keys/{id}/revoke

For rotation, issue a second key for the same connection, switch the HMS backend and confirm it works, then revoke the old key. Send { "reason": "Rotated" } or an empty JSON object. Success is 204. The connection retains its patient links and orders.

Confirm an existing patient link

PUT/api/hms-connections/{id}/patients/{externalPatientId}

Use the lab patient's GUID in patientId when staff have confirmed the match. Success is 204. If the external ID already links to a different patient, the API returns 409 patient_conflict.

Patient link request
{"patientId":"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"}
Staff permissions. ApiKey.Read lists entries. ApiKey.Create creates connections and keys and replaces tariffs. Patient linking also requires Patient.Update. ApiKey.Delete revokes keys.

OPD, IPD and billing

Use a stable externalPatientId for the hospital UHID and a stable externalEncounterId for each OPD consultation or IPD admission. All diagnostic requests under one admission use that same encounter ID and a fresh externalRequestId for each submission.

When hospitalCollectsPayment is true, the HMS issues the patient bill and controls patient report delivery. DrPerfectReport handles clinical work and internal printing. The report's QR page can verify the document and directs the patient to the hospital for the PDF. Lab patient billing and direct patient PDF delivery are disabled for these visits.

When the flag is false, the lab bills the patient and applies its own payment hold rules. Settle the hospital's commercial arrangement with the lab separately.

Post charges from the confirmation's accepted unitRate values, deduplicating by orderRef and itemRef. A profile or package is one charge and can expand into several clinical work items. HMS taxes and discounts are handled in the HMS.

Code examples

Set DPR_API to your API host and DPR_HMS_KEY to your connection key in the backend environment. Each example accepts the same commands.

CommandWhat it does
catalogPrint the first page of the branch catalogue with its revision and rates.
submitSubmit a saved order.json and print the accepted order and charges. Use the OPD or IPD example with your own references and catalogue values.
track HOSP-REQ-1042Look up the original request ID, print the work and report status, and save the first available PDF as report.pdf.

After an uncertain submission, run track with your original request ID and follow the retry guidance. Run track again when the report is ready.

C# and .NET

Create a console project with dotnet new console and replace Program.cs with this example. Run dotnet run -- catalog from that folder. Use the same syntax for the other commands.

C# · HttpClient
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

var host = Setting("DPR_API").TrimEnd('/');
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{
    BaseAddress = new Uri($"{host}/api/integration/v2/"),
    Timeout = TimeSpan.FromSeconds(30)
};
http.DefaultRequestHeaders.Add("X-Api-Key", Setting("DPR_HMS_KEY"));

switch (args.Length == 0 ? "" : args[0])
{
    case "catalog" when args.Length == 1:
        Console.WriteLine(await ReadJsonAsync("catalog"));
        break;

    case "submit" when args.Length == 1:
        var payload = await File.ReadAllTextAsync("order.json");
        Console.WriteLine(await ReadJsonAsync("orders", payload));
        break;

    case "track" when args.Length == 2:
        var requestId = Uri.EscapeDataString(args[1]);
        using (var state = JsonDocument.Parse(await ReadJsonAsync($"orders/by-external-ref/{requestId}")))
        {
            Console.WriteLine(state.RootElement.GetRawText());
            var orderRef = state.RootElement.GetProperty("order").GetProperty("orderRef").GetGuid();
            using var reports = JsonDocument.Parse(await ReadJsonAsync($"orders/{orderRef}/reports"));
            Console.WriteLine(reports.RootElement.GetRawText());
            foreach (var report in reports.RootElement.EnumerateArray())
            {
                if (report.GetProperty("availability").GetString() != "Available") continue;
                var reportId = report.GetProperty("reportId").GetGuid();
                using var pdf = await http.GetAsync($"orders/{orderRef}/reports/{reportId}/pdf");
                await EnsureSuccessAsync(pdf);
                if (pdf.Content.Headers.ContentType?.MediaType != "application/pdf")
                    throw new InvalidOperationException("Expected application/pdf.");
                await File.WriteAllBytesAsync("report.pdf", await pdf.Content.ReadAsByteArrayAsync());
                break;
            }
        }
        break;

    default:
        Console.Error.WriteLine("Use catalog, submit or track <externalRequestId>.");
        Environment.ExitCode = 2;
        break;
}

async Task<string> ReadJsonAsync(string path, string? payload = null)
{
    using var request = new HttpRequestMessage(payload is null ? HttpMethod.Get : HttpMethod.Post, path);
    if (payload is not null)
        request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
    using var response = await http.SendAsync(request);
    await EnsureSuccessAsync(response);
    return await response.Content.ReadAsStringAsync();
}

static async Task EnsureSuccessAsync(HttpResponseMessage response)
{
    if (!response.IsSuccessStatusCode)
        throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
}

static string Setting(string name) => Environment.GetEnvironmentVariable(name) is { Length: > 0 } value
    ? value : throw new InvalidOperationException($"Set {name} in the environment.");
VB.NET

Create a .NET console project with dotnet new console -lang VB and replace Program.vb with this example. Run dotnet run -- catalog from that folder.

VB.NET · HttpClient
Option Strict On
Option Infer On

Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading.Tasks

Module Program
    Function Main(args As String()) As Integer
        Try
            Return RunAsync(args).GetAwaiter().GetResult()
        Catch ex As Exception
            Console.Error.WriteLine(ex.Message)
            Return 1
        End Try
    End Function

    Private Async Function RunAsync(args As String()) As Task(Of Integer)
        Dim command = If(args.Length > 0, args(0), "")
        Dim host = Setting("DPR_API").TrimEnd("/"c)
        Using http As New HttpClient(New HttpClientHandler With {.AllowAutoRedirect = False}) With {
            .BaseAddress = New Uri($"{host}/api/integration/v2/"),
            .Timeout = TimeSpan.FromSeconds(30)
        }
            http.DefaultRequestHeaders.Add("X-Api-Key", Setting("DPR_HMS_KEY"))

            If command = "catalog" AndAlso args.Length = 1 Then
                Console.WriteLine(Await ReadJsonAsync(http, "catalog"))
            ElseIf command = "submit" AndAlso args.Length = 1 Then
                Dim payload = Await File.ReadAllTextAsync("order.json")
                Console.WriteLine(Await ReadJsonAsync(http, "orders", payload))
            ElseIf command = "track" AndAlso args.Length = 2 Then
                Await TrackAsync(http, args(1))
            Else
                Console.Error.WriteLine("Use catalog, submit or track <externalRequestId>.")
                Return 2
            End If
        End Using
        Return 0
    End Function

    Private Async Function TrackAsync(http As HttpClient, requestId As String) As Task
        Dim externalRef = Uri.EscapeDataString(requestId)
        Using state = JsonDocument.Parse(Await ReadJsonAsync(http, $"orders/by-external-ref/{externalRef}"))
            Console.WriteLine(state.RootElement.GetRawText())
            Dim orderRef = state.RootElement.GetProperty("order").GetProperty("orderRef").GetGuid()
            Dim orderPath = $"orders/{orderRef}"
            Using reports = JsonDocument.Parse(Await ReadJsonAsync(http, $"{orderPath}/reports"))
                Console.WriteLine(reports.RootElement.GetRawText())
                For Each report In reports.RootElement.EnumerateArray()
                    If report.GetProperty("availability").GetString() <> "Available" Then Continue For
                    Dim reportId = report.GetProperty("reportId").GetGuid()
                    Using pdf = Await http.GetAsync($"{orderPath}/reports/{reportId}/pdf")
                        Await EnsureSuccessAsync(pdf)
                        If pdf.Content.Headers.ContentType?.MediaType <> "application/pdf" Then
                            Throw New InvalidOperationException("Expected application/pdf.")
                        End If
                        Dim bytes = Await pdf.Content.ReadAsByteArrayAsync()
                        Await File.WriteAllBytesAsync("report.pdf", bytes)
                    End Using
                    Exit For
                Next
            End Using
        End Using
    End Function

    Private Async Function ReadJsonAsync(http As HttpClient, path As String,
                                         Optional payload As String = Nothing) As Task(Of String)
        Dim method = If(payload Is Nothing, HttpMethod.Get, HttpMethod.Post)
        Using request As New HttpRequestMessage(method, path)
            If payload IsNot Nothing Then
                request.Content = New StringContent(payload, Encoding.UTF8, "application/json")
            End If
            Using response = Await http.SendAsync(request)
                Await EnsureSuccessAsync(response)
                Return Await response.Content.ReadAsStringAsync()
            End Using
        End Using
    End Function

    Private Async Function EnsureSuccessAsync(response As HttpResponseMessage) As Task
        If Not response.IsSuccessStatusCode Then
            Dim body = Await response.Content.ReadAsStringAsync()
            Throw New HttpRequestException($"HTTP {CInt(response.StatusCode)}: {body}")
        End If
    End Function

    Private Function Setting(name As String) As String
        Dim value = Environment.GetEnvironmentVariable(name)
        If String.IsNullOrWhiteSpace(value) Then
            Throw New InvalidOperationException($"Set {name} in the environment.")
        End If
        Return value
    End Function
End Module
Node.js

Save as hms.mjs and run node hms.mjs catalog.

Node.js · Fetch
import { readFile, writeFile } from "node:fs/promises";

const { DPR_API, DPR_HMS_KEY } = process.env;
if (!DPR_API || !DPR_HMS_KEY) throw new Error("Set DPR_API and DPR_HMS_KEY in the environment.");
const base = DPR_API.replace(/\/+$/, "") + "/api/integration/v2";

async function call(path, payload) {
  const headers = { "X-Api-Key": DPR_HMS_KEY };
  if (payload !== undefined) headers["Content-Type"] = "application/json";
  const response = await fetch(`${base}/${path}`, {
    method: payload === undefined ? "GET" : "POST",
    headers,
    body: payload,
    redirect: "error",
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response;
}

const [command, requestId] = process.argv.slice(2);
if (command === "catalog") {
  const catalog = await (await call("catalog")).json();
  console.log(JSON.stringify(catalog, null, 2));
} else if (command === "submit") {
  const payload = await readFile("order.json");
  const order = await (await call("orders", payload)).json();
  console.log(JSON.stringify(order, null, 2));
} else if (command === "track" && requestId) {
  const state = await (await call(`orders/by-external-ref/${encodeURIComponent(requestId)}`)).json();
  console.log(JSON.stringify(state, null, 2));
  const orderPath = `orders/${encodeURIComponent(state.order.orderRef)}`;
  const reports = await (await call(`${orderPath}/reports`)).json();
  console.log(JSON.stringify(reports, null, 2));
  const ready = reports.find(report => report.availability === "Available");
  if (ready) {
    const pdf = await call(`${orderPath}/reports/${encodeURIComponent(ready.reportId)}/pdf`);
    if (pdf.headers.get("content-type")?.split(";")[0] !== "application/pdf") {
      throw new Error("Expected application/pdf.");
    }
    await writeFile("report.pdf", Buffer.from(await pdf.arrayBuffer()));
  }
} else {
  console.error("Use catalog, submit or track <externalRequestId>.");
  process.exitCode = 2;
}
Python

Save as hms.py and run python3 hms.py catalog. This example uses the standard library.

Python · urllib
import json
import os
import sys
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import HTTPRedirectHandler, Request, build_opener

host = os.environ["DPR_API"].rstrip("/")
key = os.environ["DPR_HMS_KEY"]
base = f"{host}/api/integration/v2"

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

http = build_opener(NoRedirect())

def call(path, payload=None):
    headers = {"X-Api-Key": key}
    if payload is not None:
        headers["Content-Type"] = "application/json"
    request = Request(f"{base}/{path}", data=payload, headers=headers)
    try:
        with http.open(request, timeout=30) as response:
            return response.headers.get_content_type(), response.read()
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        raise SystemExit(f"HTTP {error.code}: {detail}") from None

args = sys.argv[1:]
if args == ["catalog"]:
    print(json.dumps(json.loads(call("catalog")[1]), indent=2))
elif args == ["submit"]:
    payload = Path("order.json").read_bytes()
    print(json.dumps(json.loads(call("orders", payload)[1]), indent=2))
elif len(args) == 2 and args[0] == "track":
    request_id = quote(args[1], safe="")
    state = json.loads(call(f"orders/by-external-ref/{request_id}")[1])
    print(json.dumps(state, indent=2))
    order_ref = quote(state["order"]["orderRef"], safe="")
    order_path = f"orders/{order_ref}"
    reports = json.loads(call(f"{order_path}/reports")[1])
    print(json.dumps(reports, indent=2))
    ready = next((report for report in reports if report["availability"] == "Available"), None)
    if ready:
        report_id = quote(ready["reportId"], safe="")
        content_type, pdf = call(f"{order_path}/reports/{report_id}/pdf")
        if content_type != "application/pdf":
            raise SystemExit("Expected application/pdf.")
        Path("report.pdf").write_bytes(pdf)
else:
    raise SystemExit("Use catalog, submit or track <externalRequestId>.")

Catalogue

GET/catalog

The connection tariff and the branch's enabled investigations determine which items are available.

QueryMeaning
searchOptional name or code match, up to 100 characters.
modalityOptional, case-insensitive. Pathology, Ultrasound, XRay, CT or MRI. Bundles can match more than one modality.
page1–2,000, default 1.
pageSize1–100, default 50. total is the count after filtering.
curl · search by code
curl --fail-with-body "$DPR_API/api/integration/v2/catalog?search=CBC&page=1&pageSize=50" \
  -H "X-Api-Key: $DPR_HMS_KEY"
200 · application/json
{
  "branchId": "11111111-1111-4111-8111-111111111111",
  "catalogRevision": "22222222-2222-4222-8222-222222222222",
  "currency": "INR",
  "page": 1,
  "pageSize": 50,
  "total": 1,
  "items": [
    {
      "itemType": "Test",
      "itemId": "33333333-3333-4333-8333-333333333333",
      "name": "Complete Blood Count",
      "code": "CBC",
      "department": "Haematology",
      "modalities": ["Pathology"],
      "unitRate": 350
    }
  ]
}

Create an order

POST/orders
FieldHow to send it
externalRequestIdUnique request ID within this connection. Keep it for retries and reconciliation.
externalPatientId, externalEncounterIdRequired hospital UHID and consultation or admission ID.
encounterTypeRequired uppercase OPD or IPD.
branchId, catalogRevisionRequired GUIDs from your catalogue response.
items1–50 distinct entries with itemType of Test, Profile or Package, and the catalogue itemId and expectedUnitRate.
patientRequired on first use of an unlinked patient ID. Send fullName (up to 200 characters), gender (1 Male, 2 Female, 3 Other), and dateOfBirth (YYYY-MM-DD) or age (0–150). ageUnit is 1 Years (default), 2 Months or 3 Days. phone is optional.
orderingDoctor, urgencyOptional. Doctor name up to 150 characters. Urgency is 1 Routine (default), 2 Urgent or 3 Stat.
answersOptional array of up to 50 order-question answers with key and value. Use the keys supplied by the lab.

Each external reference is 1–100 ASCII characters, starts with a letter or digit, and can include dots, hyphens and underscores. The API trims and compares references in uppercase.

Mixed OPD request

This CBC and ultrasound example uses synthetic catalogue IDs. Copy IDs and prices from your connection's catalogue when submitting.

order.json
{
  "externalRequestId": "HOSP-REQ-1042",
  "externalPatientId": "UHID-07014",
  "externalEncounterId": "OPD-2026-0612",
  "encounterType": "OPD",
  "branchId": "11111111-1111-4111-8111-111111111111",
  "catalogRevision": "22222222-2222-4222-8222-222222222222",
  "patient": {
    "fullName": "Synthetic Patient",
    "gender": 2,
    "dateOfBirth": "1990-05-21"
  },
  "orderingDoctor": "Dr Example",
  "urgency": 1,
  "items": [
    {"itemType":"Test","itemId":"33333333-3333-4333-8333-333333333333","expectedUnitRate":350},
    {"itemType":"Test","itemId":"44444444-4444-4444-8444-444444444444","expectedUnitRate":900}
  ]
}
curl · create order
curl --fail-with-body "$DPR_API/api/integration/v2/orders" \
  -H "X-Api-Key: $DPR_HMS_KEY" -H 'Content-Type: application/json' \
  --data-binary @order.json
200 · application/json
{
  "orderRef": "55555555-5555-4555-8555-555555555555",
  "visitNumber": "DPR/V/2026/00354",
  "branchId": "11111111-1111-4111-8111-111111111111",
  "externalRequestId": "HOSP-REQ-1042",
  "externalPatientId": "UHID-07014",
  "externalEncounterId": "OPD-2026-0612",
  "encounterType": "OPD",
  "currency": "INR",
  "total": 1250,
  "hospitalCollectsPayment": true,
  "items": [
    {
      "itemRef": "66666666-6666-4666-8666-666666666666",
      "itemType": "Test",
      "itemId": "33333333-3333-4333-8333-333333333333",
      "name": "Complete Blood Count",
      "code": "CBC",
      "unitRate": 350
    },
    {
      "itemRef": "77777777-7777-4777-8777-777777777777",
      "itemType": "Test",
      "itemId": "44444444-4444-4444-8444-444444444444",
      "name": "Ultrasound Abdomen",
      "code": "USG-ABD",
      "unitRate": 900
    }
  ]
}
Example IPD request for a linked patient

Send the same encounter ID for further requests during this admission. Omit patient once the hospital UHID is linked to a lab patient.

IPD request body
{
  "externalRequestId": "HOSP-REQ-1043",
  "externalPatientId": "UHID-07014",
  "externalEncounterId": "ADM-2026-0031",
  "encounterType": "IPD",
  "branchId": "11111111-1111-4111-8111-111111111111",
  "catalogRevision": "22222222-2222-4222-8222-222222222222",
  "items": [
    {"itemType":"Test","itemId":"33333333-3333-4333-8333-333333333333","expectedUnitRate":350}
  ]
}

Track and reconcile an order

GET/orders/{orderRef}
GET/orders/by-external-ref/{requestId}

Both endpoints return the saved confirmation in order and current progress. Store the original HMS request ID so you can reconcile submissions before you receive the lab's orderRef.

For pathology read resultStatus and, when linked, sampleStatus. Visit-level sampleStatuses can include specimens registered before they were linked to work. For radiology read imagingStage for each investigation. workRef identifies the clinical item and billableItemRef identifies its charge.

curl · reconcile by request ID
curl --fail-with-body "$DPR_API/api/integration/v2/orders/by-external-ref/HOSP-REQ-1042" \
  -H "X-Api-Key: $DPR_HMS_KEY"
Show the 200 status response
200 · application/json
{
  "order": {
    "orderRef": "55555555-5555-4555-8555-555555555555",
    "visitNumber": "DPR/V/2026/00354",
    "branchId": "11111111-1111-4111-8111-111111111111",
    "externalRequestId": "HOSP-REQ-1042",
    "externalPatientId": "UHID-07014",
    "externalEncounterId": "OPD-2026-0612",
    "encounterType": "OPD",
    "currency": "INR",
    "total": 1250,
    "hospitalCollectsPayment": true,
    "items": [
      {
        "itemRef": "66666666-6666-4666-8666-666666666666",
        "itemType": "Test",
        "itemId": "33333333-3333-4333-8333-333333333333",
        "name": "Complete Blood Count",
        "code": "CBC",
        "unitRate": 350
      },
      {
        "itemRef": "77777777-7777-4777-8777-777777777777",
        "itemType": "Test",
        "itemId": "44444444-4444-4444-8444-444444444444",
        "name": "Ultrasound Abdomen",
        "code": "USG-ABD",
        "unitRate": 900
      }
    ]
  },
  "visitStatus": "SampleCollected",
  "sampleStatuses": ["Collected"],
  "items": [
    {
      "workRef": "66666666-6666-4666-8666-666666666666",
      "billableItemRef": "66666666-6666-4666-8666-666666666666",
      "modality": "Pathology",
      "resultStatus": "Pending",
      "imagingStage": null,
      "sampleStatus": "Collected"
    },
    {
      "workRef": "77777777-7777-4777-8777-777777777777",
      "billableItemRef": "77777777-7777-4777-8777-777777777777",
      "modality": "Ultrasound",
      "resultStatus": "Pending",
      "imagingStage": "Registered",
      "sampleStatus": null
    }
  ]
}

List and download reports

GET/orders/{orderRef}/reports

The list includes reports with a recorded approval. Clinical work can finish at different times, so continue polling pending items, including after IPD discharge. workRefs identify the clinical work covered by the PDF and itemRefs identify the related charges.

200 · application/json
[
  {
    "reportId": "88888888-8888-4888-8888-888888888888",
    "reportNumber": "DPR/RPT/2026/00068",
    "version": 1,
    "generatedAt": "2026-11-28T09:12:00Z",
    "modality": "Pathology",
    "availability": "Available",
    "workRefs": ["66666666-6666-4666-8666-666666666666"],
    "itemRefs": ["66666666-6666-4666-8666-666666666666"]
  }
]
AvailabilityHMS action
AvailableDownload and apply the billing owner's delivery rules.
PaymentHoldWait for the lab to release the report under its payment policy.
AwaitingReissueWait for the lab to approve an updated report.
Superseded, WithdrawnStop serving the old copy and look for a new available report.
PdfUnavailableContact the lab if an approved PDF remains unavailable.
GET/orders/{orderRef}/reports/{reportId}/pdf

200 streams application/pdf. Check the current listing before serving cached copies. A held report returns 402, an unavailable version returns 409, and an unknown report or order returns 404.

curl · download an available PDF
curl --fail "$DPR_API/api/integration/v2/orders/55555555-5555-4555-8555-555555555555/reports/88888888-8888-4888-8888-888888888888/pdf" \
  -H "X-Api-Key: $DPR_HMS_KEY" --output report.pdf

Cancel a billable item

POST/orders/{orderRef}/items/{itemRef}/cancel

Use the confirmation's itemRef. Send a reason of up to 250 characters. Repeat cancellation requests are safe. Started, outsourced or already lab-invoiced work returns 409 cancellation_review_required.

curl · cancel a charge item
curl --fail-with-body "$DPR_API/api/integration/v2/orders/55555555-5555-4555-8555-555555555555/items/77777777-7777-4777-8777-777777777777/cancel" \
  -H "X-Api-Key: $DPR_HMS_KEY" -H 'Content-Type: application/json' \
  --data '{"reason":"Clinician cancelled the request"}'
200 · application/json
{"itemRef":"77777777-7777-4777-8777-777777777777","status":"Cancelled"}

After confirmation, reconcile the charge through your HMS credit or refund workflow.

Errors and retries

HMS domain errors include code and message. Invalid JSON or model fields may return validation problem details. Authentication failures can have an empty body.

HTTPRecovery
400Correct the request. Check invalid_query, invalid_branch, invalid_order, patient_details_required or item_unavailable.
401Check the backend key or staff token for missing, invalid, expired or revoked credentials.
402payment_hold. The lab must settle or release the report.
403Check the connection key scope, staff permissions and api_access entitlement.
404Check the order, item or report ID for this connection. After an uncertain submission, look up the original request ID.
409Resolve catalog_changed, request_conflict, encounter_conflict, patient_conflict, patient_link_required, report_unavailable or cancellation_review_required.
503retry_later. Reconcile and retry the saved payload with backoff if absent.
Save the payload before sending it. After a timeout, look up the original request ID and resend the same payload with that ID if the order is absent. An accepted order returns the original confirmation on replay. Changing an already accepted request returns 409 request_conflict. After a confirmed catalog_changed rejection, refresh the catalogue and reconfirm the amount before submitting.

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.