Documentation/ Developers/ Code Examples

Code Examples

Real-world code examples for integrating with Organiko.ai

💻

Multiple Language Support

Examples are provided in TypeScript/JavaScript, Python, Ruby, and cURL. Use whichever language fits your stack best.

1. Authentication & Token Management

Complete example of logging in, managing tokens, and making authenticated requests.

TypeScript
import fetch from 'node-fetch'; class OrganikoClient { private accessToken: string | null = null; private refreshToken: string | null = null; private readonly baseUrl = 'https://api.organiko.ai/v1'; async login(email: string, password: string) { const response = await fetch(`${this.baseUrl}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); const data = await response.json(); this.accessToken = data.data.access_token; this.refreshToken = data.data.refresh_token; return data.data.user; } async refreshAccessToken() { if (!this.refreshToken) throw new Error('No refresh token'); const response = await fetch(`${this.baseUrl}/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: this.refreshToken }), }); const data = await response.json(); this.accessToken = data.data.access_token; } async request(endpoint: string, options: RequestInit = {}) { const response = await fetch(`${this.baseUrl}${endpoint}`, { ...options, headers: { 'Authorization': `Bearer ${this.accessToken}`, 'Content-Type': 'application/json', ...options.headers, }, }); if (response.status === 401) { // Token expired, refresh and retry await this.refreshAccessToken(); return this.request(endpoint, options); } return response.json(); } } // Usage const client = new OrganikoClient(); await client.login('user@example.com', 'password'); const subscription = await client.request('/subscriptions/current');
Python
import requests from typing import Optional, Dict, Any class OrganikoClient: def __init__(self): self.base_url = 'https://api.organiko.ai/v1' self.access_token: Optional[str] = None self.refresh_token: Optional[str] = None def login(self, email: str, password: str) -> Dict[str, Any]: response = requests.post( f'{self.base_url}/auth/login', json={'email': email, 'password': password} ) response.raise_for_status() data = response.json()['data'] self.access_token = data['access_token'] self.refresh_token = data['refresh_token'] return data['user'] def refresh_access_token(self): if not self.refresh_token: raise ValueError('No refresh token available') response = requests.post( f'{self.base_url}/auth/refresh', json={'refresh_token': self.refresh_token} ) response.raise_for_status() self.access_token = response.json()['data']['access_token'] def request(self, endpoint: str, method: str = 'GET', **kwargs) -> Dict[str, Any]: headers = { 'Authorization': f'Bearer {self.access_token}', **kwargs.pop('headers', {}) } response = requests.request( method, f'{self.base_url}{endpoint}', headers=headers, **kwargs ) if response.status_code == 401: # Token expired, refresh and retry self.refresh_access_token() return self.request(endpoint, method, **kwargs) response.raise_for_status() return response.json() # Usage client = OrganikoClient() client.login('user@example.com', 'password') subscription = client.request('/subscriptions/current')

2. Creating a Purchase Order

Example of syncing a purchase order from your system to Organiko.ai.

TypeScript
async function createPurchaseOrder(client: OrganikoClient) { const orderData = { external_id: 'PO-2025-001', order_number: 'PO-001', order_date: '2025-10-30', expected_delivery: '2025-11-05', supplier: { name: 'Organic Farm Co.', email: 'orders@organicfarm.com', certification: 'USDA-ORG-12345', }, line_items: [ { product_name: 'Organic Tomatoes', quantity: 500, unit: 'lbs', unit_price: 2.50, certification_number: 'CERT-TOM-001', lot_number: 'LOT-2025-10-A', }, { product_name: 'Organic Lettuce', quantity: 300, unit: 'heads', unit_price: 1.75, certification_number: 'CERT-LET-002', lot_number: 'LOT-2025-10-B', }, ], notes: 'Deliver to warehouse dock B', }; try { const result = await client.request('/orders/purchase', { method: 'POST', body: JSON.stringify(orderData), }); console.log('Purchase order created:', result.data.id); return result.data; } catch (error) { console.error('Failed to create purchase order:', error); throw error; } } // Usage const order = await createPurchaseOrder(client);
cURL
curl -X POST https://api.organiko.ai/v1/orders/purchase \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "external_id": "PO-2025-001", "order_number": "PO-001", "order_date": "2025-10-30", "supplier": { "name": "Organic Farm Co.", "email": "orders@organicfarm.com" }, "line_items": [ { "product_name": "Organic Tomatoes", "quantity": 500, "unit": "lbs" } ] }'

3. Handling Webhooks

Example webhook handler with signature verification.

Node.js / Express
import express from 'express'; import crypto from 'crypto'; const app = express(); const WEBHOOK_SECRET = process.env.ORGANIKO_WEBHOOK_SECRET; // Verify webhook signature function verifySignature(payload: string, signature: string): boolean { const expectedSignature = crypto .createHmac('sha256', WEBHOOK_SECRET) .update(payload) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expectedSignature) ); } app.post('/webhooks/organiko', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.headers['x-organiko-signature'] as string; const payload = req.body.toString('utf8'); // Verify signature if (!verifySignature(payload, signature)) { return res.status(401).send('Invalid signature'); } const event = JSON.parse(payload); // Handle different event types switch (event.type) { case 'order.certified': console.log('Order certified:', event.data.order_id); // Update your system break; case 'inventory.updated': console.log('Inventory updated:', event.data.product_id); // Sync inventory levels break; case 'subscription.upgraded': console.log('Subscription upgraded:', event.data.new_tier); // Update user permissions break; default: console.log('Unknown event type:', event.type); } // Acknowledge receipt res.json({ received: true }); }); app.listen(3000, () => console.log('Webhook server running'));
Python / Flask
from flask import Flask, request, jsonify import hmac import hashlib import os app = Flask(__name__) WEBHOOK_SECRET = os.environ['ORGANIKO_WEBHOOK_SECRET'] def verify_signature(payload: bytes, signature: str) -> bool: expected_signature = hmac.new( WEBHOOK_SECRET.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected_signature) @app.route('/webhooks/organiko', methods=['POST']) def handle_webhook(): signature = request.headers.get('X-Organiko-Signature') payload = request.get_data() # Verify signature if not verify_signature(payload, signature): return jsonify({'error': 'Invalid signature'}), 401 event = request.get_json() # Handle different event types if event['type'] == 'order.certified': print(f"Order certified: {event['data']['order_id']}") # Update your system elif event['type'] == 'inventory.updated': print(f"Inventory updated: {event['data']['product_id']}") # Sync inventory levels # Acknowledge receipt return jsonify({'received': True}) if __name__ == '__main__': app.run(port=3000)

4. Batch Operations with Rate Limiting

Example of processing multiple records while respecting rate limits.

TypeScript
interface RateLimitInfo { limit: number; remaining: number; resetAt: Date; } class RateLimitedClient extends OrganikoClient { private rateLimit: RateLimitInfo | null = null; async request(endpoint: string, options: RequestInit = {}) { // Check if we need to wait for rate limit reset if (this.rateLimit && this.rateLimit.remaining === 0) { const waitTime = this.rateLimit.resetAt.getTime() - Date.now(); if (waitTime > 0) { console.log(`Rate limit reached, waiting ${waitTime}ms...`); await new Promise(resolve => setTimeout(resolve, waitTime)); } } const response = await super.request(endpoint, options); // Update rate limit info from headers const headers = response.headers; if (headers) { this.rateLimit = { limit: parseInt(headers.get('X-RateLimit-Limit') || '0'), remaining: parseInt(headers.get('X-RateLimit-Remaining') || '0'), resetAt: new Date(parseInt(headers.get('X-RateLimit-Reset') || '0') * 1000), }; } return response; } } async function batchSyncOrders(client: RateLimitedClient, orders: any[]) { const results = []; const batchSize = 10; // Process 10 at a time for (let i = 0; i < orders.length; i += batchSize) { const batch = orders.slice(i, i + batchSize); console.log(`Processing batch ${i / batchSize + 1} of ${Math.ceil(orders.length / batchSize)}`); const batchResults = await Promise.all( batch.map(async (order) => { try { return await client.request('/orders/purchase', { method: 'POST', body: JSON.stringify(order), }); } catch (error) { console.error(`Failed to sync order ${order.external_id}:`, error); return { error: true, order_id: order.external_id }; } }) ); results.push(...batchResults); // Small delay between batches if (i + batchSize < orders.length) { await new Promise(resolve => setTimeout(resolve, 1000)); } } return results; }

5. Robust Error Handling

Example with comprehensive error handling and retry logic.

Python
import time import requests from typing import Callable, Any class OrganikoAPIError(Exception): def __init__(self, status_code: int, message: str, code: str = None): self.status_code = status_code self.message = message self.code = code super().__init__(self.message) def with_retry( func: Callable, max_retries: int = 3, backoff_factor: float = 2.0 ) -> Any: """Retry decorator with exponential backoff""" for attempt in range(max_retries): try: return func() except requests.exceptions.RequestException as e: if attempt == max_retries - 1: raise wait_time = backoff_factor ** attempt print(f"Attempt {attempt + 1} failed, retrying in {wait_time}s...") time.sleep(wait_time) def safe_api_call(client: OrganikoClient, endpoint: str, **kwargs) -> Dict[str, Any]: """Make API call with proper error handling""" try: return with_retry(lambda: client.request(endpoint, **kwargs)) except requests.exceptions.HTTPError as e: response = e.response error_data = response.json().get('error', {}) if response.status_code == 400: raise OrganikoAPIError( 400, f"Bad request: {error_data.get('message')}", error_data.get('code') ) elif response.status_code == 401: raise OrganikoAPIError(401, "Unauthorized - check credentials") elif response.status_code == 429: # Rate limited reset_time = int(response.headers.get('X-RateLimit-Reset', 0)) wait_seconds = reset_time - int(time.time()) raise OrganikoAPIError( 429, f"Rate limited - retry after {wait_seconds}s" ) else: raise OrganikoAPIError( response.status_code, error_data.get('message', 'Unknown error') ) except requests.exceptions.ConnectionError: raise OrganikoAPIError(0, "Connection failed - check network") except requests.exceptions.Timeout: raise OrganikoAPIError(0, "Request timeout") # Usage try: result = safe_api_call(client, '/orders/purchase', method='POST', json=order_data) print(f"Order created: {result['data']['id']}") except OrganikoAPIError as e: print(f"API Error [{e.status_code}]: {e.message}") if e.code: print(f"Error code: {e.code}")

6. Using Official SDKs

Simplify your integration using our official SDKs.

TypeScript SDK
// Install: npm install @organiko/api-client import { Organiko } from '@organiko/api-client'; const organiko = new Organiko({ email: process.env.ORGANIKO_EMAIL, password: process.env.ORGANIKO_PASSWORD, }); // Auto-handles authentication and token refresh const subscription = await organiko.subscriptions.getCurrent(); console.log(`Current tier: ${subscription.tier}`); // Create purchase order const order = await organiko.orders.createPurchase({ orderNumber: 'PO-001', supplier: { name: 'Organic Farm' }, lineItems: [ { productName: 'Tomatoes', quantity: 500, unit: 'lbs' } ], }); // List inventory with filters const inventory = await organiko.inventory.list({ filter: 'status:active', limit: 50, });
Python SDK
# Install: pip install organiko-api from organiko import Organiko organiko = Organiko( email=os.environ['ORGANIKO_EMAIL'], password=os.environ['ORGANIKO_PASSWORD'] ) # Auto-handles authentication and token refresh subscription = organiko.subscriptions.get_current() print(f"Current tier: {subscription.tier}") # Create purchase order order = organiko.orders.create_purchase( order_number='PO-001', supplier={'name': 'Organic Farm'}, line_items=[ {'product_name': 'Tomatoes', 'quantity': 500, 'unit': 'lbs'} ] ) # List inventory with filters inventory = organiko.inventory.list( filter='status:active', limit=50 )