Skip to main content

Code Examples

Real-world code examples for common integration scenarios.

Complete Patient Management Flow

JavaScript/Node.js

import { NajeebClient } from '@najeeb/health-suite-sdk';

const client = new NajeebClient({
clientId: process.env.NAJEEB_CLIENT_ID,
clientSecret: process.env.NAJEEB_CLIENT_SECRET,
});

// Create a new patient
async function createPatient(patientData) {
try {
const patient = await client.patients.create({
national_id: patientData.nationalId,
first_name: patientData.firstName,
last_name: patientData.lastName,
date_of_birth: patientData.dateOfBirth,
gender: patientData.gender,
insurance_number: patientData.insuranceNumber,
insurance_company: patientData.insuranceCompany,
policy_start_date: patientData.policyStartDate,
address: {
street: patientData.address.street,
city: patientData.address.city,
region: patientData.address.region,
},
});

console.log('Patient created:', patient.id);
return patient;
} catch (error) {
if (error.code === 'DUPLICATE_ENTRY') {
// Patient already exists, fetch existing
const existing = await client.patients.list({
national_id: patientData.nationalId,
});
return existing.data[0];
}
throw error;
}
}

// Update patient information
async function updatePatient(patientId, updates) {
const patient = await client.patients.update(patientId, updates);
console.log('Patient updated:', patient.id);
return patient;
}

// Get patient with all related data
async function getPatientDetails(patientId) {
const patient = await client.patients.get(patientId);
const claims = await client.claims.list({ patient_id: patientId });
const authorizations = await client.authorizations.list({ patient_id: patientId });

return {
patient,
claims: claims.data,
authorizations: authorizations.data,
};
}

Python

from najeeb import NajeebClient
from najeeb.exceptions import DuplicateEntryError

client = NajeebClient(
client_id=os.environ['NAJEEB_CLIENT_ID'],
client_secret=os.environ['NAJEEB_CLIENT_SECRET']
)

def create_patient(patient_data):
try:
patient = client.patients.create({
'national_id': patient_data['national_id'],
'first_name': patient_data['first_name'],
'last_name': patient_data['last_name'],
'date_of_birth': patient_data['date_of_birth'],
'gender': patient_data['gender'],
'insurance_number': patient_data['insurance_number'],
'insurance_company': patient_data['insurance_company'],
'policy_start_date': patient_data['policy_start_date'],
'address': {
'street': patient_data['address']['street'],
'city': patient_data['address']['city'],
'region': patient_data['address']['region']
}
})
print(f'Patient created: {patient["id"]}')
return patient
except DuplicateEntryError:
# Patient already exists, fetch existing
existing = client.patients.list(national_id=patient_data['national_id'])
return existing['data'][0]

def get_patient_details(patient_id):
patient = client.patients.get(patient_id)
claims = client.claims.list(patient_id=patient_id)
authorizations = client.authorizations.list(patient_id=patient_id)

return {
'patient': patient,
'claims': claims['data'],
'authorizations': authorizations['data']
}

Claim Submission and Processing

JavaScript

// Submit a claim and track its status
async function submitAndTrackClaim(claimData) {
// Submit the claim
const claim = await client.claims.create({
patient_id: claimData.patientId,
provider_id: claimData.providerId,
service_date: claimData.serviceDate,
services: claimData.services,
diagnosis_codes: claimData.diagnosisCodes,
});

console.log(`Claim submitted: ${claim.claim_number}`);

// Poll for status updates
const maxAttempts = 30;
let attempts = 0;

while (attempts < maxAttempts) {
const updatedClaim = await client.claims.get(claim.id);

if (updatedClaim.status !== 'pending') {
console.log(`Claim ${updatedClaim.claim_number} status: ${updatedClaim.status}`);
return updatedClaim;
}

// Wait 10 seconds before checking again
await new Promise(resolve => setTimeout(resolve, 10000));
attempts++;
}

throw new Error('Claim processing timeout');
}

