Code Examples
Real-world code examples for common integration scenarios.
Complete Patient Management Flow
JavaScript/Node.js
const BASE_URL = 'https://api.najeeb.com/v1';
async function apiRequest(path, options = {}) {
const response = await fetch(`${BASE_URL}${path}`, {
...options,
headers: {
'Authorization': `Bearer ${options.accessToken}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const error = new Error(`Request failed with status ${response.status}`);
error.status = response.status;
error.body = await response.json().catch(() => null);
throw error;
}
return response.json();
}
// Create a new patient
async function createPatient(accessToken, patientData) {
try {
const patient = await apiRequest('/patients', {
method: 'POST',
accessToken,
body: JSON.stringify({
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.data.id);
return patient.data;
} catch (error) {
if (error.body?.code === 'DUPLICATE_ENTRY') {
// Patient already exists, fetch existing
const existing = await apiRequest(`/patients?national_id=${patientData.nationalId}`, { accessToken });
return existing.data[0];
}
throw error;
}
}
// Update patient information
async function updatePatient(accessToken, patientId, updates) {
const patient = await apiRequest(`/patients/${patientId}`, {
method: 'PATCH',
accessToken,
body: JSON.stringify(updates),
});
console.log('Patient updated:', patient.data.id);
return patient.data;
}
// Get patient with all related data
async function getPatientDetails(accessToken, patientId) {
const patient = await apiRequest(`/patients/${patientId}`, { accessToken });
const claims = await apiRequest(`/claims?patient_id=${patientId}`, { accessToken });
const authorizations = await apiRequest(`/authorizations?patient_id=${patientId}`, { accessToken });
return {
patient: patient.data,
claims: claims.data,
authorizations: authorizations.data,
};
}
Python
import os
import requests
BASE_URL = 'https://api.najeeb.com/v1'
class DuplicateEntryError(Exception):
pass
def api_request(method, path, access_token, **kwargs):
response = requests.request(
method,
f'{BASE_URL}{path}',
headers={
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
},
**kwargs,
)
if response.status_code == 409:
raise DuplicateEntryError()
response.raise_for_status()
return response.json()
def create_patient(access_token, patient_data):
try:
result = api_request('POST', '/patients', access_token, json={
'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']
}
})
patient = result['data']
print(f'Patient created: {patient["id"]}')
return patient
except DuplicateEntryError:
# Patient already exists, fetch existing
existing = api_request('GET', f'/patients?national_id={patient_data["national_id"]}', access_token)
return existing['data'][0]
def get_patient_details(access_token, patient_id):
patient = api_request('GET', f'/patients/{patient_id}', access_token)
claims = api_request('GET', f'/claims?patient_id={patient_id}', access_token)
authorizations = api_request('GET', f'/authorizations?patient_id={patient_id}', access_token)
return {
'patient': patient['data'],
'claims': claims['data'],
'authorizations': authorizations['data']
}
Claim Submission and Processing
JavaScript
// Submit a claim and track its status
async function submitAndTrackClaim(accessToken, claimData) {
// Submit the claim
const claim = await apiRequest('/claims', {
method: 'POST',
accessToken,
body: JSON.stringify({
patient_id: claimData.patientId,
provider_id: claimData.providerId,
service_date: claimData.serviceDate,
services: claimData.services,
diagnosis_codes: claimData.diagnosisCodes,
}),
}).then(res => res.data);
console.log(`Claim submitted: ${claim.claim_number}`);
// Poll for status updates
const maxAttempts = 30;
let attempts = 0;
while (attempts < maxAttempts) {
const updatedClaim = await apiRequest(`/claims/${claim.id}`, { accessToken }).then(res => res.data);
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(accessToken, claims) {
const results = [];
for (const claimData of claims) {
try {
const claim = await apiRequest('/claims', {
method: 'POST',
accessToken,
body: JSON.stringify(claimData),
}).then(res => res.data);
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(accessToken, authData) {
// Request authorization
const authorization = await apiRequest('/authorizations', {
method: 'POST',
accessToken,
body: JSON.stringify({
patient_id: authData.patientId,
provider_id: authData.providerId,
service_date: authData.serviceDate,
services: authData.services,
diagnosis_codes: authData.diagnosisCodes,
urgency: authData.urgency,
}),
}).then(res => res.data);
console.log(`Authorization requested: ${authorization.authorization_number}`);
// For urgent/emergency, check status immediately
if (authData.urgency === 'urgent' || authData.urgency === 'emergency') {
return await waitForAuthorizationDecision(accessToken, authorization.id);
}
return authorization;
}
async function waitForAuthorizationDecision(accessToken, authId) {
const maxWaitTime = 300000; // 5 minutes
const startTime = Date.now();
const checkInterval = 5000; // 5 seconds
while (Date.now() - startTime < maxWaitTime) {
const auth = await apiRequest(`/authorizations/${authId}`, { accessToken }).then(res => res.data);
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 crypto = require('crypto');
const app = express();
const processedEvents = new Set();
function verifyWebhookSignature(payload, signature, secret) {
const expected = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
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(() =>
apiRequest('/patients/pat_123456', { accessToken })
);
Next Steps
- API Reference - Explore all endpoints