Tutorial 2 of 6
Your first call
Prove it's you with your key, get a token, and list the accounts you can work in.
You need your client ID, from NeuroTrax, and the key from Set up your key.
1Sign a one-time pass
To get a token, your integration signs a one-time pass with its private key. NeuroTrax checks it against your public key, so it knows the request is yours. A pass works once, for at most five minutes, so sign a new one each time.
Put your values at the top of this helper; the later tutorials use it too.
import os
import time
import uuid
import jwt
import requests
CLIENT_ID = "your-client-id" # NeuroTrax gives you this
KEY_NAME = "acme-2026-10" # the name you gave your key
KEY_FILE = "neurotrax-private.pem" # your private key file
TOKEN_URL = "https://api.neurotrax.com/oauth/token"
with open(KEY_FILE) as f:
PRIVATE_KEY = f.read()
def signed(claims):
now = int(time.time())
return jwt.encode({**claims, "iat": now, "exp": now + 240, "jti": str(uuid.uuid4())},
PRIVATE_KEY, algorithm="RS384", headers={"kid": KEY_NAME, "typ": "JWT"})
// Node.js 18 or later
import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { SignJWT, importPKCS8 } from "jose";
const CLIENT_ID = "your-client-id"; // NeuroTrax gives you this
const KEY_NAME = "acme-2026-10"; // the name you gave your key
const KEY_FILE = "neurotrax-private.pem"; // your private key file
const TOKEN_URL = "https://api.neurotrax.com/oauth/token";
const privateKey = await importPKCS8(await readFile(KEY_FILE, "utf8"), "RS384");
const signed = (claims) => new SignJWT(claims)
.setProtectedHeader({ alg: "RS384", kid: KEY_NAME, typ: "JWT" })
.setIssuedAt()
.setExpirationTime("4m")
.setJti(randomUUID())
.sign(privateKey);
// .NET 8 or later; package Microsoft.IdentityModel.JsonWebTokens
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
var clientId = "your-client-id"; // NeuroTrax gives you this
var keyName = "acme-2026-10"; // the name you gave your key
var keyFile = "neurotrax-private.pem"; // your private key file
const string TokenUrl = "https://api.neurotrax.com/oauth/token";
var rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText(keyFile));
var signing = new SigningCredentials(new RsaSecurityKey(rsa) { KeyId = keyName }, SecurityAlgorithms.RsaSha384);
string Signed(string subject, string audience, IDictionary<string, object>? extra = null)
{
var claims = new Dictionary<string, object> { ["sub"] = subject, ["jti"] = Guid.NewGuid().ToString() };
foreach (var (key, value) in extra ?? new Dictionary<string, object>()) claims[key] = value;
return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
Issuer = clientId, Audience = audience, Claims = claims, TokenType = "JWT",
Expires = DateTime.UtcNow.AddMinutes(4), SigningCredentials = signing,
});
}
// Java 15 or later; library com.nimbusds:nimbus-jose-jwt
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
import java.util.UUID;
var clientId = "your-client-id"; // NeuroTrax gives you this
var keyName = "acme-2026-10"; // the name you gave your key
var keyFile = "neurotrax-private.pem"; // your private key file
var tokenUrl = "https://api.neurotrax.com/oauth/token";
var privateKey = ((RSAKey) JWK.parseFromPEMEncodedObjects(Files.readString(Path.of(keyFile)))).toRSAPrivateKey();
var header = new JWSHeader.Builder(JWSAlgorithm.RS384).keyID(keyName).type(JOSEObjectType.JWT).build();
// Signs a one-time pass that works for four minutes.
String signed(String subject, String audience, java.util.Map<String, Object> extra) throws Exception {
var claims = new JWTClaimsSet.Builder()
.issuer(clientId).subject(subject).audience(audience)
.expirationTime(new Date(System.currentTimeMillis() + 240_000))
.jwtID(UUID.randomUUID().toString());
extra.forEach(claims::claim);
var jwt = new SignedJWT(header, claims.build());
jwt.sign(new RSASSASigner(privateKey));
return jwt.serialize();
}
// Go 1.21 or later; go get github.com/golang-jwt/jwt/v5
package main
import (
"crypto/rand"
"crypto/rsa"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
clientID = "your-client-id" // NeuroTrax gives you this
keyName = "acme-2026-10" // the name you gave your key
keyFile = "neurotrax-private.pem" // your private key file
tokenURL = "https://api.neurotrax.com/oauth/token"
)
var privateKey = loadKey(keyFile)
func loadKey(path string) *rsa.PrivateKey {
raw, err := os.ReadFile(path)
if err != nil {
panic(err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(raw)
if err != nil {
panic(err)
}
return key
}
// signed signs claims for one use: RS384, your kid, typ JWT, four minutes, a fresh jti.
func signed(claims jwt.MapClaims) string {
id := make([]byte, 16)
rand.Read(id)
now := time.Now()
claims["iat"], claims["exp"], claims["jti"] = now.Unix(), now.Add(4*time.Minute).Unix(), hex.EncodeToString(id)
token := jwt.NewWithClaims(jwt.SigningMethodRS384, claims) // the header has typ JWT already
token.Header["kid"] = keyName
out, err := token.SignedString(privateKey)
if err != nil {
panic(err)
}
return out
}
# Ruby 3 or later; gem install jwt
require "json"
require "jwt"
require "net/http"
require "securerandom"
CLIENT_ID = "your-client-id" # NeuroTrax gives you this
KEY_NAME = "acme-2026-10" # the name you gave your key
KEY_FILE = "neurotrax-private.pem" # your private key file
TOKEN_URL = "https://api.neurotrax.com/oauth/token"
PRIVATE_KEY = OpenSSL::PKey::RSA.new(File.read(KEY_FILE))
def signed(claims)
now = Time.now.to_i
JWT.encode(claims.merge(iat: now, exp: now + 240, jti: SecureRandom.uuid),
PRIVATE_KEY, "RS384", { kid: KEY_NAME, typ: "JWT" })
end
// Cargo.toml: jsonwebtoken = "9", reqwest = { version = "0.12", features = ["blocking", "json"] },
// serde_json = "1", uuid = { version = "1", features = ["v4"] }
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde_json::{json, Value};
use std::time::{SystemTime, UNIX_EPOCH};
const CLIENT_ID: &str = "your-client-id"; // NeuroTrax gives you this
const KEY_NAME: &str = "acme-2026-10"; // the name you gave your key
const KEY_FILE: &str = "neurotrax-private.pem"; // your private key file
const TOKEN_URL: &str = "https://api.neurotrax.com/oauth/token";
// Signs a one-time pass that works for four minutes.
fn signed(mut claims: Value) -> Result<String, Box<dyn std::error::Error>> {
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
claims["iat"] = json!(now);
claims["exp"] = json!(now + 240);
claims["jti"] = json!(uuid::Uuid::new_v4().to_string());
let mut header = Header::new(Algorithm::RS384); // typ JWT by default
header.kid = Some(KEY_NAME.into());
let key = EncodingKey::from_rsa_pem(&std::fs::read(KEY_FILE)?)?;
Ok(encode(&header, &claims, &key)?)
}
2Create a token
Post the pass to POST /oauth/token with grant_type=client_credentials. You get back an access token, how many seconds it lasts (an hour), and the scopes it carries. Your integration acts as its own API user: no person signs in.
# Sign the assertion in your language (see the other tabs), then:
curl -X POST 'https://api.neurotrax.com/oauth/token' \
-d grant_type=client_credentials \
-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
-d "client_assertion=$CLIENT_ASSERTION"
response = requests.post(TOKEN_URL, data={
"grant_type": "client_credentials",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": signed({"iss": CLIENT_ID, "sub": CLIENT_ID, "aud": TOKEN_URL}),
})
response.raise_for_status()
token = response.json()
print(token["expires_in"], token["scope"])
const response = await fetch(TOKEN_URL, {
method: "POST",
body: new URLSearchParams({
grant_type: "client_credentials",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: await signed({ iss: CLIENT_ID, sub: CLIENT_ID, aud: TOKEN_URL }),
}),
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
const token = await response.json();
console.log(token.expires_in, token.scope);
using var http = new HttpClient();
var response = await http.PostAsync(TokenUrl, new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
["client_assertion"] = Signed(clientId, TokenUrl),
}));
response.EnsureSuccessStatusCode();
var token = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine($"{token.GetProperty("expires_in")} {token.GetProperty("scope")}");
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
var client = HttpClient.newHttpClient();
var form = "grant_type=client_credentials"
+ "&client_assertion_type=" + URLEncoder.encode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer", StandardCharsets.UTF_8)
+ "&client_assertion=" + signed(clientId, tokenUrl, java.util.Map.of());
var request = HttpRequest.newBuilder(URI.create(tokenUrl))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body()); // {"access_token":"...","token_type":"Bearer","expires_in":3600,...}
// In main:
res, err := http.PostForm(tokenURL, url.Values{
"grant_type": {"client_credentials"},
"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
"client_assertion": {signed(jwt.MapClaims{"iss": clientID, "sub": clientID, "aud": tokenURL})},
})
if err != nil {
panic(err)
}
defer res.Body.Close()
var token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
json.NewDecoder(res.Body).Decode(&token)
fmt.Println(res.Status, token.ExpiresIn, token.Scope)
response = Net::HTTP.post_form(URI(TOKEN_URL),
"grant_type" => "client_credentials",
"client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion" => signed(iss: CLIENT_ID, sub: CLIENT_ID, aud: TOKEN_URL))
response.value # raises unless the call succeeded
token = JSON.parse(response.body)
puts token["expires_in"], token["scope"]
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client_id = CLIENT_ID;
let client = reqwest::blocking::Client::new();
let assertion = signed(json!({ "iss": client_id, "sub": client_id, "aud": TOKEN_URL }))?;
let token: Value = client
.post(TOKEN_URL)
.form(&[
("grant_type", "client_credentials"),
("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
("client_assertion", assertion.as_str()),
])
.send()?
.error_for_status()?
.json()?;
println!("{} {}", token["expires_in"], token["scope"]);
Ok(())
}
3List your accounts
Call GET /v1/accounts with the token. You get every account your integration may work in, with its number, name and status. A master account comes with its sub_accounts; you work in the sub-accounts, not in the master account itself.
The number is what you send in the X-Nx-Account header on every call about patients and orders.
export NEUROTRAX_TOKEN="the access_token from the previous step"
curl 'https://api.neurotrax.com/v1/accounts' \
-H "Authorization: Bearer $NEUROTRAX_TOKEN"
response = requests.get(
"https://api.neurotrax.com/v1/accounts",
headers={"Authorization": f"Bearer {token['access_token']}"},
)
response.raise_for_status()
for account in response.json()["data"]["accounts"]:
print(account["number"], account["name"], account["status"])
for sub in account.get("sub_accounts", []):
print(" ", sub["number"], sub["name"], sub["status"])
const accounts = await fetch("https://api.neurotrax.com/v1/accounts", {
headers: { Authorization: `Bearer ${token.access_token}` },
});
if (!accounts.ok) throw new Error(`${accounts.status} ${await accounts.text()}`);
for (const account of (await accounts.json()).data.accounts) {
console.log(account.number, account.name, account.status);
for (const sub of account.sub_accounts ?? []) console.log(" ", sub.number, sub.name, sub.status);
}
var list = new HttpRequestMessage(HttpMethod.Get, "https://api.neurotrax.com/v1/accounts");
list.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.GetProperty("access_token").GetString());
var accounts = await http.SendAsync(list);
accounts.EnsureSuccessStatusCode();
var body = await accounts.Content.ReadFromJsonAsync<JsonElement>();
foreach (var account in body.GetProperty("data").GetProperty("accounts").EnumerateArray())
Console.WriteLine($"{account.GetProperty("number")} {account.GetProperty("name")} {account.GetProperty("status")}");
// accessToken: the "access_token" from the previous step, read with your JSON library
var list = HttpRequest.newBuilder(URI.create("https://api.neurotrax.com/v1/accounts"))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
var accounts = client.send(list, HttpResponse.BodyHandlers.ofString());
System.out.println(accounts.statusCode() + " " + accounts.body());
req, _ := http.NewRequest("GET", "https://api.neurotrax.com/v1/accounts", nil)
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
listed, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer listed.Body.Close()
type account struct{ Number, Name, Status string }
var body struct {
Data struct {
Accounts []struct {
account
SubAccounts []account `json:"sub_accounts"`
}
}
}
json.NewDecoder(listed.Body).Decode(&body)
for _, a := range body.Data.Accounts {
fmt.Println(a.Number, a.Name, a.Status)
for _, sub := range a.SubAccounts {
fmt.Println(" ", sub.Number, sub.Name, sub.Status)
}
}
uri = URI("https://api.neurotrax.com/v1/accounts")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{token["access_token"]}"
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
response.value
JSON.parse(response.body)["data"]["accounts"].each do |account|
puts [account["number"], account["name"], account["status"]].join(" ")
account.fetch("sub_accounts", []).each { |sub| puts " #{sub["number"]} #{sub["name"]} #{sub["status"]}" }
end
let accounts: Value = client
.get("https://api.neurotrax.com/v1/accounts")
.bearer_auth(token["access_token"].as_str().unwrap_or_default())
.send()?
.error_for_status()?
.json()?;
for account in accounts["data"]["accounts"].as_array().into_iter().flatten() {
println!("{} {} {}", account["number"], account["name"], account["status"]);
for sub in account["sub_accounts"].as_array().into_iter().flatten() {
println!(" {} {} {}", sub["number"], sub["name"], sub["status"]);
}
}
4Reuse the token
A token works for an hour. Keep it and reuse it for every call; ask for a new one shortly before it expires, not once per call. Requests for tokens are limited per address, and a fresh token per call wastes both sides' time.
A small helper does it: keep the token and its expiry time, and fetch a new one a minute early.
_token = {"value": None, "expires_at": 0}
def access_token():
if time.time() > _token["expires_at"] - 60:
response = requests.post(TOKEN_URL, data={
"grant_type": "client_credentials",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": signed({"iss": CLIENT_ID, "sub": CLIENT_ID, "aud": TOKEN_URL}),
})
response.raise_for_status()
body = response.json()
_token.update(value=body["access_token"], expires_at=time.time() + body["expires_in"])
return _token["value"]
let cached = { value: null, expiresAt: 0 };
async function accessToken() {
if (Date.now() > cached.expiresAt - 60_000) {
const response = await fetch(TOKEN_URL, {
method: "POST",
body: new URLSearchParams({
grant_type: "client_credentials",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: await signed({ iss: CLIENT_ID, sub: CLIENT_ID, aud: TOKEN_URL }),
}),
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
const body = await response.json();
cached = { value: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
}
return cached.value;
}
string? cachedToken = null;
var expiresAt = DateTimeOffset.MinValue;
async Task<string> AccessToken()
{
if (cachedToken is null || DateTimeOffset.UtcNow > expiresAt.AddMinutes(-1))
{
var response = await http.PostAsync(TokenUrl, new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
["client_assertion"] = Signed(clientId, TokenUrl),
}));
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
cachedToken = body.GetProperty("access_token").GetString();
expiresAt = DateTimeOffset.UtcNow.AddSeconds(body.GetProperty("expires_in").GetInt32());
}
return cachedToken!;
}
// Keeps the token and fetches a new one a minute before it expires.
// Parse the JSON with the library you already use (Jackson shown).
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
String cachedToken;
Instant expiresAt = Instant.EPOCH;
synchronized String accessToken() throws Exception {
if (Instant.now().isAfter(expiresAt.minusSeconds(60))) {
var form = "grant_type=client_credentials"
+ "&client_assertion_type=" + URLEncoder.encode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer", StandardCharsets.UTF_8)
+ "&client_assertion=" + signed(clientId, tokenUrl, java.util.Map.of());
var request = HttpRequest.newBuilder(URI.create(tokenUrl))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
var body = new ObjectMapper().readTree(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
cachedToken = body.get("access_token").asText();
expiresAt = Instant.now().plusSeconds(body.get("expires_in").asLong());
}
return cachedToken;
}
var cached struct {
value string
expiresAt time.Time
}
// accessToken keeps the token and fetches a new one a minute before it expires.
func accessToken() string {
if time.Now().After(cached.expiresAt.Add(-time.Minute)) {
res, err := http.PostForm(tokenURL, url.Values{
"grant_type": {"client_credentials"},
"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
"client_assertion": {signed(jwt.MapClaims{"iss": clientID, "sub": clientID, "aud": tokenURL})},
})
if err != nil {
panic(err)
}
defer res.Body.Close()
var body struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
json.NewDecoder(res.Body).Decode(&body)
cached.value, cached.expiresAt = body.AccessToken, time.Now().Add(time.Duration(body.ExpiresIn)*time.Second)
}
return cached.value
}
def access_token
if @token.nil? || Time.now > @expires_at - 60
response = Net::HTTP.post_form(URI(TOKEN_URL),
"grant_type" => "client_credentials",
"client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion" => signed(iss: CLIENT_ID, sub: CLIENT_ID, aud: TOKEN_URL))
response.value
body = JSON.parse(response.body)
@token, @expires_at = body["access_token"], Time.now + body["expires_in"]
end
@token
end
use std::time::{Duration, Instant};
// Keeps the token and fetches a new one a minute before it expires.
struct TokenCache {
value: String,
expires_at: Instant,
}
impl TokenCache {
fn get(&mut self, client: &reqwest::blocking::Client, client_id: &str) -> Result<String, Box<dyn std::error::Error>> {
if self.value.is_empty() || Instant::now() + Duration::from_secs(60) > self.expires_at {
let assertion = signed(json!({ "iss": client_id, "sub": client_id, "aud": TOKEN_URL }))?;
let body: Value = client
.post(TOKEN_URL)
.form(&[
("grant_type", "client_credentials"),
("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
("client_assertion", assertion.as_str()),
])
.send()?
.error_for_status()?
.json()?;
self.value = body["access_token"].as_str().unwrap_or_default().to_string();
self.expires_at = Instant::now() + Duration::from_secs(body["expires_in"].as_u64().unwrap_or(0));
}
Ok(self.value.clone())
}
}