Collections API Reference - Detailed Examples

Comprehensive examples for working with Payload CMS collections through the REST API.

📌 Note: In all code examples below, replace {org-name} with your organization's subdomain. For example: eeda, kinexion, or my-company.

Table of Contents

  1. User Management
  2. Product Catalog
  3. Order Management
  4. Financial Operations
  5. Care Management
  6. Messaging

User Management

Creating Users Programmatically

// Create a new patient user
const createPatientUser = 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: 'Patient',
      role: 'patient',
      location: 'New York, NY',
    }),
  });
  return response.json();
};

Response:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "patient@example.com",
  "firstName": "John",
  "lastName": "Patient",
  "role": "patient",
  "location": "New York, NY",
  "createdAt": "2024-01-20T10:30:00Z"
}

Querying Users with Filters

// Get all admin users
const getAdminUsers = async (token) => {
  const response = await fetch(
      'https://{org-name}.api.picoshealth.com/v1/users?where={"role":{"equals":"admin"}}',
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get users created in the last 7 days
const getRecentUsers = async (token) => {
  const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
  const response = await fetch(
      `https://{org-name}.api.picoshealth.com/v1/users?where={"createdAt":{"greater_than":"${sevenDaysAgo}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Search users by email
const searchUserByEmail = async (token, emailPattern) => {
  const response = await fetch(
      `https://{org-name}.api.picoshealth.com/v1/users?limit=10&where={"email":{"contains":"${emailPattern}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Updating User Information

// Update user role
const promoteUserToProvider = async (token, userId) => {
  const response = await fetch(
      `https://{org-name}.api.picoshealth.com/v1/users/${userId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        role: 'provider',
      }),
    }
  );
  return response.json();
};

// Update user profile
const updateUserProfile = async (token, userId, updates) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/users/${userId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        firstName: updates.firstName,
        lastName: updates.lastName,
        location: updates.location,
      }),
    }
  );
  return response.json();
};

Product Catalog

Creating Products

// Create a new product with HCPCS code
const createProduct = async (token) => {
    const response = await fetch('https://{org-name}.api.picoshealth.com/v1/products', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      title: 'Compression Socks',
      description: 'Medical-grade compression socks for circulation support',
      price: 49.99,
      currency: 'USD',
      sku: 'CS-MED-001',
      manufacturer: 'CompressionCare Inc',
      hcpcs_code: ['E0663', 'E0666'],
      variant_unit: 'pair',
      status: 'draft',
      categories: ['category-id-123'],
    }),
  });
  return response.json();
};

Response:

{
  "id": "prod-uuid-abc123",
  "title": "Compression Socks",
  "price": 49.99,
  "currency": "USD",
  "sku": "CS-MED-001",
  "status": "draft",
  "createdAt": "2024-01-20T11:00:00Z"
}

Publishing Products

// Publish a draft product
const publishProduct = async (token, productId) => {
  const response = await fetch(
      `https://{org-name}.api.picoshealth.com/v1/products/${productId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        status: 'published',
      }),
    }
  );
  return response.json();
};

Searching Products

// Find 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();
};

// Find products in price range
const getProductsByPriceRange = async (token, minPrice, maxPrice) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/products?where={"and":[{"price":{"greater_than":${minPrice}}},{"price":{"less_than":${maxPrice}}}]}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Search by HCPCS code
const findProductByHCPCSCode = async (token, hcpcsCode) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/products?where={"hcpcs_code":{"contains":"${hcpcsCode}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Find published products with pagination
const getPublishedProducts = async (token, page = 1, limit = 20) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/products?where={"status":{"equals":"published"}}&limit=${limit}&page=${page}&sort=-createdAt`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Bulk Product Operations

// Update product pricing
const updateProductPrice = async (token, productId, newPrice) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/products/${productId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        price: newPrice,
      }),
    }
  );
  return response.json();
};

// Archive a product
const archiveProduct = async (token, productId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/products/${productId}`,
    {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response;
};

Order Management

Creating Orders

// Create a new 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-uuid-1',
          quantity: 2,
          price: 49.99,
        },
        {
          product: 'prod-uuid-2',
          quantity: 1,
          price: 29.99,
        },
      ],
      subtotal: 129.97,
      tax: 10.40,
      total: 140.37,
      currency: 'USD',
      status: 'pending',
      shipping_address: {
        street: '123 Main St',
        city: 'New York',
        state: 'NY',
        zip: '10001',
        country: 'USA',
      },
      billing_address: {
        street: '123 Main St',
        city: 'New York',
        state: 'NY',
        zip: '10001',
        country: 'USA',
      },
    }),
  });
  return response.json();
};

