API v1.4

Tutorial 3 of 6

Enroll a patient and order a test

Create the patient once, find them again by your own ID, and order a test battery for them.

You need a token (see Your first call) and the number of the account to work in. The examples read them from NEUROTRAX_TOKEN and NEUROTRAX_ACCOUNT.

1Enroll the patient

Create the patient with POST /v1/patients. Which fields a patient takes depends on how the account's patient form is set up: send the ones it uses, and nothing else. A field the form doesn't use is refused with 422, never dropped silently. dob is always required.

Send your own ID for the patient, such as their MRN, as unique_external_id. It is unique within the account, and lets you find the patient again without storing NeuroTrax's number.

The response gives the patient's NeuroTrax number. Use it to order tests.

curl -X POST 'https://api.neurotrax.com/v1/patients' \
  -H "Authorization: Bearer $NEUROTRAX_TOKEN" \
  -H "X-Nx-Account: $NEUROTRAX_ACCOUNT" \
  -H 'Content-Type: application/json' \
  -d '{
    "first_name": "Jane",
    "last_name": "Doe",
    "dob": "1958-04-12",
    "unique_external_id": "MRN-0048213"
  }'
import os
import requests

API = "https://api.neurotrax.com/v1"
HEADERS = {
    "Authorization": f"Bearer {os.environ['NEUROTRAX_TOKEN']}",
    "X-Nx-Account": os.environ["NEUROTRAX_ACCOUNT"],
}

response = requests.post(f"{API}/patients", headers=HEADERS, json={
    "first_name": "Jane",
    "last_name": "Doe",
    "dob": "1958-04-12",
    "unique_external_id": "MRN-0048213",
})
response.raise_for_status()
patient_number = response.json()["data"]["patient"]["number"]
print(patient_number)
// Node.js 18 or later
const API = "https://api.neurotrax.com/v1";
const headers = {
  Authorization: `Bearer ${process.env.NEUROTRAX_TOKEN}`,
  "X-Nx-Account": process.env.NEUROTRAX_ACCOUNT,
  "Content-Type": "application/json",
};

const response = await fetch(`${API}/patients`, {
  method: "POST",
  headers,
  body: JSON.stringify({ first_name: "Jane", last_name: "Doe", dob: "1958-04-12", unique_external_id: "MRN-0048213" }),
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
const patientNumber = (await response.json()).data.patient.number;
console.log(patientNumber);
// .NET 8 or later
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

using var http = new HttpClient { BaseAddress = new Uri("https://api.neurotrax.com/v1/") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("NEUROTRAX_TOKEN"));
http.DefaultRequestHeaders.Add("X-Nx-Account", Environment.GetEnvironmentVariable("NEUROTRAX_ACCOUNT"));

var response = await http.PostAsJsonAsync("patients", new
{
    first_name = "Jane",
    last_name = "Doe",
    dob = "1958-04-12",
    unique_external_id = "MRN-0048213",
});
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
var patientNumber = body.GetProperty("data").GetProperty("patient").GetProperty("number").GetString();
Console.WriteLine(patientNumber);
// Java 15 or later
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create("https://api.neurotrax.com/v1/patients"))
    .header("Authorization", "Bearer " + System.getenv("NEUROTRAX_TOKEN"))
    .header("X-Nx-Account", System.getenv("NEUROTRAX_ACCOUNT"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString("""
        {"first_name": "Jane", "last_name": "Doe", "dob": "1958-04-12", "unique_external_id": "MRN-0048213"}
        """))
    .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body()); // data.patient.number
// Go 1.21 or later
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const api = "https://api.neurotrax.com/v1"

// call sends a request with the token and account, and decodes the JSON reply into out.
func call(method, path string, body any, out any) int {
	var payload bytes.Buffer
	if body != nil {
		json.NewEncoder(&payload).Encode(body)
	}
	req, _ := http.NewRequest(method, api+path, &payload)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("NEUROTRAX_TOKEN"))
	req.Header.Set("X-Nx-Account", os.Getenv("NEUROTRAX_ACCOUNT"))
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	if out != nil {
		json.NewDecoder(res.Body).Decode(out)
	}
	return res.StatusCode
}

type patientReply struct {
	Data struct {
		Patient struct {
			Number string `json:"number"`
		} `json:"patient"`
	} `json:"data"`
}

func main() {
	var created patientReply
	status := call("POST", "/patients", map[string]any{
		"first_name": "Jane", "last_name": "Doe", "dob": "1958-04-12", "unique_external_id": "MRN-0048213",
	}, &created)
	fmt.Println(status, created.Data.Patient.Number)
}
# Ruby 3 or later
require "json"
require "net/http"

