### Update Referral Request Body Examples Source: https://docs.staging.bloodygoodtests.com.au/api/rest Examples of JSON payloads for updating specific referral fields. ```json { "firstName": "Jane", "lastName": "Doe", "email": "jane.doe@example.com" } ``` ```json { "address": { "addressLine1": "456 New Street", "addressLine2": "Unit 3", "postCode": "2000", "city": "Sydney", "country": "Australia", "state": "NSW" } } ``` -------------------------------- ### GET /v1/bundles Source: https://docs.staging.bloodygoodtests.com.au/api/rest Retrieves a list of pre-configured test bundles. ```APIDOC ## GET /v1/bundles ### Description Retrieves pre-configured groups of tests that can be purchased together. Requires specific Accept header. ### Method GET ### Endpoint /v1/bundles ### Parameters #### Query Parameters - **count** (integer) - Optional - Number of results to return (max 20, default 20) - **cursor** (string) - Optional - Cursor for pagination - **sort** (string) - Optional - Sort order: asc or desc (default: asc) ### Response #### Success Response (200) - **cursor** (object) - Pagination cursor information - **bundles** (array) - List of available bundles #### Response Example { "cursor": { "cursor": "MjAyNC0wNi0wNFQxMjo1OTowMS44MDJafGNyZWF0ZWRBdHxhc2M=", "count": 20, "resultCount": 5 }, "bundles": [ { "id": "254fa374-6d05-4a41-bfd8-254ba2039049", "name": "Comprehensive Health Panel", "object": "bundle", "tests": [ { "id": "tft", "name": "Thyroid Function Test", "object": "test" } ], "createdAt": "2024-06-04T05:29:06.508Z" } ] } ``` -------------------------------- ### Metadata Merging Example Source: https://docs.staging.bloodygoodtests.com.au/api/rest Demonstrates how to update or remove metadata keys. ```json { "metadata": { "newKey": "new-value", "existingKey": "updated-value", "keyToRemove": null } } ``` -------------------------------- ### Referral Created Event Payload Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Example payload for the referral.created event. ```json { "eventName": "referral.created", "eventUuid": "98603d91-9d1b-4607-8ecb-705b33c66ef0", "version": "1.0", "data": { "uuid": "b69ff810-0823-41ee-8fd2-43ff01329fae", "status": "ISSUED", "issuedAt": "2025-09-17T05:35:20.942Z", "metadata": null, "createdAt": "2025-09-17T05:35:15.810Z", "reference": "DBK4EM3H", "updatedAt": "2025-09-17T05:35:20.942Z", "profileUuid": null, "organisationUuid": "dbea642f-b741-4d33-ba7b-10fd0229a961" } } ``` -------------------------------- ### Implement a secure webhook handler in Node.js Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks A complete example demonstrating signature verification, idempotency checks, and asynchronous processing. ```javascript const express = require("express"); const crypto = require("crypto"); const app = express(); // Use raw body for signature verification app.post( "/webhooks/bgt", express.raw({ type: "application/json" }), async (req, res) => { try { // Verify signature const signature = req.headers["x-bgt-hmac-sha256"]; const payload = req.body.toString(); if (!verifySignature(payload, process.env.BGT_SECRET, signature)) { return res.status(401).json({ error: "Invalid signature" }); } // Parse event const event = JSON.parse(payload); // Check for duplicates if (await isProcessed(event.eventUuid)) { return res.status(200).json({ message: "Already processed" }); } // Respond immediately res.status(200).json({ message: "Received" }); // Process asynchronously processEventAsync(event).catch(console.error); } catch (error) { console.error("Webhook error:", error); res.status(500).json({ error: "Processing failed" }); } } ); async function processEventAsync(event) { // Mark as processing await markProcessing(event.eventUuid); try { switch (event.eventName) { case "referral.created": await handleReferralCreated(event.data); break; case "result.updated": await handleResultUpdated(event.data); break; // ... other events } // Mark as complete await markComplete(event.eventUuid); } catch (error) { await markFailed(event.eventUuid, error); } } function verifySignature(payload, secret, signature) { const expected = crypto .createHmac("sha256", secret) .update(payload) .digest("hex"); return crypto.timingSafeEqual( Buffer.from(expected, "hex"), Buffer.from(signature, "hex") ); } ``` -------------------------------- ### GET /v1/results Source: https://docs.staging.bloodygoodtests.com.au/api/rest Returns all results for your organisation with pagination support. ```APIDOC ## GET /v1/results ### Description Returns all results for your organisation with pagination support. ### Method GET ### Endpoint /v1/results ### Parameters #### Query Parameters - **count** (integer) - Optional - Number of results to return (max 20, default 20) - **cursor** (string) - Optional - Cursor for pagination - **sort** (string) - Optional - Sort order: asc or desc (default: asc) ### Response #### Success Response (200) - **results** (array) - Array of results with cursor metadata ``` -------------------------------- ### List Referrals Request Source: https://docs.staging.bloodygoodtests.com.au/api/rest Use this GET request to retrieve all referrals for your organization. ```http GET /v1/referrals ``` -------------------------------- ### Result Created Event Payload Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Example payload for the result.created event. ```json { "eventName": "result.created", "eventUuid": "fd618482-7463-49dd-baa7-4289c62b0139", "version": "1.0", "data": { "uuid": "89dd5014-750c-48c2-8f39-c39a34a4a637", "status": "CREATED", "metadata": null, "createdAt": "2025-09-17T08:01:27.616Z", "updatedAt": "2025-09-17T08:01:27.641Z", "profileUuid": null, "referralUuid": "ffc14dd3-7216-4f52-900f-360733183142", "organisationUuid": "dbea642f-b741-4d33-ba7b-10fd0229a961" } } ``` -------------------------------- ### GET /v1/tests Source: https://docs.staging.bloodygoodtests.com.au/api/rest Retrieves all available blood tests for your organization. ```APIDOC ## GET /v1/tests ### Description Returns all available tests for your organisation. ### Method GET ### Endpoint /v1/tests ### Response #### Success Response (200) - **id** (string) - Test identifier - **name** (string) - Full name of the test - **shortName** (string) - Shortened name of the test - **price** (integer) - Price in cents - **object** (string) - Object type - **turnAroundTimeAverage** (object) - Average turnaround time details - **turnAroundTimes** (array) - List of provider-specific turnaround times #### Response Example [ { "id": "cortisol", "name": "Cortisol", "shortName": "Cortisol", "price": 356, "object": "test", "turnAroundTimeAverage": { "maximumDays": 7, "minimumDays": 7, "object": "turnaroundTime" }, "turnAroundTimes": [ { "maximumDays": null, "minimumDays": null, "providerId": "4cyte", "providerName": "4Cyte Pathology", "object": "providerTurnaroundTime" } ] } ] ``` -------------------------------- ### GET /v1/referrals Source: https://docs.staging.bloodygoodtests.com.au/api/rest Retrieves a list of all referrals for the organisation with support for pagination and sorting. ```APIDOC ## GET /v1/referrals ### Description Returns all referrals for your organisation with pagination support. ### Method GET ### Endpoint /v1/referrals ### Parameters #### Query Parameters - **count** (integer) - Optional - Number of results to return (max 20, default 20) - **cursor** (string) - Optional - Cursor for pagination - **sort** (string) - Optional - Sort order: asc or desc (default: asc) ### Response #### Success Response (200) - **cursor** (object) - Pagination metadata - **referrals** (array) - List of referral objects #### Response Example { "cursor": { "cursor": "MjAyNC0wNi0wNFQxMjo1OTowMS44MDJafGNyZWF0ZWRBdHxhc2M=", "count": 20, "resultCount": 5 }, "referrals": [ { "uuid": "254fa374-6d05-4a41-bfd8-254ba2039049", "status": "COMPLETE", "object": "referral", "tests": ["tft", "free-testosterone"], "metadata": { "internalId": "1234" }, "productId": "prod_abc123", "productName": "Comprehensive Health Check", "origin": "API", "person": { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "postCode": "4000", "city": "Brisbane", "state": "QLD" }, "phone": "0412345678", "dob": "1980-01-01", "gender": "male" }, "referralType": "blood", "referenceNumber": "12345678", "referralAttachment": "https://api.bloodygoodtests.com.au/download/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "emailSentAt": "2024-06-04T05:29:09.385Z", "createdAt": "2024-06-04T05:29:06.508Z", "updatedAt": "2024-06-04T05:29:09.385Z", "deletedAt": null, "resultsUuid": "d9d820a4-72e1-41bc-9fac-ffb23f18dfb4", "bulkBilled": false, "orderingPractitioner": null, "medicareCardNumber": null, "dvaNumber": null, "orderingPractitionerClinicalNotes": null } ] } ``` -------------------------------- ### Bulk-billed referral response Source: https://docs.staging.bloodygoodtests.com.au/api/rest Example of a 200 OK response when a request includes bulkBilledTests, returning an array containing both commercial and bulk-billed referral objects. ```json [ { "uuid": "254fa374-6d05-4a41-bfd8-254ba2039049", "status": "ISSUED", "object": "referral", "tests": ["free-testosterone"], "metadata": null, "productId": null, "productName": null, "origin": "API", "person": { "firstName": "Jane", "lastName": "Doe", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "456 Sample Street", "addressLine2": null, "postCode": "2000", "city": "Sydney", "country": "Australia", "state": "NSW" }, "phone": "0498765432", "dob": "1992-05-15", "gender": "female" }, "referralType": "blood", "referenceNumber": "55667788", "referralAttachment": "https://api.bloodygoodtests.com.au/download/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "emailSentAt": "2024-06-04T05:29:09.385Z", "createdAt": "2024-06-04T05:29:06.508Z", "updatedAt": "2024-06-04T05:29:09.385Z", "deletedAt": null, "resultsUuid": null, "bulkBilled": false, "orderingPractitioner": null, "medicareCardNumber": null, "dvaNumber": null, "orderingPractitionerClinicalNotes": null }, { "uuid": "9b1f3c7a-2e54-4d0b-8a61-1c2d3e4f5a6b", "status": "ISSUED", "object": "referral", "tests": ["vitamin-d", "iron-studies"], "metadata": null, "productId": null, "productName": null, "origin": "API", "person": { "firstName": "Jane", "lastName": "Doe", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "456 Sample Street", "addressLine2": null, "postCode": "2000", "city": "Sydney", "country": "Australia", "state": "NSW" }, "phone": "0498765432", "dob": "1992-05-15", "gender": "female" }, "referralType": "blood", "referenceNumber": "55667788", "referralAttachment": "https://api.bloodygoodtests.com.au/download/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "emailSentAt": "2024-06-04T05:29:09.385Z", "createdAt": "2024-06-04T05:29:06.508Z", "updatedAt": "2024-06-04T05:29:09.385Z", "deletedAt": null, "resultsUuid": null, "bulkBilled": true, "orderingPractitioner": { "name": "Dr Bill Smith", "address": "123 Example St, Sydney NSW 2000", "providerNumber": "2426621B" }, "medicareCardNumber": "1234567890", "dvaNumber": "QX123456", "orderingPractitionerClinicalNotes": "Fatigue, ?anaemia" } ] ``` -------------------------------- ### Create Referral Request Payload Source: https://docs.staging.bloodygoodtests.com.au/api/rest Example JSON payload for creating a referral that includes both commercial tests and bulk-billed Medicare tests. ```json { "firstName": "Jane", "lastName": "Doe", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "456 Sample Street", "postCode": "2000", "city": "Sydney", "country": "Australia", "state": "NSW" }, "dob": "1992-05-15", "gender": "female", "phone": "0498765432", "tests": ["free-testosterone"], "bulkBilledTests": ["vitamin-d", "iron-studies"], "orderingPractitioner": { "name": "Dr Bill Smith", "address": "123 Example St, Sydney NSW 2000", "providerNumber": "2426621B" }, "medicareCardNumber": "1234567890", "dvaNumber": "QX123456", "clinicalNotes": "Fatigue, ?anaemia", "referenceNumber": "55667788" } ``` -------------------------------- ### GET /v1/referrals/{uuid} Source: https://docs.staging.bloodygoodtests.com.au/api/rest Retrieves a specific referral by its unique identifier (UUID). ```APIDOC ## GET /v1/referrals/{uuid} ### Description Retrieves a specific referral by UUID. ### Method GET ### Endpoint /v1/referrals/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier of the referral. ### Response #### Success Response (200) - **referralAttachment** (string) - Signed URL to the referral PDF. - **updatedAt** (string) - Time the referral record was last modified. - **deletedAt** (string) - Set when the referral has been soft-deleted. - **emailSentAt** (string) - Time the referral email was dispatched. - **resultsUuid** (string) - UUID of the associated result. - **bulkBilled** (boolean) - True if issued as bulk-billed. - **orderingPractitioner** (object) - The ordering doctor details. - **medicareCardNumber** (string) - Patient's Medicare card number. - **dvaNumber** (string) - Patient's DVA file number. - **orderingPractitionerClinicalNotes** (string) - The ordering doctor's clinical notes. ``` -------------------------------- ### Webhook Signature Verification Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Guidelines and code examples for verifying the HMAC SHA256 signature of incoming webhook payloads to ensure they originate from BGT. ```APIDOC ## Webhook Signature Verification ### Description Every webhook request includes an `x-bgt-hmac-sha256` header containing an HMAC signature of the payload. You should verify this signature using your API secret key to ensure the request is authentic and has not been tampered with. ### Verification Logic - Calculate the HMAC SHA256 hash of the raw request payload using your secret key. - Compare the calculated hash with the value provided in the `x-bgt-hmac-sha256` header. - Use a constant-time comparison function (e.g., `crypto.timingSafeEqual` in Node.js or `hmac.compare_digest` in Python) to prevent timing attacks. ``` -------------------------------- ### GET /v1/results/{resultUuid} Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Retrieves the full result data, including biomarkers, for a given result UUID. ```APIDOC ## GET /v1/results/{resultUuid} ### Description Fetches the complete result details, including biomarker information, for a specific result identified by its UUID. ### Method GET ### Endpoint https://api.bloodygoodtests.com.au/v1/results/{resultUuid} ### Parameters #### Path Parameters - **resultUuid** (string) - Required - The unique identifier of the result to retrieve. ``` -------------------------------- ### Expose local server with ngrok Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Use this command to create a public HTTPS URL for your local development environment. ```bash ngrok http 3000 ``` -------------------------------- ### List Test Bundles Source: https://docs.staging.bloodygoodtests.com.au/api/rest Retrieves pre-configured groups of tests. Requires the v1.1.0+ Accept header. ```http GET /v1/bundles ``` ```http Accept: application/vnd.bgt.v1.1.0+json ``` ```json { "cursor": { "cursor": "MjAyNC0wNi0wNFQxMjo1OTowMS44MDJafGNyZWF0ZWRBdHxhc2M=", "count": 20, "resultCount": 5 }, "bundles": [ { "id": "254fa374-6d05-4a41-bfd8-254ba2039049", "name": "Comprehensive Health Panel", "object": "bundle", "tests": [ { "id": "tft", "name": "Thyroid Function Test", "object": "test" } ], "createdAt": "2024-06-04T05:29:06.508Z" } ] } ``` -------------------------------- ### Base Webhook Event Structure Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks The standard wrapper format used for all webhook events. ```json { "eventName": "event.type", "eventUuid": "unique-event-id", "version": "1.0", "data": { /* Event-specific data */ } } ``` -------------------------------- ### Simulate Referral Results (Staging Only) Source: https://docs.staging.bloodygoodtests.com.au/api/rest Generates random dummy results for a referral to test end-to-end flows. This endpoint is restricted to the staging environment. ```HTTP PUT /v1/referrals/{uuid} ``` ```HTTP PUT /v1/referrals/254fa374-6d05-4a41-bfd8-254ba2039049 PUT /v1/referrals/254fa374-6d05-4a41-bfd8-254ba2039049?partial ``` -------------------------------- ### Get Referral endpoint Source: https://docs.staging.bloodygoodtests.com.au/api/rest Endpoint definition for retrieving a specific referral record by its unique identifier. ```http GET /v1/referrals/{uuid} ``` -------------------------------- ### Create Referral with Bundle Support Source: https://docs.staging.bloodygoodtests.com.au/api/rest JSON payload for creating a referral using a bundle ID (v1.1.0). ```json { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "postCode": "4000", "city": "Brisbane", "country": "Australia", "state": "QLD" }, "dob": "1980-01-01", "gender": "male", "phone": "0412345678", "bundleId": "56ce2120-5480-4657-9e47-7ae4ecf9229b", "metadata": { "internalId": "1234" } } ``` -------------------------------- ### POST https://auth.bloodygoodtests.com.au/oauth/token (Client Credentials) Source: https://docs.staging.bloodygoodtests.com.au/api/authentication Use this flow for machine-to-machine authentication where no user is involved. ```APIDOC ## POST https://auth.bloodygoodtests.com.au/oauth/token ### Description Use this flow for machine-to-machine authentication where no user is involved. ### Method POST ### Endpoint https://auth.bloodygoodtests.com.au/oauth/token ### Request Body - **grant_type** (string) - Required - Must be 'client_credentials' - **client_id** (string) - Optional - Required if not using Basic Auth header - **client_secret** (string) - Optional - Required if not using Basic Auth header ### Response #### Success Response (200) - **access_token** (string) - The JWT access token - **refresh_token** (string) - The refresh token - **token_type** (string) - The type of token (Bearer) - **expires_in** (integer) - Expiration time in seconds - **refresh_expires_in** (integer) - Refresh token expiration time in seconds #### Response Example { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "encrypted_refresh_token", "token_type": "Bearer", "expires_in": 3600, "refresh_expires_in": 2592000 } ``` -------------------------------- ### Lipid Risk Target Biomarker Structures Source: https://docs.staging.bloodygoodtests.com.au/api/rest Examples of lipid biomarkers showing how high-risk targets are represented in additionalRanges. ```json { "refIntervalLow": null, "refIntervalHigh": 3.4, "additionalRanges": [ { "id": "high-risk", "name": "Lipid risk target", "category": "lipid-risk-target", "lowRange": null, "highRange": 2.0 } ] } ``` ```json { "refIntervalLow": 1.0, "refIntervalHigh": null, "additionalRanges": [ { "id": "high-risk", "name": "Lipid risk target", "category": "lipid-risk-target", "lowRange": 1.0, "highRange": null } ] } ``` -------------------------------- ### Verify Webhook Signatures in Python Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Uses the hmac and hashlib libraries to compute the signature and compares it using hmac.compare_digest for secure string comparison. ```python import hmac import hashlib def verify_webhook_signature(payload: bytes, secret_key: str, signature: str) -> bool: expected_signature = hmac.new( secret_key.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected_signature, signature) ``` -------------------------------- ### Female Sex Hormone Biomarker Structure Source: https://docs.staging.bloodygoodtests.com.au/api/rest Example of a biomarker structure where primary ranges are null and specific ranges are provided via additionalRanges. ```json { "refIntervalLow": null, "refIntervalHigh": null, "additionalRanges": [ { "id": "follicular", "name": "Follicular phase", "category": "female-hormone", "lowRange": 46, "highRange": 607 }, { "id": "ovulation", "name": "Ovulation", "category": "female-hormone", "lowRange": 315, "highRange": 1828 }, { "id": "luteal", "name": "Luteal phase", "category": "female-hormone", "lowRange": 161, "highRange": 774 }, { "id": "post-menopause", "name": "Post-menopausal", "category": "female-hormone", "lowRange": null, "highRange": 201 } ] } ``` -------------------------------- ### Referral Creation Success Response Source: https://docs.staging.bloodygoodtests.com.au/api/rest A successful 200 OK response returned after creating a referral, showing the structure of the returned referral object. ```json { "uuid": "254fa374-6d05-4a41-bfd8-254ba2039049", "status": "ISSUED", "object": "referral", "tests": ["tft", "free-testosterone"], "metadata": { "internalId": "1234" }, "productId": null, "productName": null, "origin": "API", "person": { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "addressLine2": null, "postCode": "4000", "city": "Brisbane", "country": "Australia", "state": "QLD" }, "phone": "0412345678", "dob": "1980-01-01", "gender": "male" }, "referralType": "blood", "referenceNumber": "12345678", "referralAttachment": "https://api.bloodygoodtests.com.au/download/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmaWxlVXVpZCI6IjJhNGRkYjALTk5MItNDUxMy1iMTAxLTMzMjBmZmYzMzAwMSIsInByb2ZpbGVVdWlkIjoiMTQxZjQ5NTgtjYzJkYi00NDY1LIwMTEtODc3MmZmZjQzMzU3IiwicmFuZG9tVmsdWUiOiJBTHJrOXNYM01iWnFXcGc4UFNRdGZmS3Fd6dGRzZ24iLCJvcmdhbmljzYXRpb25VdWlkIjoiNWQ0NDkxOTQtYzVjMS00DUzLWIyNjTQtZGRhNzg0MjdkZjllIiwiZm9y2VEb3dubG9hZCI6dHJ1ZSwiaWF0IjjoxNzc5NDI2MjExLCJleHAiOjdE3Nzk0MjcxMTF9.x7Hj2vP9aQmLZc5dRngK4tUyB1eF6oI3wJxN8sVrTYg", "emailSentAt": "2024-06-04T05:29:09.385Z", "createdAt": "2024-06-04T05:29:06.508Z", "updatedAt": "2024-06-04T05:29:09.385Z", "deletedAt": null, "resultsUuid": null, "bulkBilled": false, "orderingPractitioner": null, "medicareCardNumber": null, "dvaNumber": null, "orderingPractitionerClinicalNotes": null } ``` -------------------------------- ### PUT /v1/referrals/{uuid} Source: https://docs.staging.bloodygoodtests.com.au/api/rest Generates random dummy results for a referral to facilitate end-to-end testing. This endpoint is only available in the staging environment. ```APIDOC ## PUT /v1/referrals/{uuid} ### Description Generates a set of random dummy results for the referral, allowing you to exercise the result-related endpoints, webhooks, and your downstream handling code without involving a real pathology lab. This endpoint is only available in the staging environment. ### Method PUT ### Endpoint /v1/referrals/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier of the referral. #### Query Parameters - **partial** (flag) - Optional - If present, only a partial set of results is generated and the referral transitions to PARTIAL_RESULTS. ### Response #### Success Response (200) - **referral** (object) - The updated referral object. ``` -------------------------------- ### Set API Version via Accept Header Source: https://docs.staging.bloodygoodtests.com.au/api/rest Include the Accept header to specify the API version for the request. ```http Accept: application/vnd.bgt.v1.1.0+json ``` -------------------------------- ### Create Referral Endpoint Source: https://docs.staging.bloodygoodtests.com.au/api/rest The POST endpoint for creating a new referral. ```http POST /v1/referrals ``` -------------------------------- ### Attach Custom Metadata to Referrals Source: https://docs.staging.bloodygoodtests.com.au/api/rest Include an object with key-value pairs under the metadata property to correlate BGT records with internal systems. ```json { "metadata": { "internalId": "your-internal-id", "customField": "custom-value" } } ``` -------------------------------- ### POST /referrals Source: https://docs.staging.bloodygoodtests.com.au/api/rest Creates a new referral. Supports commercial tests via bundleId or test lists, and bulk-billed tests via bulkBilledTests. ```APIDOC ## POST /referrals ### Description Creates a new medical referral. Depending on the input, this can generate a commercial referral, a bulk-billed Medicare referral, or both. ### Request Body - **firstName** (string) - Required - Patient first name - **lastName** (string) - Required - Patient last name - **email** (string) - Required - Patient email - **address** (object) - Required - Patient address details - **dob** (string) - Required - Patient date of birth (YYYY-MM-DD) - **gender** (string) - Required - Patient gender - **phone** (string) - Required - Patient phone number - **tests** (array) - Optional - List of commercial test codes - **bundleId** (string) - Optional - ID of a pre-configured test bundle (v1.1.0+) - **bulkBilledTests** (array) - Optional - List of Medicare bulk-billed test codes - **orderingPractitioner** (object) - Required - Practitioner details including name, address, and providerNumber - **medicareCardNumber** (string) - Optional - Patient Medicare card number - **dvaNumber** (string) - Optional - Patient DVA number - **clinicalNotes** (string) - Optional - Clinical notes for the referral - **referenceNumber** (string) - Optional - External reference number ### Request Example { "firstName": "Jane", "lastName": "Doe", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "456 Sample Street", "postCode": "2000", "city": "Sydney", "country": "Australia", "state": "NSW" }, "dob": "1992-05-15", "gender": "female", "phone": "0498765432", "tests": ["free-testosterone"], "bulkBilledTests": ["vitamin-d", "iron-studies"], "orderingPractitioner": { "name": "Dr Bill Smith", "address": "123 Example St, Sydney NSW 2000", "providerNumber": "2426621B" }, "medicareCardNumber": "1234567890", "dvaNumber": "QX123456", "clinicalNotes": "Fatigue, ?anaemia", "referenceNumber": "55667788" } ``` -------------------------------- ### Client Credentials Flow Request Source: https://docs.staging.bloodygoodtests.com.au/api/authentication Initiate a machine-to-machine authentication request using the client credentials grant type. ```http POST https://auth.bloodygoodtests.com.au/oauth/token Content-Type: application/x-www-form-urlencoded Authorization: Basic base64(client_id:client_secret) ``` ```text grant_type=client_credentials ``` ```text grant_type=client_credentials &client_id=YOUR_CLIENT_ID &client_secret=YOUR_CLIENT_SECRET ``` -------------------------------- ### Verify Webhook Signatures in Node.js Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Uses the crypto module to calculate an HMAC-SHA256 signature and compares it using timingSafeEqual to mitigate timing attacks. ```javascript const crypto = require("crypto"); function verifyWebhookSignature(payload, secretKey, signature) { // Calculate expected signature const expectedSignature = crypto .createHmac("sha256", secretKey) .update(payload) .digest("hex"); // Use timingSafeEqual to prevent timing attacks return crypto.timingSafeEqual( Buffer.from(expectedSignature, "hex"), Buffer.from(signature, "hex") ); } // Usage in an Express endpoint app.post( "/webhooks/bgt", express.raw({ type: "application/json" }), (req, res) => { const signature = req.headers["x-bgt-hmac-sha256"]; const payload = req.body.toString(); if ( !verifyWebhookSignature(payload, process.env.BGT_SECRET_KEY, signature) ) { return res.status(401).send("Invalid signature"); } // Process webhook const event = JSON.parse(payload); // ... handle event ... res.status(200).send("OK"); } ); ``` -------------------------------- ### Create Referral Request Body Source: https://docs.staging.bloodygoodtests.com.au/api/rest Standard JSON payload for creating a referral. ```json { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "addressLine2": null, "postCode": "4000", "city": "Brisbane", "country": "Australia", "state": "QLD" }, "dob": "1980-01-01", "gender": "male", "phone": "0412345678", "tests": ["tft", "free-testosterone"], "metadata": { "internalId": "1234" }, "referenceNumber": "12345678", "emailReferralToCustomer": true } ``` -------------------------------- ### Authentication Success Response Source: https://docs.staging.bloodygoodtests.com.au/api/authentication Standard JSON response structure returned upon successful token acquisition. ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "encrypted_refresh_token", "token_type": "Bearer", "expires_in": 3600, "refresh_expires_in": 2592000 } ``` -------------------------------- ### Handling Webhook Idempotency Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks To ensure reliable processing, implement idempotency by tracking the `eventUuid` to prevent duplicate event handling. ```APIDOC ## Idempotency Implementation Use the `eventUuid` provided in the request body to verify if an event has already been processed. ```javascript const processedEvents = new Set(); // Or use a database app.post("/webhooks/bgt", async (req, res) => { const event = req.body; // Check if already processed if (processedEvents.has(event.eventUuid)) { return res.status(200).send("Already processed"); } // Process event await handleEvent(event); // Mark as processed processedEvents.add(event.eventUuid); res.status(200).send("OK"); }); ``` ``` -------------------------------- ### POST /v1/referrals Source: https://docs.staging.bloodygoodtests.com.au/api/rest Creates a new referral for a patient. Supports both individual tests and bundle-based orders. ```APIDOC ## POST /v1/referrals ### Description Creates a new referral for a patient. This endpoint supports creating referrals with specific tests or by using a bundle ID. ### Method POST ### Endpoint /v1/referrals ### Request Body - **firstName** (string) - Required - Patient first name - **lastName** (string) - Required - Patient last name - **email** (string) - Required - Patient email address - **address** (object) - Required - Patient address details - **dob** (string) - Required - Date of birth (YYYY-MM-DD) - **gender** (string) - Required - Patient gender - **phone** (string) - Required - Patient phone number - **tests** (array) - Optional - List of test codes - **bundleId** (string) - Optional - ID of the bundle to order - **metadata** (object) - Optional - Custom metadata - **referenceNumber** (string) - Optional - External reference number - **emailReferralToCustomer** (boolean) - Optional - Controls if BGT emails the PDF to the customer (default: true) ### Request Example { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "postCode": "4000", "city": "Brisbane", "country": "Australia", "state": "QLD" }, "dob": "1980-01-01", "gender": "male", "phone": "0412345678", "tests": ["tft", "free-testosterone"], "metadata": { "internalId": "1234" }, "referenceNumber": "12345678", "emailReferralToCustomer": true } ``` -------------------------------- ### Webhook Headers Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks The following headers are included in every webhook request to ensure security and provide metadata. ```APIDOC ## Webhook Headers | Header | Description | Example | | --- | --- | --- | | `x-bgt-hmac-sha256` | HMAC signature for payload verification | `a1b2c3d4...` | | `x-bgt-delivery-time` | Server-side timestamp of when the event was sent | `Sun, 28 Sep 2025 23:41:01 GMT` | | `Content-Type` | Always `application/json` | `application/json` | ``` -------------------------------- ### Authenticate API Requests Source: https://docs.staging.bloodygoodtests.com.au/api/rest Include the access token in the Authorization header for all requests. ```http Authorization: Bearer YOUR_ACCESS_TOKEN ``` -------------------------------- ### List Referrals Response Source: https://docs.staging.bloodygoodtests.com.au/api/rest The response returns a paginated list of referral objects containing patient and test details. ```json { "cursor": { "cursor": "MjAyNC0wNi0wNFQxMjo1OTowMS44MDJafGNyZWF0ZWRBdHxhc2M=", "count": 20, "resultCount": 5 }, "referrals": [ { "uuid": "254fa374-6d05-4a41-bfd8-254ba2039049", "status": "COMPLETE", "object": "referral", "tests": ["tft", "free-testosterone"], "metadata": { "internalId": "1234" }, "productId": "prod_abc123", "productName": "Comprehensive Health Check", "origin": "API", "person": { "firstName": "John", "lastName": "Vein", "email": "john.vein@bloodygoodtests.com.au", "address": { "addressLine1": "123 Example Way", "postCode": "4000", "city": "Brisbane", "state": "QLD" }, "phone": "0412345678", "dob": "1980-01-01", "gender": "male" }, "referralType": "blood", "referenceNumber": "12345678", "referralAttachment": "https://api.bloodygoodtests.com.au/download/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "emailSentAt": "2024-06-04T05:29:09.385Z", "createdAt": "2024-06-04T05:29:06.508Z", "updatedAt": "2024-06-04T05:29:09.385Z", "deletedAt": null, "resultsUuid": "d9d820a4-72e1-41bc-9fac-ffb23f18dfb4", "bulkBilled": false, "orderingPractitioner": null, "medicareCardNumber": null, "dvaNumber": null, "orderingPractitionerClinicalNotes": null } ] } ``` -------------------------------- ### Make an authenticated API request Source: https://docs.staging.bloodygoodtests.com.au/api/getting-started Use the access token obtained via the Client Credentials flow to authorize requests to the BGT API endpoints. ```http GET https://api.bloodygoodtests.com.au/v1/tests Authorization: Bearer YOUR_ACCESS_TOKEN ``` -------------------------------- ### Retrieve Full Result Data Source: https://docs.staging.bloodygoodtests.com.au/api/webhooks Pattern for fetching complete result details using the UUID provided in a webhook event. ```javascript async function handleResultUpdated(event) { const resultUuid = event.data.uuid; // Fetch full result data from API const response = await fetch( `https://api.bloodygoodtests.com.au/v1/results/${resultUuid}`, { headers: { Authorization: `Bearer ${accessToken}`, }, } ); const fullResult = await response.json(); // fullResult includes biomarkers array } ``` -------------------------------- ### Create Referral Source: https://docs.staging.bloodygoodtests.com.au/api/rest Creates a new medical referral. Supports bulk-billed pathology tests when specific practitioner and patient Medicare details are provided. ```APIDOC ## Create Referral ### Description Creates a new referral. Supports bulk-billed pathology tests by providing the `bulkBilledTests` field and associated practitioner/patient Medicare information. ### Request Body - **bulkBilledTests** (string[]) - Optional - Tests to order as bulk-billed (Medicare). - **orderingPractitioner** (object) - Required if bulkBilledTests is present - The ordering doctor: name, address, and providerNumber. - **medicareCardNumber** (string) - Required if bulkBilledTests is present - Patient's Medicare card number (10 digits, optionally followed by 1-digit IRN). - **dvaNumber** (string) - Optional - Patient's DVA file number. - **clinicalNotes** (string) - Optional - The ordering doctor's clinical notes for the bulk-billed referral. ### Response #### Success Response (200) - **uuid** (string) - Unique identifier for the referral. - **status** (string) - Current status of the referral (e.g., ISSUED). - **object** (string) - Type of object (referral). - **tests** (string[]) - List of tests included. - **referralAttachment** (string) - URL to download the referral document. - **bulkBilled** (boolean) - Indicates if the referral is bulk-billed. ```