Examples Documentation

Code Examples

Welcome to the Nuxera API Code Examples. This section provides ready-to-use code snippets and sample applications to help you integrate Nuxera's healthcare AI capabilities into your applications.

Available Examples

Here you'll find examples for various use cases and programming languages:

JavaScript/TypeScript Examples

Authentication

Basic Token Authentication (Node.js)

const axios = require('axios');

async function getAccessToken() {
  try {
    const response = await axios.post('https://api.nuxera.ai/v1/auth/token', {
      client_id: 'YOUR_CLIENT_ID',
      client_secret: 'YOUR_CLIENT_SECRET',
    });

    const { access_token, expires_in, token_type } = response.data;
    console.log(`Token acquired! Expires in ${expires_in} seconds`);

    return access_token;
  } catch (error) {
    console.error(
      'Authentication error:',
      error.response?.data || error.message
    );
    throw error;
  }
}

// Usage
getAccessToken().then((token) => {
  console.log('Access token:', token);
});

Token Management with Auto-Refresh (TypeScript)

import axios from 'axios';

interface TokenResponse {
  access_token: string;
  expires_in: number;
  token_type: string;
}

class TokenManager {
  private accessToken: string | null = null;
  private expiresAt: Date | null = null;
  private readonly clientId: string;
  private readonly clientSecret: string;

  constructor(clientId: string, clientSecret: string) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
  }

  async getToken(): Promise<string> {
    // If token exists and is still valid (with 30s buffer)
    if (
      this.accessToken &&
      this.expiresAt &&
      this.expiresAt > new Date(Date.now() + 30000)
    ) {
      return this.accessToken;
    }

    // Otherwise, get a new token
    return this.refreshToken();
  }

  private async refreshToken(): Promise<string> {
    try {
      const response = await axios.post<TokenResponse>(
        'https://api.nuxera.ai/v1/auth/token',
        {
          client_id: this.clientId,
          client_secret: this.clientSecret,
        }
      );

      const { access_token, expires_in } = response.data;
      this.accessToken = access_token;
      this.expiresAt = new Date(Date.now() + expires_in * 1000);

      return access_token;
    } catch (error) {
      console.error('Token refresh failed:', error);
      throw error;
    }
  }
}

// Usage
const tokenManager = new TokenManager('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');

async function makeAuthenticatedRequest() {
  const token = await tokenManager.getToken();
  // Use token for API calls...
}

Transcription Examples

Basic Transcription Request (Browser JavaScript)

async function transcribeAudio(audioBlob) {
  try {
    const token = await getAccessToken(); // Get your authentication token

    const formData = new FormData();
    formData.append('audio', audioBlob);
    formData.append('language', 'en-US');

    const response = await fetch('https://api.nuxera.ai/v1/transcription', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
    });

    if (!response.ok) {
      throw new Error(
        `Transcription failed: ${response.status} ${response.statusText}`
      );
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('Transcription error:', error);
    throw error;
  }
}

// Usage with a file input
document
  .getElementById('audioFileInput')
  .addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const result = await transcribeAudio(file);
        displayTranscription(result.transcription);
        displayStructuredData(result.structured_data);
      } catch (error) {
        showErrorMessage('Transcription failed. Please try again.');
      }
    }
  });

function displayTranscription(text) {
  document.getElementById('transcriptionResult').textContent = text;
}

function displayStructuredData(data) {
  // Handle structured data like ICD-10 codes, medications, etc.
  const container = document.getElementById('structuredDataContainer');
  container.innerHTML = '';

  if (data.icd10_codes && data.icd10_codes.length > 0) {
    const codesSection = document.createElement('div');
    codesSection.innerHTML = `<h3>ICD-10 Codes</h3>
      <ul>${data.icd10_codes
        .map((code) => `<li>${code.code}: ${code.description}</li>`)
        .join('')}</ul>`;
    container.appendChild(codesSection);
  }

  // Similar handling for medications, procedures, etc.
}

Streaming Transcription (React.js)

import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';