API = "https://api.neurotrax.com/v1"

# Sends a request with the token and account; returns [status, parsed body].
def call(verb, path, body = nil)
  uri = URI("#{API}#{path}")
  request = Net::HTTP.const_get(verb.capitalize).new(uri)
  request["Authorization"] = "Bearer #{ENV.fetch("NEUROTRAX_TOKEN")}"
  request["X-Nx-Account"] = ENV.fetch("NEUROTRAX_ACCOUNT")
  if body
    request.content_type = "application/json"
    request.body = body.to_json
  end
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
  [response.code.to_i, (JSON.parse(response.body) rescue nil)]
end

status, body = call("Post", "/patients", {
  first_name: "Jane", last_name: "Doe", dob: "1958-04-12", unique_external_id: "MRN-0048213"
})
patient_number = body.dig("data", "patient", "number")
puts status, patient_number
// Cargo.toml: reqwest = { version = "0.12", features = ["blocking", "json"] }, serde_json = "1"
use reqwest::blocking::{Client, RequestBuilder};
use serde_json::{json, Value};
use std::env;

const API: &str = "https://api.neurotrax.com/v1";

// Adds the token and account to a request.
fn authed(request: RequestBuilder) -> Result<RequestBuilder, Box<dyn std::error::Error>> {
    Ok(request.bearer_auth(env::var("NEUROTRAX_TOKEN")?).header("X-Nx-Account", env::var("NEUROTRAX_ACCOUNT")?))
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let created: Value = authed(client.post(format!("{API}/patients")))?
        .json(&json!({ "first_name": "Jane", "last_name": "Doe", "dob": "1958-04-12", "unique_external_id": "MRN-0048213" }))
        .send()?
        .error_for_status()?
        .json()?;
    let patient_number = created["data"]["patient"]["number"].as_str().unwrap_or_default().to_string();
    println!("{patient_number}");
    Ok(())
}

2Find a patient you enrolled before

Look a patient up by your own ID with GET /v1/patients/uextid:<your ID>, or by NeuroTrax's number with GET /v1/patients/<number>. Encode the ID if it holds characters that aren't safe in a URL.

A common pattern: look the patient up first, and enroll them only when the lookup returns 404.

curl 'https://api.neurotrax.com/v1/patients/uextid:MRN-0048213' \
  -H "Authorization: Bearer $NEUROTRAX_TOKEN" \
  -H "X-Nx-Account: $NEUROTRAX_ACCOUNT"
from urllib.parse import quote

def find_patient(mrn):
    response = requests.get(f"{API}/patients/uextid:{quote(mrn, safe='')}", headers=HEADERS)
    if response.status_code == 404:
        return None
    response.raise_for_status()
    return response.json()["data"]["patient"]

patient = find_patient("MRN-0048213")
async function findPatient(mrn) {
  const response = await fetch(`${API}/patients/uextid:${encodeURIComponent(mrn)}`, { headers });
  if (response.status === 404) return null;
  if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
  return (await response.json()).data.patient;
}

const patient = await findPatient("MRN-0048213");
async Task<JsonElement?> FindPatient(string mrn)
{
    var response = await http.GetAsync($"patients/uextid:{Uri.EscapeDataString(mrn)}");
    if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null;
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadFromJsonAsync<JsonElement>();
    return body.GetProperty("data").GetProperty("patient");
}

var patient = await FindPatient("MRN-0048213");
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

var mrn = URLEncoder.encode("MRN-0048213", StandardCharsets.UTF_8);
var lookup = HttpRequest.newBuilder(URI.create("https://api.neurotrax.com/v1/patients/uextid:" + mrn))
    .header("Authorization", "Bearer " + System.getenv("NEUROTRAX_TOKEN"))
    .header("X-Nx-Account", System.getenv("NEUROTRAX_ACCOUNT"))
    .GET()
    .build();
var found = client.send(lookup, HttpResponse.BodyHandlers.ofString());
System.out.println(found.statusCode() == 404 ? "not enrolled yet" : found.body());
// add "net/url" to the imports
var found patientReply
if call("GET", "/patients/uextid:"+url.PathEscape("MRN-0048213"), nil, &found) == http.StatusNotFound {
	fmt.Println("not enrolled yet")
} else {
	fmt.Println(found.Data.Patient.Number)
}
require "erb"

def find_patient(mrn)
  status, body = call("Get", "/patients/uextid:#{ERB::Util.url_encode(mrn)}")
  return nil if status == 404
  raise "#{status} #{body}" unless status == 200
  body.dig("data", "patient")
end

patient = find_patient("MRN-0048213")
// Cargo.toml: also urlencoding = "2"
let response = authed(client.get(format!("{API}/patients/uextid:{}", urlencoding::encode("MRN-0048213"))))?.send()?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
    println!("not enrolled yet");
} else {
    let found: Value = response.error_for_status()?.json()?;
    println!("{}", found["data"]["patient"]["number"]);
}

3Order a test

Order a test battery with POST /v1/orders: the patient's number, the battery, its language version (battery_translation_id) and the patient's years_of_education. The batteries and languages an account may order are agreed when it's set up; ask NeuroTrax which IDs to use. As with patients, any other fields depend on the account's order form.

A patient can't have more than one order waiting at a time.

curl -X POST 'https://api.neurotrax.com/v1/orders' \
  -H "Authorization: Bearer $NEUROTRAX_TOKEN" \
  -H "X-Nx-Account: $NEUROTRAX_ACCOUNT" \
  -H 'Content-Type: application/json' \
  -d '{
    "patient_number": "200001000417",
    "battery_id": 400,
    "battery_translation_id": 1,
    "years_of_education": 16
  }'
response = requests.post(f"{API}/orders", headers=HEADERS, json={
    "patient_number": patient_number,
    "battery_id": 400,
    "battery_translation_id": 1,
    "years_of_education": 16,
})
response.raise_for_status()
order = response.json()["data"]["order"]
print(order["number"], order["status"], order["launch_path"])
const ordered = await fetch(`${API}/orders`, {
  method: "POST",
  headers,
  body: JSON.stringify({ patient_number: patientNumber, battery_id: 400, battery_translation_id: 1, years_of_education: 16 }),
});
if (!ordered.ok) throw new Error(`${ordered.status} ${await ordered.text()}`);
const order = (await ordered.json()).data.order;
console.log(order.number, order.status, order.launch_path);
var ordered = await http.PostAsJsonAsync("orders", new
{
    patient_number = patientNumber,
    battery_id = 400,
    battery_translation_id = 1,
    years_of_education = 16,
});
ordered.EnsureSuccessStatusCode();
var order = (await ordered.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("data").GetProperty("order");
Console.WriteLine($"{order.GetProperty("number")} {order.GetProperty("status")} {order.GetProperty("launch_path")}");
var order = HttpRequest.newBuilder(URI.create("https://api.neurotrax.com/v1/orders"))
    .header("Authorization", "Bearer " + System.getenv("NEUROTRAX_TOKEN"))
    .header("X-Nx-Account", System.getenv("NEUROTRAX_ACCOUNT"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString("""
        {"patient_number": "200001000417", "battery_id": 400, "battery_translation_id": 1, "years_of_education": 16}
        """))
    .build();
var ordered = client.send(order, HttpResponse.BodyHandlers.ofString());
System.out.println(ordered.statusCode() + " " + ordered.body()); // data.order.number, data.order.launch_path
var ordered struct {
	Data struct {
		Order struct {
			Number     string `json:"number"`
			Status     string `json:"status"`
			LaunchPath string `json:"launch_path"`
		} `json:"order"`
	} `json:"data"`
}
status = call("POST", "/orders", map[string]any{
	"patient_number": created.Data.Patient.Number, "battery_id": 400, "battery_translation_id": 1, "years_of_education": 16,
}, &ordered)
fmt.Println(status, ordered.Data.Order.Number, ordered.Data.Order.LaunchPath)
status, body = call("Post", "/orders", {
  patient_number: patient_number, battery_id: 400, battery_translation_id: 1, years_of_education: 16
})
order = body.dig("data", "order")
puts status, order["number"], order["launch_path"]
let ordered: Value = authed(client.post(format!("{API}/orders")))?
    .json(&json!({ "patient_number": patient_number, "battery_id": 400, "battery_translation_id": 1, "years_of_education": 16 }))
    .send()?
    .error_for_status()?
    .json()?;
let order = &ordered["data"]["order"];
println!("{} {} {}", order["number"], order["status"], order["launch_path"]);

4Start the test

How the patient takes the test depends on where they are:

  • In the clinic: the order's launch_path opens its test. Open it for the clinician with a signed launch, so they arrive signed in, with no password (see Act for a clinician).
  • At home: set "telehealth": true when ordering. The response then includes a telehealth_url and a code; send both to the patient. They are the only links meant to reach a patient.

When the patient finishes, the order's status becomes completed and its results are ready (see Get results).