Response:

{
  "id": "order-uuid-abc123",
  "uuid": "order-uuid-abc123",
  "customer": "user-id-123",
  "total": 140.37,
  "currency": "USD",
  "status": "pending",
  "line_items": [
    {
      "product": "prod-uuid-1",
      "quantity": 2,
      "price": 49.99
    }
  ],
  "createdAt": "2024-01-20T14:30:00Z"
}

Order Status Management

// Update order status to approved
const approveOrder = async (token, orderId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders/${orderId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        status: 'approved',
      }),
    }
  );
  return response.json();
};

// Cancel an order
const cancelOrder = async (token, orderId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders/${orderId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        status: 'cancelled',
      }),
    }
  );
  return response.json();
};

// Ship an order
const shipOrder = async (token, orderId, trackingNumber) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders/${orderId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        status: 'shipped',
        metadata: {
          trackingNumber: trackingNumber,
        },
      }),
    }
  );
  return response.json();
};

Querying Orders

// Get pending orders
const getPendingOrders = async (token) => {
  const response = await fetch(
    'https://{org-name}.api.picoshealth.com/v1/orders?where={"status":{"equals":"pending"}}&sort=-createdAt',
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get customer orders
const getCustomerOrders = async (token, customerId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders?where={"customer":{"equals":"${customerId}"}}&sort=-createdAt`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get high-value orders
const getHighValueOrders = async (token, minAmount) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders?where={"total":{"greater_than":${minAmount}}}&limit=50`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get orders from date range
const getOrdersByDateRange = async (token, startDate, endDate) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/orders?where={"and":[{"createdAt":{"greater_than":"${startDate}"}},{"createdAt":{"less_than":"${endDate}"}}]}&sort=-createdAt`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Financial Operations

Transaction Management

// Record a new transaction
const recordTransaction = async (token, userId, amount, type) => {
  const response = await fetch('https://{org-name}.api.picoshealth.com/v1/transactions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      user: userId,
      type: type, // 'charge', 'credit', 'refund'
      amount: amount,
      currency: 'USD',
      status: 'completed',
      description: `Payment for order`,
    }),
  });
  return response.json();
};

Wallet Operations

// Get user wallet balance
const getUserWallet = async (token, userId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/wallet-balance?where={"user":{"equals":"${userId}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get payment methods for user
const getUserPaymentMethods = async (token, userId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/payment-methods?where={"user":{"equals":"${userId}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Add payment method
const addPaymentMethod = async (token, userId) => {
    const response = await fetch('https://{org-name}.api.picoshealth.com/v1/payment-methods', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      user: userId,
      type: 'credit_card',
      last4: '4242',
      expiryDate: '12/2025',
      isDefault: false,
    }),
  });
  return response.json();
};

Transaction History

// Get user transaction history
const getUserTransactionHistory = async (token, userId, limit = 50) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/transactions?where={"user":{"equals":"${userId}"}}&limit=${limit}&sort=-createdAt`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get transaction details
const getTransactionDetails = async (token, transactionId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/transactions/${transactionId}?depth=2`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get refunds for a period
const getRefunds = async (token, startDate, endDate) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/transactions?where={"and":[{"type":{"equals":"refund"}},{"createdAt":{"greater_than":"${startDate}"}},{"createdAt":{"less_than":"${endDate}"}}]}&limit=100`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Care Management

My CareList Operations

// Create a care list for patient management
const createCareList = async (token, ownerId) => {
  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: 'Mom\'s Weekly Care',
      owner: ownerId,
      assignedTo: ['patient-id-123'],
      items: [
        {
          product: 'prod-uuid-1',
          quantity: 12,
        },
        {
          product: 'prod-uuid-2',
          quantity: 7,
        },
      ],
      spendingLimits: [
        {
          recipient: 'patient-id-123',
          limit: 500,
        },
      ],
    }),
  });
  return response.json();
};