function StreamingTranscriptionComponent() {
  const [isRecording, setIsRecording] = useState(false);
  const [transcription, setTranscription] = useState('');
  const [finalTranscription, setFinalTranscription] = useState('');
  const mediaRecorderRef = useRef(null);
  const socketRef = useRef(null);
  const accessTokenRef = useRef(null);

  // Get access token on component mount
  useEffect(() => {
    async function getToken() {
      try {
        const response = await axios.post(
          'https://api.nuxera.ai/v1/auth/token',
          {
            client_id: 'YOUR_CLIENT_ID',
            client_secret: 'YOUR_CLIENT_SECRET',
          }
        );
        accessTokenRef.current = response.data.access_token;
      } catch (error) {
        console.error('Failed to get access token:', error);
      }
    }

    getToken();

    // Cleanup on unmount
    return () => {
      if (socketRef.current) {
        socketRef.current.close();
      }
      if (mediaRecorderRef.current) {
        mediaRecorderRef.current.stop();
      }
    };
  }, []);

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

      // Set up WebSocket connection
      socketRef.current = new WebSocket(
        'wss://api.nuxera.ai/v1/streaming-transcription'
      );

      socketRef.current.onopen = () => {
        // Send authentication message
        socketRef.current.send(
          JSON.stringify({
            type: 'auth',
            token: accessTokenRef.current,
          })
        );
      };

      socketRef.current.onmessage = (event) => {
        const data = JSON.parse(event.data);

        if (data.type === 'partial_transcription') {
          setTranscription(data.text);
        } else if (data.type === 'final_transcription') {
          setFinalTranscription((prev) => prev + ' ' + data.text);
          setTranscription('');
        }
      };

      socketRef.current.onerror = (error) => {
        console.error('WebSocket error:', error);
      };

      // Set up media recorder
      const recorder = new MediaRecorder(stream);
      mediaRecorderRef.current = recorder;

      recorder.ondataavailable = (event) => {
        if (
          event.data.size > 0 &&
          socketRef.current?.readyState === WebSocket.OPEN
        ) {
          socketRef.current.send(event.data);
        }
      };

      recorder.start(250); // Send audio chunks every 250ms
      setIsRecording(true);
    } catch (error) {
      console.error('Error starting recording:', error);
    }
  };

  const stopRecording = () => {
    if (mediaRecorderRef.current) {
      mediaRecorderRef.current.stop();
      mediaRecorderRef.current = null;
    }

    if (socketRef.current) {
      // Send end of stream message
      socketRef.current.send(
        JSON.stringify({
          type: 'end',
        })
      );
      socketRef.current.close();
      socketRef.current = null;
    }

    setIsRecording(false);
  };

  return (
    <div className="streaming-transcription">
      <div className="transcription-results">
        <div className="final-transcription">{finalTranscription}</div>
        <div className="partial-transcription">{transcription}</div>
      </div>

      <div className="controls">
        {!isRecording ? (
          <button onClick={startRecording}>Start Recording</button>
        ) : (
          <button onClick={stopRecording}>Stop Recording</button>
        )}
      </div>
    </div>
  );
}

export default StreamingTranscriptionComponent;

Dictation Examples

Medical Dictation with Patient Context (JavaScript)

