API Overview
Welcome to the Picos Health API documentation. This guide covers all accessible Picos Health collections and globals with examples, best practices, and advanced patterns.
📚 Documentation Structure
- Full API Reference - Complete endpoint documentation with all collections and globals
- API Authentication Guide - How to generate API keys and authenticate requests
- Search & Finder Endpoints - HCPCS code and SKU product search APIs with examples
- Collections & Examples - Practical JavaScript examples for working with data
- Globals & Advanced Patterns - System configuration, caching, rate limiting, and optimization
🚀 Quick Start
📌 Important: Throughout this documentation, you'll see
{org-name}as a placeholder in API URLs. Replace this with your organization's assigned subdomain. For example, if your organization is "EEDA", useeeda.api.picoshealth.cominstead of{org-name}.api.picoshealth.com.
0. Your Organization
Before you can authenticate, you need to identify your organization's assigned subdomain ({org-name}):
How to find your organization's subdomain:
- Log in to Picos Health Dashboard
- Navigate to Account Settings → Organization
- Look for your Organization Subdomain (e.g.,
eeda,kinexion,my-company) - Use this subdomain in all API URLs:
https://{subdomain}.api.picoshealth.com/v1
Example:
- If your subdomain is
eeda, your API base URL is:https://eeda.api.picoshealth.com/v1 - If your subdomain is
kinexion, your API base URL is:https://kinexion.api.picoshealth.com/v1
Note: Your organization's subdomain is unique and cannot be changed. If you're unsure of your subdomain, contact your account administrator or check your welcome email.
1. Authentication
All API requests require a JWT bearer token. Get started by:
- Generate an API Key in your Account Settings → API Integration
- Exchange it for a bearer token using the
/auth/tokenendpoint - Include the token in your request headers
// 1. Exchange API key for token
const authResponse = await fetch('https://{org-name}.api.picoshealth.com/v1/auth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: 'pk_live_...' }),
});
const { token } = await authResponse.json();
// 2. Use token in API requests
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/users', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
See detailed authentication guide →
2. Base URL
Important: The API base URL uses your organization's unique subdomain. Replace {org-name} with your assigned identifier.
https://{org-name}.api.picoshealth.com/v1
Environments:
Development: https://dev-api.picoshealth.com/v1
Production: https://{org-name}.api.picoshealth.com/v1
Multi-Tenant Deployments:
For organizations with custom domains, use your tenant-specific subdomain:
https://{tenant-name}.api.picoshealth.com/v1
Examples:
https://eeda.api.picoshealth.com/v1
https://my-company.api.picoshealth.com/v1
https://healthcare-org.api.picoshealth.com/v1
How to determine your API URL:
- Check your account settings or welcome email
- Use your organization's assigned subdomain
- Replace
{tenant-name}with your organization's identifier - Always append
/v1for the current API version
3. Common Patterns
Get all documents:
GET /users?limit=50&page=1&sort=-createdAt
Filter by field:
GET /products?where={"status":{"equals":"published"}}
Create document:
POST /users
Content-Type: application/json
{
"email": "user@example.com",
"password": "SecurePass123",
"role": "patient"
}
Update document:
PATCH /users/{id}
Content-Type: application/json
{
"role": "provider"
}
Delete document:
DELETE /users/{id}
📦 Collections Overview
Core Entities
| Collection | Purpose | Key Fields | Endpoint |
|---|---|---|---|
| Users | User accounts with auth | email, password, role | /users |
| Products | Formulary items | title, price, HCPCS codes | /products |
| Orders | Purchase orders | customer, line_items, total | /orders |
| Patients | Patient records | user, DOB, conditions | /patients |
Financial
| Collection | Purpose | Endpoint |
|---|---|---|
| Transactions | Financial records | /transactions |
| WalletBalance | Account balances | /wallet-balance |
| PaymentMethods | Stored payment info | /payment-methods |
| OrderAggregations | Revenue analytics | /order-aggregations |
Care Management
| Collection | Purpose | Endpoint |
|---|---|---|
| MyCareList | Patient care plans | /my-care-list |
| Overseers | Care supervisors | /overseers |
| Fulfillment | Order shipping | /fulfillment |
System
| Collection | Purpose | Endpoint |
|---|---|---|
| Messages | User messaging | /messages |
| Groups | User grouping | /groups |
| Media | File uploads | /media |
| Documents | File management | /documents |
🌍 Globals Overview
Globals are site-wide configuration settings:
| Global | Purpose | Endpoint |
|---|---|---|
| SiteSettings | Brand & contact info | /globals/site-settings |
| OrganizationSettings | Org configuration | /globals/organization-settings |
| Wallet | Payment system config | /globals/wallet |
| MessageSettings | Messaging config | /globals/message-settings |
| HCPCSFinder | Medical code lookup | /globals/hcpcs-finder |
| SKUFinder | SKU lookup | /globals/sku-finder |
Access any global:
GET /globals/{slug}
POST /globals/{slug}
� Search APIs
Specialized endpoints for searching medical codes and products with fuzzy matching and pagination.
HCPCS Code Search
Search for Healthcare Common Procedure Coding System (HCPCS) codes across 75,000+ medical codes.
// Search for HCPCS codes
const response = await fetch(
'https://{org-name}.api.picoshealth.com/v1/hcpcs/search?q=dressing&page=1&limit=10',
{
headers: { 'Authorization': `Bearer ${token}` },
}
);
const { results, totalCount } = await response.json();
// results: array of matching HCPCS codes
// totalCount: total number of matches across all pages
Query Parameters:
q(required): Search term (code or description)page(optional): Page number, default 1limit(optional): Results per page (max 100), default 10
Performance & Features:
- ✅ First request: ~100-200ms (loads 1.8 MB Excel data)
- ✅ Cached requests: ~50-100ms (1-hour cache TTL)
- ✅ Fuzzy matching with typo tolerance (Levenshtein distance)
- ✅ Data source: HCPC2025_JUL_ANWEB_v3.xlsx (75,000+ codes, July 2025 update)
- ✅ Bearer token authentication required
SKU Product Search
Search for products by description, manufacturer, category, or bar codes.
// Search for respiratory products
const response = await fetch(
'https://{org-name}.api.picoshealth.com/v1/sku/search?q=respiratory&limit=20',
{
headers: { 'Authorization': `Bearer ${token}` },
}
);
const { results, totalCount } = await response.json();
// results: array of matching products
// totalCount: total number of matches
Performance & Features:
- ✅ First request: ~100-200ms (loads 2.7 MB Excel data)
- ✅ Cached requests: ~50-100ms (1-hour cache TTL)
- ✅ Multi-field search: description, manufacturer, categories, UPC, EAN, GTIN
- ✅ Data source: Master-List.xlsx (34,542 products with full metadata)
- ✅ Fuzzy matching with typo tolerance
- ✅ Bearer token authentication required
Complete Search Workflow Example:
// 1. Search for SKU products
const productResults = await fetch(
'https://{org-name}.api.picoshealth.com/v1/sku/search?q=cpap&limit=10',
{ headers: { 'Authorization': `Bearer ${token}` } }
).then(r => r.json());
// 2. Search for HCPCS codes
const codeResults = await fetch(
'https://{org-name}.api.picoshealth.com/v1/hcpcs/search?q=E0601&limit=5',
{ headers: { 'Authorization': `Bearer ${token}` } }
).then(r => r.json());
// 3. Create product request with both
const productRequest = await fetch('https://{org-name}.api.picoshealth.com/v1/products/request', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
productData: productResults.results[0],
hcpcsCode: codeResults.results[0].HCPC,
userEmail: 'user@organization.com',
userName: 'John Doe',
userRole: 'Healthcare Admin',
organizationName: 'Healthcare Organization'
})
}).then(r => r.json());
console.log(`Product request created: ${productRequest.requestId}`);
See detailed Search API reference →
📝 Product Request API
Request products to be added to your formulary.
Create Product Request
Submit a product request with optional HCPCS code association:
// Basic product request
const requestProduct = async (token, product, hcpcsCode) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/products/request', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
productData: product,
hcpcsCode,
userEmail: 'user@organization.com',
userName: 'John Doe',
userRole: 'Admin',
organizationName: 'Healthcare Organization',
}),
});
return response.json();
};
// Use with SKU search results
const skuResults = await sku_search('respiratory');
const product = skuResults.results[0];
const request = await requestProduct(token, product, 'E0601');
Tier 1 Product Request
For Tier 1 admins: Include volume and pricing information:
// Tier 1 request with volume and pricing
const requestProductTier1 = async (token, product, hcpcsCode) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/products/request', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
productData: product,
hcpcsCode,
isTier1: true,
anticipatedVolume: 500, // units
volumeRate: 'monthly', // or 'weekly', 'yearly'
priceAmount: '45.99', // current unit price
priceCurrency: 'USD', // or 'CAD', 'EUR'
userEmail: 'admin@organization.com',
userName: 'Jane Smith',
userRole: 'Tier 1 Admin',
organizationName: 'Premier Healthcare',
}),
});
return response.json();
};
Features:
- ✅ Integration with SKU search results
- ✅ Optional HCPCS code association
- ✅ Tier 1-specific volume and pricing fields
- ✅ Unique request ID for tracking
- ✅ Bearer token authentication
See full Product Request reference →
�💡 Common Use Cases
User Management
Create a new patient:
const createPatient = async (token) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/users', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'patient@example.com',
password: 'SecurePass123!',
firstName: 'John',
lastName: 'Doe',
role: 'patient',
}),
});
return response.json();
};
Product Catalog
Search products by category:
const getProductsByCategory = async (token, categoryId) => {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/products?where={"categories":{"in":["${categoryId}"]}}`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
return response.json();
};
Order Processing
Create an order:
const createOrder = async (token, customerId) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/orders', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
customer: customerId,
line_items: [{ product: 'prod-id-1', quantity: 2 }],
total: 99.98,
currency: 'USD',
status: 'pending',
}),
});
return response.json();
};
Financial Operations
Get user transactions:
const getUserTransactions = async (token, userId) => {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/transactions?where={"user":{"equals":"${userId}"}}&sort=-createdAt`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
return response.json();
};
Care Management
Create a care list:
const createCareList = async (token, userId) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/my-care-list', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'Weekly Care',
owner: userId,
items: [{ product: 'prod-id-1', quantity: 12 }],
spendingLimits: [{ recipient: 'patient-id-1', limit: 500 }],
}),
});
return response.json();
};
🔍 Query Reference
Filtering
# Exact match
GET /users?where={"role":{"equals":"admin"}}
# In list
GET /users?where={"role":{"in":["admin","provider"]}}
# Numeric comparison
GET /orders?where={"total":{"greater_than":100}}
# Text contains
GET /products?where={"title":{"contains":"socks"}}
# Date range
GET /orders?where={"and":[{"createdAt":{"greater_than":"2024-01-01T00:00:00Z"}},{"createdAt":{"less_than":"2024-12-31T23:59:59Z"}}]}
Pagination
# Page 1 with 50 items
GET /users?limit=50&page=1
# Get all (use sparingly)
GET /products?limit=1000
Sorting
# Sort ascending
GET /products?sort=price
# Sort descending
GET /orders?sort=-createdAt
# Multiple fields
GET /orders?sort=-status,createdAt
Expansion
# No relationship expansion
GET /orders/{id}?depth=0
# Expand related documents
GET /orders/{id}?depth=2
⚡ Advanced Features
Caching
Implement caching for better performance:
class CachedAPI {
constructor(ttl = 60000) {
this.cache = new Map();
this.ttl = ttl;
}
async fetch(url, options) {
const cacheKey = `${options?.method || 'GET'}:${url}`;
if (!options?.method || options.method === 'GET') {
if (this.cache.has(cacheKey)) {
const { data, timestamp } = this.cache.get(cacheKey);
if (Date.now() - timestamp < this.ttl) {
return data;
}
}
}
const response = await fetch(url, options);
const data = await response.json();
if (!options?.method || options.method === 'GET') {
this.cache.set(cacheKey, { data, timestamp: Date.now() });
}
return data;
}
}
Rate Limiting
Avoid rate limit errors with proper queuing:
class RateLimitedQueue {
constructor(maxRequests = 100, windowMs = 60000) {
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = [];
}
async add(fn) {
// Queue management
const now = Date.now();
this.requests = this.requests.filter(time => now - time < this.windowMs);
if (this.requests.length >= this.maxRequests) {
await new Promise(resolve => setTimeout(resolve, 100));
return this.add(fn);
}
this.requests.push(now);
return fn();
}
}
Error Handling
Implement robust error handling:
const apiRequest = async (url, options = {}) => {
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`${response.status}: ${errorData.errors?.[0]?.message}`);
}
return await response.json();
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
📊 Response Format
All API responses follow a consistent format:
List Response
{
"docs": [
{ "id": "...", "email": "...", ... }
],
"totalDocs": 100,
"limit": 10,
"page": 1,
"totalPages": 10
}
Single Document
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"createdAt": "2024-01-20T10:30:00Z",
"updatedAt": "2024-01-20T10:30:00Z"
}
Error Response
{
"errors": [
{
"message": "Invalid credentials",
"field": "email"
}
]
}
🛡️ Security
Best Practices
Never commit tokens - Use environment variables
const token = process.env.API_TOKEN;Always use HTTPS - In production only
https://{org-name}.api.picoshealth.comRotate tokens regularly - Refresh every hour
if (tokenAge > 3600000) { token = await refreshToken(); }Validate input - Check before sending
if (!email.includes('@')) throw new Error('Invalid email');Handle errors safely - Don't leak sensitive info
catch (error) { console.error('Request failed'); // Don't log token }
📱 SDKs & Clients
JavaScript/TypeScript
Installation (Coming Soon):
npm install @picos/api-sdk
Usage:
import { PicosAPI } from '@picos/api-sdk';
const api = new PicosAPI({ token: 'YOUR_TOKEN' });
const users = await api.users.list();
Other Languages
- Python:
pip install picos-api(Coming Soon) - Go:
go get github.com/picos/api-sdk(Coming Soon) - Ruby:
gem install picos_api(Coming Soon)
🐛 Troubleshooting
Authentication Issues
401 Unauthorized: Missing or invalid authorization
// ❌ Wrong - Missing Authorization header
fetch('https://{org-name}.api.picoshealth.com/v1/users');
// ✅ Correct - Include Bearer token
fetch('https://{org-name}.api.picoshealth.com/v1/users', {
headers: { 'Authorization': `Bearer ${token}` }
});
Token Expired
- Tokens expire after 1 hour by default
- Solution: Refresh token by calling
/auth/tokenendpoint again
// Implement token refresh logic
const getValidToken = async (apiKey) => {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/auth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey })
});
return response.json().then(r => r.token);
};
Search API Issues
Search returns empty results despite query
- Verify authentication token is valid
- Try simpler search terms (e.g., "respiratory" instead of "r-e-s")
- Check that data file is loaded: first request takes 100-200ms
Search is slow (>1 second)
- First request loads Excel data (~100-200ms normal)
- Subsequent requests should be <100ms (cached)
- Large result sets (limit=100) may take longer to serialize
// Optimize search performance
const optimizedSearch = async (token, query) => {
// Use reasonable limits
const limit = 20; // Don't request max 100 if not needed
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/sku/search?q=${encodeURIComponent(query)}&limit=${limit}`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const { results, totalCount } = await response.json();
console.log(`Found ${results.length} of ${totalCount} total matches`);
return results;
};
Permission Issues
403 Forbidden
- User lacks permissions for this action
- Check user role: admin, provider, patient, user
- Tier 1 Admin required for: order approval, user management
Example: Order Approval (Tier 1 Admin only)
const approveOrder = async (token, orderId) => {
try {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/${orderId}/approve`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ status: 'approved' })
}
);
if (response.status === 403) {
throw new Error('You must be a Tier 1 Admin to approve orders');
}
return response.json();
} catch (error) {
console.error('Order approval failed:', error.message);
}
};
Common HTTP Errors
| Code | Issue | Solution |
|---|---|---|
| 400 | Bad Request - Invalid parameters | Check query/body format, validate JSON |
| 401 | Unauthorized - Missing/invalid token | Refresh token using /auth/token |
| 403 | Forbidden - Insufficient permissions | Verify user role (Tier 1 Admin required for some operations) |
| 404 | Not Found - Resource doesn't exist | Verify resource ID is correct |
| 429 | Rate Limited - Too many requests | Implement exponential backoff strategy |
| 500 | Server Error | Retry after short delay, contact support if persistent |
Rate Limiting Strategy
const fetchWithRetry = async (url, options, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);
if (response.status === 429) {
// Exponential backoff: 1s, 2s, 4s
const delayMs = Math.pow(2, i) * 1000;
console.log(`Rate limited, retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
continue;
}
return response;
}
throw new Error('Max retries exceeded');
};
🏢 Multi-Tenant Deployments
Dynamic API URL Configuration
For multi-tenant deployments, each organization has its own API subdomain:
// Determine API URL based on organization
const getApiUrl = (tenantName, environment = 'production') => {
if (environment === 'development') {
return 'https://dev-api.picoshealth.com/v1';
}
if (!tenantName) {
throw new Error('tenantName is required. Pass your organization\'s subdomain (e.g., "eeda", "my-company")');
}
// Custom tenant: https://tenant-name.api.picoshealth.com/v1
return `https://${tenantName}.api.picoshealth.com/v1`;
};
// Usage
const eeda_api = getApiUrl('eeda'); // https://eeda.api.picoshealth.com/v1
const custom_api = getApiUrl('my-company'); // https://my-company.api.picoshealth.com/v1
Multi-Tenant API Client
class PicosHealthAPI {
constructor(apiKey, tenantName, environment = 'production') {
if (!tenantName && environment === 'production') {
throw new Error('tenantName is required for production. Use your organization\'s subdomain.');
}
this.apiKey = apiKey;
this.tenantName = tenantName;
this.environment = environment;
this.token = null;
this.tokenExpiry = null;
}
getBaseUrl() {
if (this.environment === 'development') {
return 'https://dev-api.picoshealth.com/v1';
}
if (!this.tenantName) {
throw new Error('tenantName is required');
}
return `https://${this.tenantName}.api.picoshealth.com/v1`;
}
async ensureValidToken() {
if (this.token && this.tokenExpiry > Date.now()) {
return this.token;
}
const response = await fetch(`${this.getBaseUrl()}/auth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: this.apiKey })
});
const { token, expiresIn } = await response.json();
this.token = token;
this.tokenExpiry = Date.now() + (expiresIn * 1000);
return token;
}
async request(method, endpoint, data = null) {
const token = await this.ensureValidToken();
const url = `${this.getBaseUrl()}${endpoint}`;
const options = {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
return fetch(url, options).then(r => r.json());
}
searchSKU(query, limit = 10, page = 1) {
return this.request('GET', `/sku/search?q=${encodeURIComponent(query)}&limit=${limit}&page=${page}`);
}
searchHCPCS(query, limit = 10, page = 1) {
return this.request('GET', `/hcpcs/search?q=${encodeURIComponent(query)}&limit=${limit}&page=${page}`);
}
}
// Usage
const api = new PicosHealthAPI('pk_live_xxx', 'eeda');
const results = await api.searchSKU('respiratory', 20);
📞 Support
Need help?
- Documentation: Read the full API Reference
- Examples: Check Collections Examples
- Advanced: See Advanced Patterns
- Search Issues: Check Troubleshooting section
- Email: support@picoshealth.com
- Issues: Report via admin dashboard
🔄 Complete Workflows
End-to-end examples showing common business processes with proper error handling.
Workflow 1: Search and Request a Product
Complete flow: authenticate → search for product → create product request
// Complete workflow: Search and request a product
const searchAndRequestProduct = async (apiKey, tenantName, searchQuery) => {
if (!tenantName) {
throw new Error('tenantName is required. Provide your organization\'s subdomain.');
}
const baseUrl = `https://${tenantName}.api.picoshealth.com/v1`;
try {
// 1. Authenticate
console.log('Step 1: Authenticating...');
const authResponse = await fetch(`${baseUrl}/auth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey })
});
if (!authResponse.ok) {
throw new Error('Authentication failed: ' + authResponse.statusText);
}
const { token } = await authResponse.json();
console.log('✓ Authenticated');
// 2. Search for SKU products
console.log(`Step 2: Searching for "${searchQuery}"...`);
const searchResponse = await fetch(
`${baseUrl}/sku/search?q=${encodeURIComponent(searchQuery)}&limit=5`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const { results, totalCount } = await searchResponse.json();
if (results.length === 0) {
throw new Error('No products found');
}
console.log(`✓ Found ${results.length} of ${totalCount} matches`);
const product = results[0];
// 3. Search for related HCPCS codes
console.log('Step 3: Searching for related HCPCS codes...');
const hcpcsResponse = await fetch(
`${baseUrl}/hcpcs/search?q=${encodeURIComponent(searchQuery)}&limit=3`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const { results: hcpcsCodes } = await hcpcsResponse.json();
const hcpcsCode = hcpcsCodes[0]?.HCPC;
console.log(`✓ Found HCPCS code: ${hcpcsCode}`);
// 4. Create product request
console.log('Step 4: Creating product request...');
const requestResponse = await fetch(`${baseUrl}/products/request`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
productData: product,
hcpcsCode: hcpcsCode,
userEmail: 'user@organization.com',
userName: 'John Doe',
userRole: 'Healthcare Admin',
organizationName: 'Healthcare Organization'
})
});
const { requestId, status } = await requestResponse.json();
console.log(`✓ Product request created: ${requestId} (Status: ${status})`);
return { product, hcpcsCode, requestId };
} catch (error) {
console.error('❌ Workflow failed:', error.message);
throw error;
}
};
// Usage
await searchAndRequestProduct('pk_live_xxx', 'eeda', 'respiratory');
Workflow 2: Error Handling Example
Comprehensive error handling for real-world scenarios
// Robust error handling with retry logic
async function robustAPICall(token, endpoint, method = 'GET', data = null) {
const maxRetries = 3;
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const options = {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
const response = await fetch(endpoint, options);
// Handle specific error codes
switch (response.status) {
case 401:
throw new Error('Token expired or invalid - refresh and retry');
case 403:
throw new Error('Insufficient permissions for this operation');
case 429:
// Rate limited - retry with backoff
if (attempt < maxRetries) {
const delayMs = Math.pow(2, attempt - 1) * 1000;
console.log(`Rate limited. Retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
continue;
}
throw new Error('Rate limit exceeded - too many retries');
case 500:
// Server error - retry
if (attempt < maxRetries) {
console.log(`Server error. Attempt ${attempt}/${maxRetries}...`);
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
throw new Error('Server error persists after retries');
}
if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error(`API error: ${error.error || response.statusText}`);
}
return response.json();
} catch (error) {
lastError = error;
console.error(`Attempt ${attempt} failed:`, error.message);
if (attempt === maxRetries) {
throw lastError;
}
}
}
throw lastError;
}
// Usage
const results = await robustAPICall(token, 'https://{org-name}.api.picoshealth.com/v1/sku/search?q=cpap');
� Order Management Examples
Complete examples for managing orders in Picos Health - from creation through approval and cancellation.
Create Order
// Create a new order with line items and addresses
async function createOrder(token, orderData) {
const response = await fetch('https://{org-name}.api.picoshealth.com/v1/orders/create', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
lineItems: [
{
product: 'CPAP Machine',
title: 'CPAP Heated Tubing Kit Luna II G2',
price: '45.99',
quantity: 2,
subtotal: '91.98',
currency: 'USD',
vendor: '3B Medical Inc'
}
],
shippingAddress: {
name: 'John Doe',
street: '123 Main St',
city: 'New York',
state: 'NY',
zip: '10001',
country: 'USA'
},
notes: 'Please call before delivery'
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Order creation failed: ${error.error}`);
}
const { orderId, total, createdAt } = await response.json();
console.log(`Order created: ${orderId}, Total: $${total}`);
return { orderId, total, createdAt };
}
// Usage
const order = await createOrder(token, {});
List Orders with Pagination
// Retrieve paginated list of orders
async function listOrders(token, page = 1, limit = 10, filters = {}) {
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
...filters // Can include: status, userId, approved
});
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/view?${params}`,
{
headers: { 'Authorization': `Bearer ${token}` }
}
);
if (!response.ok) throw new Error('Failed to fetch orders');
const { orders, pagination } = await response.json();
console.log(`Found ${pagination.totalCount} orders (page ${pagination.page})`);
return { orders, pagination };
}
// Usage - Get approved orders
const { orders, pagination } = await listOrders(token, 1, 20, { approved: true });
// Usage - Filter by status
const pending = await listOrders(token, 1, 10, { status: 'pending' });
Get Single Order
// Retrieve full order details by ID
async function getOrder(token, orderId) {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/view/${orderId}`,
{
headers: { 'Authorization': `Bearer ${token}` }
}
);
if (!response.ok) {
if (response.status === 404) throw new Error('Order not found');
throw new Error('Failed to fetch order');
}
const order = await response.json();
console.log(`Order ${orderId}:`, {
status: order.status,
total: order.total,
items: order.lineItems.length,
approved: order.approved
});
return order;
}
// Usage
const order = await getOrder(token, 'order-uuid-12345');
Approve Order (Admin)
// Approve a pending order (Tier 1 Admin only)
async function approveOrder(token, orderId, adminMemberId) {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/${orderId}/approve`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ memberId: adminMemberId })
}
);
if (!response.ok) {
const error = await response.json();
if (response.status === 409) {
throw new Error('Order already approved');
}
throw new Error(`Approval failed: ${error.error}`);
}
const { approved, approvalDate } = await response.json();
console.log(`Order approved at ${approvalDate}`);
return { approved, approvalDate };
}
// Usage
try {
await approveOrder(token, 'order-uuid-12345', 'admin-member-uuid');
console.log('✓ Order approved');
} catch (error) {
console.error(error.message);
}
Deny Order
// Deny or cancel an order with optional reason
async function denyOrder(token, orderId, reason = '') {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/${orderId}/deny`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ reason })
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(`Denial failed: ${error.error}`);
}
const { status } = await response.json();
console.log(`Order cancelled. Reason: ${reason}`);
return { status };
}
// Usage
await denyOrder(token, 'order-uuid-12345', 'Out of stock');
Reorder (Duplicate Previous Order)
// Create a new order by duplicating a previous one
async function reorderPrevious(token, originalOrderId, notes = '') {
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/${originalOrderId}/reorder`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ notes })
}
);
if (!response.ok) {
if (response.status === 404) throw new Error('Original order not found');
throw new Error('Failed to create repeat order');
}
const { orderId, createdAt } = await response.json();
console.log(`Repeat order created: ${orderId}`);
return { orderId, createdAt };
}
// Usage - Reorder with same products and addresses
const newOrder = await reorderPrevious(
token,
'order-uuid-12345',
'Same as before, please expedite'
);
Cancel Order (1-Hour Window)
// Cancel an approved order (within 1 hour of approval)
async function cancelOrder(token, orderId, force = false) {
const params = force ? '?force=true' : '';
const response = await fetch(
`https://{org-name}.api.picoshealth.com/v1/orders/${orderId}/cancel${params}`,
{
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
}
);
if (!response.ok) {
const error = await response.json();
if (response.status === 410) {
throw new Error('Cancellation window expired (> 1 hour after approval)');
}
throw new Error(`Cancellation failed: ${error.error}`);
}
const { cancelledAt } = await response.json();
console.log(`Order cancelled at ${cancelledAt}`);
return { cancelledAt };
}
// Usage - Cancel within window
try {
await cancelOrder(token, 'order-uuid-12345');
console.log('✓ Order cancelled');
} catch (error) {
console.error(error.message);
}
// Usage - Force cancel (admin only)
await cancelOrder(token, 'order-uuid-12345', true);
Complete Order Workflow
// End-to-end workflow: create → list → view → approve → cancel
async function orderWorkflow(token) {
try {
// 1. Create order
console.log('1. Creating order...');
const { orderId } = await createOrder(token, {});
// 2. List orders to verify
console.log('2. Listing pending orders...');
const { orders } = await listOrders(token, 1, 10, { status: 'pending' });
console.log(`Found ${orders.length} pending orders`);
// 3. Get full order details
console.log('3. Getting order details...');
const order = await getOrder(token, orderId);
// 4. Approve order (if admin)
console.log('4. Approving order...');
await approveOrder(token, orderId, 'admin-member-uuid');
// 5. Try to cancel within 1 hour
console.log('5. Cancelling approved order...');
await cancelOrder(token, orderId);
console.log('✓ Complete workflow finished');
} catch (error) {
console.error('✗ Workflow error:', error.message);
}
}
// Run workflow
await orderWorkflow(token);
�📝 API Endpoints Summary
Collections (24)
Users, Products, Orders, Patients, Transactions, WalletBalance, PaymentMethods, Messages, Groups, Media, Documents, Members, Overseers, Fulfillment, MyCareList, Invites, ProductCategories, ProductTags, ProductFavorites, CheckoutSessions, OrdersActivityFeed, TransactionLogs, OrderAggregations, UserPermissionsConfig
Globals (9)
SiteSettings, OrganizationSettings, Wallet, MessageSettings, HCPCSFinder, SKUFinder, GlobalOrgDashboard, GlobalStorefrontHomepage, GlobalFormularySettings
Total Endpoints: 24 Collections + 9 Globals = 33 primary endpoints
🔄 API Changelog
Version 1.0.0 (Current)
- Full REST API for all collections
- Global configuration endpoints
- User authentication with JWT
- Role-based access control
- Pagination and filtering
- Relationship expansion
- Webhook support
📚 Additional Resources
Last Updated: June 17, 2026
API Version: 1.0.2