// Get user's care lists
const getUserCareLists = async (token, userId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/my-care-list?where={"owner":{"equals":"${userId}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Update care list items
const updateCareListItems = async (token, careListId, newItems) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/my-care-list/${careListId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        items: newItems,
      }),
    }
  );
  return response.json();
};

Patient Management

// Create patient record
const createPatientRecord = async (token, userId) => {
  const response = await fetch('https://{org-name}.api.picoshealth.com/v1/patients', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      user: userId,
      dateOfBirth: '1970-05-15',
      medicalConditions: ['diabetes', 'hypertension', 'arthritis'],
      medications: ['Metformin', 'Lisinopril'],
      insuranceProvider: 'Blue Cross Blue Shield',
      emergencyContact: {
        name: 'Jane Smith',
        phone: '555-0123',
        relationship: 'Spouse',
      },
    }),
  });
  return response.json();
};

// Get patient details
const getPatientDetails = async (token, patientId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/patients/${patientId}?depth=2`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Overseer Relationships

// Add overseer for patient
const addOverseerForPatient = async (token, overseerUserId, patientId) => {
    const response = await fetch('https://{org-name}.api.picoshealth.com/v1/overseers', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      overseer: overseerUserId,
      patient: patientId,
      permissions: ['view_profile', 'approve_orders', 'view_transactions'],
      approvalRequired: true,
    }),
  });
  return response.json();
};

// Get overseers for patient
const getPatientOverseers = async (token, patientId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/overseers?where={"patient":{"equals":"${patientId}"}}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

Messaging

Creating Messages

// Send a message
const sendMessage = async (token, fromUserId, toUserId) => {
  const response = await fetch('https://{org-name}.api.picoshealth.com/v1/messages', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      subject: 'Your Order Has Been Shipped',
      body: '<p>Your order #12345 has been shipped! Track your package using the tracking number: 1Z999AA10123456784</p>',
      from_user: fromUserId,
      to_user: toUserId,
      read: false,
    }),
  });
  return response.json();
};

Managing Messages

// Get user inbox
const getUserInbox = async (token, userId, limit = 30) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/messages?where={"to_user":{"equals":"${userId}"}}&sort=-createdAt&limit=${limit}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Get unread messages
const getUnreadMessages = async (token, userId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/messages?where={"and":[{"to_user":{"equals":"${userId}"}},{"read":{"equals":false}}]}`,
    {
      headers: { 'Authorization': `Bearer ${token}` },
    }
  );
  return response.json();
};

// Mark message as read
const markMessageAsRead = async (token, messageId) => {
  const response = await fetch(
    `https://{org-name}.api.picoshealth.com/v1/messages/${messageId}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        read: true,
        read_at: new Date().toISOString(),
      }),
    }
  );
  return response.json();
};

Error Handling Best Practices

// Comprehensive error handling function
const apiRequest = async (url, options = {}) => {
  try {
    const response = await fetch(url, options);
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${response.status} - ${errorData.errors?.[0]?.message || 'Unknown error'}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Request failed:', error.message);
    throw error;
  }
};

// Usage
try {
  const users = await apiRequest('https://{org-name}.api.picoshealth.com/v1/users', {
    headers: { 'Authorization': `Bearer ${token}` },
  });
  console.log('Users:', users);
} catch (error) {
  console.error('Failed to fetch users:', error);
}

Rate Limiting

Be aware of rate limiting:

  • Default limit: 100 requests per minute
  • Implement exponential backoff for retries
  • Cache frequently accessed data
// Retry with exponential backoff
const retryWithBackoff = async (fn, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};

SDK Usage (Coming Soon)

Official JavaScript SDK available at npm install @picos/api-sdk