// Batch claim submission
async function submitBatchClaims(claims) {
const results = [];

for (const claimData of claims) {
try {
const claim = await client.claims.create(claimData);
results.push({ success: true, claim });
} catch (error) {
results.push({ success: false, error: error.message });
}

// Rate limiting: wait 100ms between requests
await new Promise(resolve => setTimeout(resolve, 100));
}

return results;
}

Authorization Workflow

JavaScript

// Request authorization and handle approval/rejection
async function requestAuthorization(authData) {
// Request authorization
const authorization = await client.authorizations.create({
patient_id: authData.patientId,
provider_id: authData.providerId,
service_date: authData.serviceDate,
services: authData.services,
diagnosis_codes: authData.diagnosisCodes,
urgency: authData.urgency,
});

console.log(`Authorization requested: ${authorization.authorization_number}`);

// For urgent/emergency, check status immediately
if (authData.urgency === 'urgent' || authData.urgency === 'emergency') {
return await waitForAuthorizationDecision(authorization.id);
}

return authorization;
}

async function waitForAuthorizationDecision(authId) {
const maxWaitTime = 300000; // 5 minutes
const startTime = Date.now();
const checkInterval = 5000; // 5 seconds

while (Date.now() - startTime < maxWaitTime) {
const auth = await client.authorizations.get(authId);

if (auth.status === 'approved') {
console.log('Authorization approved!');
return auth;
}

if (auth.status === 'rejected') {
throw new Error(`Authorization rejected: ${auth.notes || 'No reason provided'}`);
}

await new Promise(resolve => setTimeout(resolve, checkInterval));
}

throw new Error('Authorization decision timeout');
}

Webhook Handler

Node.js/Express

const express = require('express');
const { verifyWebhookSignature } = require('@najeeb/health-suite-sdk');

const app = express();
const processedEvents = new Set();

app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
const signature = req.headers['x-najeeb-signature'];
const secret = process.env.WEBHOOK_SECRET;

// Verify signature
if (!verifyWebhookSignature(req.body, signature, secret)) {
return res.status(401).send('Invalid signature');
}

const event = JSON.parse(req.body);

// Prevent duplicate processing
if (processedEvents.has(event.event_id)) {
return res.status(200).send('Event already processed');
}

try {
// Process event
await handleWebhookEvent(event);
processedEvents.add(event.event_id);

res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing error:', error);
res.status(500).send('Internal error');
}
});

async function handleWebhookEvent(event) {
switch (event.event_type) {
case 'claim.status_changed':
await handleClaimStatusChanged(event.data.object);
break;

case 'authorization.approved':
await handleAuthorizationApproved(event.data.object);
break;

case 'authorization.rejected':
await handleAuthorizationRejected(event.data.object);
break;

default:
console.log(`Unhandled event type: ${event.event_type}`);
}
}

async function handleClaimStatusChanged(claim) {
console.log(`Claim ${claim.claim_number} status: ${claim.status}`);

if (claim.status === 'approved') {
// Notify patient, update internal systems, etc.
await notifyPatient(claim.patient_id, 'Your claim has been approved');
}
}

async function handleAuthorizationApproved(authorization) {
console.log(`Authorization ${authorization.authorization_number} approved`);
// Update systems, notify provider, etc.
}

Error Handling with Retry Logic

JavaScript

async function makeRequestWithRetry(requestFn, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
// Don't retry on client errors (4xx)
if (error.status >= 400 && error.status < 500 && error.status !== 429) {
throw error;
}

// Rate limit: use Retry-After header if available
if (error.status === 429) {
const retryAfter = error.headers?.['retry-after'] || Math.pow(2, attempt);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
continue;
}

// Server errors: exponential backoff
if (error.status >= 500) {
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}

// Last attempt failed
if (attempt === maxRetries - 1) {
throw error;
}
}
}
}

// Usage
const patient = await makeRequestWithRetry(() =>
client.patients.get('pat_123456')
);

Next Steps