async function submitDictation(audioBlob, patientInfo, encounterInfo) {
  const token = await getAccessToken(); // Your token retrieval function

  const formData = new FormData();
  formData.append('audio', audioBlob);
  formData.append('patient_id', patientInfo.id);
  formData.append('provider_id', encounterInfo.providerId);
  formData.append('encounter_type', encounterInfo.type);
  formData.append('medical_specialty', encounterInfo.specialty);

  // Optional context to improve accuracy
  if (patientInfo.age) formData.append('patient_age', patientInfo.age);
  if (patientInfo.gender) formData.append('patient_gender', patientInfo.gender);
  if (encounterInfo.reason)
    formData.append('visit_reason', encounterInfo.reason);

  try {
    const response = await fetch('https://api.nuxera.ai/v1/dictation', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`Dictation failed: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Dictation submission error:', error);
    throw error;
  }
}

// Example usage
const patientData = {
  id: 'PATIENT12345',
  age: 45,
  gender: 'female',
};

const encounterData = {
  providerId: 'PROVIDER789',
  type: 'follow_up',
  specialty: 'cardiology',
  reason: 'Chest pain follow-up',
};

// When dictation recording is complete:
submitDictation(audioBlobFromRecording, patientData, encounterData)
  .then((result) => {
    console.log('Dictation processed successfully');
    console.log('Dictation text:', result.dictation_text);
    console.log('Structured data:', result.structured_data);

    // Save to EHR or display for review
    saveToEHR(result);
  })
  .catch((error) => {
    console.error('Failed to process dictation:', error);
    // Show error to user
  });

Python Examples

Authentication in Python

import requests

def get_access_token(client_id, client_secret):
    """
    Authenticate with the Nuxera API and get an access token.

    Args:
        client_id (str): Your API client ID
        client_secret (str): Your API client secret

    Returns:
        str: Access token if successful

    Raises:
        Exception: If authentication fails
    """
    url = "https://api.nuxera.ai/v1/auth/token"
    payload = {
        "client_id": client_id,
        "client_secret": client_secret
    }

    try:
        response = requests.post(url, json=payload)
        response.raise_for_status()  # Raise exception for 4XX/5XX responses

        token_data = response.json()
        return token_data["access_token"]
    except requests.exceptions.RequestException as e:
        print(f"Authentication error: {e}")
        raise

# Usage
if __name__ == "__main__":
    client_id = "YOUR_CLIENT_ID"
    client_secret = "YOUR_CLIENT_SECRET"

    try:
        token = get_access_token(client_id, client_secret)
        print(f"Token: {token}")
    except Exception as e:
        print(f"Failed to get token: {e}")

Transcription in Python

import requests
import json

def transcribe_audio_file(file_path, language="en-US", specialty=None, access_token=None):
    """
    Transcribe an audio file using the Nuxera Transcription API.

    Args:
        file_path (str): Path to the audio file
        language (str): Language code (default: en-US)
        specialty (str): Medical specialty (optional)
        access_token (str): Your access token

    Returns:
        dict: Transcription results
    """
    if not access_token:
        raise ValueError("Access token is required")

    url = "https://api.nuxera.ai/v1/transcription"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    # Prepare form data with the file and parameters
    files = {
        "audio": open(file_path, "rb")
    }

    data = {
        "language": language
    }

    if specialty:
        data["medical_specialty"] = specialty

    try:
        response = requests.post(url, headers=headers, files=files, data=data)
        response.raise_for_status()

        result = response.json()
        return result
    except requests.exceptions.RequestException as e:
        print(f"Transcription error: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        raise
    finally:
        # Make sure to close the file
        files["audio"].close()

# Example usage
if __name__ == "__main__":
    from auth import get_access_token  # Import the authentication function

    client_id = "YOUR_CLIENT_ID"
    client_secret = "YOUR_CLIENT_SECRET"

    try:
        # Get access token
        token = get_access_token(client_id, client_secret)

        # Transcribe audio file
        transcription_result = transcribe_audio_file(
            file_path="patient_consultation.wav",
            language="en-US",
            specialty="cardiology",
            access_token=token
        )

        # Print results
        print("Transcription:")
        print(transcription_result["transcription"])

        print("\nStructured Data:")
        print(json.dumps(transcription_result["structured_data"], indent=2))

    except Exception as e:
        print(f"Error: {e}")

Java Examples

Authentication in Java

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

import org.json.JSONObject;

public class NuxeraAuthentication {

    private static final String AUTH_URL = "https://api.nuxera.ai/v1/auth/token";
    private static final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    public static String getAccessToken(String clientId, String clientSecret) throws IOException, InterruptedException {
        // Create the JSON payload
        JSONObject payload = new JSONObject();
        payload.put("client_id", clientId);
        payload.put("client_secret", clientSecret);

        // Build the request
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(AUTH_URL))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(payload.toString()))
                .build();

        // Send the request and get the response
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // Check if request was successful
        if (response.statusCode() != 200) {
            throw new IOException("Authentication failed: " + response.statusCode() + " " + response.body());
        }

        // Parse the response
        JSONObject jsonResponse = new JSONObject(response.body());

        return jsonResponse.getString("access_token");
    }

    public static void main(String[] args) {
        try {
            String clientId = "YOUR_CLIENT_ID";
            String clientSecret = "YOUR_CLIENT_SECRET";

            String token = getAccessToken(clientId, clientSecret);
            System.out.println("Access Token: " + token);
        } catch (Exception e) {
            System.err.println("Error getting access token: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Transcription in Java

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.time.Duration;
import java.util.UUID;

import org.json.JSONObject;

public class NuxeraTranscription {

    private static final String TRANSCRIPTION_URL = "https://api.nuxera.ai/v1/transcription";
    private static final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();

    public static JSONObject transcribeAudio(String filePath, String language, String accessToken)
            throws IOException, InterruptedException {

        // Read the audio file
        File audioFile = new File(filePath);
        byte[] fileContent = Files.readAllBytes(audioFile.toPath());

        // Generate boundary for multipart form
        String boundary = UUID.randomUUID().toString();

        // Build multipart form data
        String formData = buildMultipartFormData(boundary, fileContent, audioFile.getName(), language);

        // Build the request
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(TRANSCRIPTION_URL))
                .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                .header("Authorization", "Bearer " + accessToken)
                .POST(HttpRequest.BodyPublishers.ofString(formData))
                .build();

        // Send the request and get the response
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // Check if request was successful
        if (response.statusCode() != 200) {
            throw new IOException("Transcription failed: " + response.statusCode() + " " + response.body());
        }

        // Parse the response
        return new JSONObject(response.body());
    }

    private static String buildMultipartFormData(String boundary, byte[] fileContent,
            String fileName, String language) {
        StringBuilder builder = new StringBuilder();

        // Add audio file part
        builder.append("--").append(boundary).append("\r\n");
        builder.append("Content-Disposition: form-data; name=\"audio\"; filename=\"").append(fileName).append("\"\r\n");
        builder.append("Content-Type: audio/wav\r\n\r\n");
        builder.append(new String(fileContent)).append("\r\n");

        // Add language parameter
        builder.append("--").append(boundary).append("\r\n");
        builder.append("Content-Disposition: form-data; name=\"language\"\r\n\r\n");
        builder.append(language).append("\r\n");

        // End of multipart form
        builder.append("--").append(boundary).append("--\r\n");

        return builder.toString();
    }

    public static void main(String[] args) {
        try {
            // Get access token first (from the Authentication example)
            String accessToken = NuxeraAuthentication.getAccessToken("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");

            // Transcribe an audio file
            JSONObject result = transcribeAudio(
                "path/to/patient_recording.wav",
                "en-US",
                accessToken
            );

            // Print the results
            System.out.println("Transcription: " + result.getString("transcription"));
            System.out.println("Structured Data: " + result.getJSONObject("structured_data").toString(2));

        } catch (Exception e) {
            System.err.println("Error during transcription: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Full Application Examples

React Web Application for Medical Transcription

Check out our complete React application example on GitHub that demonstrates:

  • User authentication
  • Audio recording with quality monitoring
  • Transcription submission and result display
  • Structured medical data visualization
  • Integration with EHR systems

Node.js Backend Integration

Our Node.js backend example shows how to:

  • Create a secure proxy for Nuxera API calls
  • Implement token management and refresh
  • Handle file uploads and processing
  • Implement webhook receivers for asynchronous processing
  • Store and retrieve transcription results from a database

EHR Integration Examples

This section provides examples for integrating Nuxera transcription and dictation services with Electronic Health Record (EHR) systems.

FHIR Implementation Examples

This section contains examples for formatting Nuxera API results into FHIR-compliant resources.

Error Handling Examples

Robust Error Handling in JavaScript

async function transcribeWithErrorHandling(audioFile) {
  // Retry parameters
  const maxRetries = 3;
  const initialDelay = 1000; // ms

  let attempt = 0;

  while (attempt < maxRetries) {
    try {
      attempt++;
      console.log(`Attempt ${attempt} of ${maxRetries}`);

      // Get a fresh token each attempt to avoid token expiration issues
      const token = await getAccessToken();

      const formData = new FormData();
      formData.append('audio', audioFile);

      const response = await fetch('https://api.nuxera.ai/v1/transcription', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: formData,
      });

      // If we get a rate limit error, wait and retry
      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || 5;
        const delay = parseInt(retryAfter, 10) * 1000;
        console.log(`Rate limited. Retrying after ${retryAfter} seconds...`);
        await new Promise((resolve) => setTimeout(resolve, delay));
        continue;
      }

      // If we get an auth error, get a new token and retry
      if (response.status === 401) {
        console.log('Authentication error. Refreshing token...');
        // Force token refresh on next loop
        continue;
      }

      // For other errors, parse the error response
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(
          `API error: ${response.status} - ${
            errorData.message || response.statusText
          }`
        );
      }

      // Success - return the result
      return await response.json();
    } catch (error) {
      const isLastAttempt = attempt >= maxRetries;

      if (!isLastAttempt) {
        // Exponential backoff
        const delay = initialDelay * Math.pow(2, attempt - 1);
        console.log(`Retrying in ${delay}ms...`);
        await new Promise((resolve) => setTimeout(resolve, delay));
      } else {
        // Last attempt failed
        console.error('All retry attempts failed:', error);
        throw error;
      }
    }
  }
}

// Usage
try {
  const result = await transcribeWithErrorHandling(audioFile);
  console.log('Transcription successful:', result);
} catch (error) {
  console.error('Transcription failed after retries:', error);
  showUserFriendlyError(
    'We could not process your audio. Please try again later.'
  );
}

Audio Processing Examples

This section contains examples for processing audio files before sending them to the Nuxera API.

Need Help?

If you need assistance with these code examples or have questions about integrating the Nuxera API: