SDK Reference
Official Software Development Kits (SDKs) for integrating with the Alaikis BI API. SDKs provide convenient, type-safe wrappers around API endpoints with built-in error handling.
Supported Languages
| Language | Package | Version |
|---|---|---|
| Python | alaikis | 1.0.0 |
| JavaScript/TypeScript | @alaikis/sdk | 1.0.0 |
| Java | com.alaikis:alaikis-sdk | 1.0.0 |
| Go | github.com/alaikis/alaikis-go | 1.0.0 |
| PHP | alaikis/alaikis-php | 1.0.0 |
| Rust | alaikis | 1.0.0 |
Python SDK
Installation
bash
pip install alaikis
# or
pip install git+https://github.com/alaikis/alaikis-python.gitQuick Start
python
from alai kis import AlaikisClient
# Initialize client
client = AlaikisClient(api_key="alaikis_sk_your_key_here")
# Or with JWT token
client = AlaikisClient(jwt_token="eyJhbGciOiJIUzI1NiIs...")
# Packing calculation
result = client.packing.calculate(
skus=[
{
"id": "SKU001",
"length": 20,
"width": 15,
"height": 10,
"weight": 2.5,
"quantity": 10
}
],
pallets=[
{
"id": "PAL001",
"length": 120,
"width": 80,
"height": 150,
"max_weight": 1000
}
],
use_ai=True
)
print(f"Total pallets used: {result['total_pallets']}")
print(f"Total cost: {result.get('total_cost', 0)}")Product Trace Example
python
# Record a product
record_result = client.product_trace.record(
sku="PRODUCT-123",
identification_code="BATCH-001",
image_url="https://your-storage.com/product.jpg",
product_name="Premium Widget"
)
# Verify a product
verify_result = client.product_trace.verify(
sku="PRODUCT-123",
identification_code="BATCH-001",
image_url="https://your-storage.com/verify.jpg",
threshold=0.85
)
if verify_result["is_verified"]:
print(f"Product verified! Score: {verify_result['similarity_score']}")
else:
print("Product not verified")
# Barcode detection
barcode_result = client.product_trace.detect_barcode(
image_url="https://your-storage.com/with_barcode.jpg"
)
for barcode in barcode_result["unique_barcodes"]:
print(f"Found {barcode['type']}: {barcode['data']}")Address Parsing Example
python
# Parse single address
address_result = client.address.parse(
address="John Smith 123 Main St Apt 4B New York NY 10001",
language="en"
)
data = address_result["data"]
print(f"City: {data['city']}")
print(f"Postal: {data['postcode']}")
# Batch parse
batch_result = client.address.batch([
"1600 Pennsylvania Ave NW Washington DC 20500",
"10 Downing Street London SW1A 2AA UK"
])
for result in batch_result["results"]:
print(f"{result['city']}, {result['postcode']}")Classification Example
python
class_result = client.classifications.classify(
model="shipping-status-classifier",
query="Your package has been delivered to the front desk",
language="en"
)
print(f"Classification: {class_result['label']}")
print(f"Confidence: {class_result['scores'][class_result['label']]}")Error Handling
python
from alai kis.exceptions import (
AlaikisError,
AuthenticationError,
ValidationError,
RateLimitError,
ServerError
)
try:
result = client.packing.calculate(skus=[...], pallets=[...])
except AuthenticationError:
print("Invalid API key - check your credentials")
except ValidationError as e:
print(f"Validation error: {e}")
except RateLimitError as e:
print(f"Rate limited, retry after {e.retry_after}s")
except ServerError:
print("Server error - try again later")
except AlaikisError as e:
print(f"API error: {e}")Advanced Configuration
python
client = AlaikisClient(
api_key="alaikis_sk_your_key",
base_url="https://api.alaikis.com",
timeout=30,
max_retries=3,
retry_delay=1.0
)
# Enable debug logging
import logging
logging.getLogger("alaikis").setLevel(logging.DEBUG)JavaScript/TypeScript SDK
Installation
bash
npm install @alaikis/sdk
# or
yarn add @alaikis/sdkQuick Start
typescript
import { AlaikisClient } from '@alaikis/sdk';
const client = new AlaikisClient({
apiKey: 'alaikis_sk_your_key_here'
});
// Packing calculation
const result = await client.packing.calculate({
skus: [{
id: 'SKU001',
length: 20,
width: 15,
height: 10,
weight: 2.5,
quantity: 10
}],
pallets: [{
id: 'PAL001',
length: 120,
width: 80,
height: 150,
maxWeight: 1000
}],
useAi: true
});
console.log(`Total pallets: ${result.totalPallets}`);Product Trace Example
typescript
// Record product
const recordResult = await client.productTrace.record({
sku: 'PRODUCT-123',
identificationCode: 'BATCH-001',
imageUrl: 'https://your-storage.com/product.jpg',
productName: 'Premium Widget'
});
// Verify product
const verifyResult = await client.productTrace.verify({
sku: 'PRODUCT-123',
identificationCode: 'BATCH-001',
imageUrl: 'https://your-storage.com/verify.jpg',
threshold: 0.85
});
if (verifyResult.isVerified) {
console.log(`Verified! Score: ${verifyResult.similarityScore}`);
}Promise-based API with async/await
typescript
// Parallel requests
const [packing, address] = await Promise.all([
client.packing.calculate({...}),
client.address.parse({ address: '123 Main St...' })
]);Error Handling
typescript
import { AlaikisClient, errors } from '@alaikis/sdk';
try {
const result = await client.packing.calculate({...});
} catch (error) {
if (error instanceof errors.AuthenticationError) {
console.log('Invalid credentials');
} else if (error instanceof errors.RateLimitError) {
console.log(`Retry after ${error.retryAfter}s`);
} else if (error instanceof errors.ValidationError) {
console.log('Validation:', error.details);
}
}Configuration Options
typescript
const client = new AlaikisClient({
apiKey: 'alaikis_sk_your_key',
baseUrl: 'https://api.alaikis.com',
timeout: 30000,
maxRetries: 3,
retryDelay: 1000
});Java SDK
Installation (Maven)
xml
<dependency>
<groupId>com.alaikis</groupId>
<artifactId>alaikis-sdk</artifactId>
<version>1.0.0</version>
</dependency>Quick Start
java
import com.alaikis.sdk.AlaikisClient;
import com.alaikis.sdk.models.*;
import com.alaikis.sdk.exceptions.*;
public class Example {
public static void main(String[] args) {
AlaikisClient client = new AlaikisClient("alaikis_sk_your_key");
// Packing request
PackingRequest request = new PackingRequest();
Sku sku = new Sku();
sku.setId("SKU001");
sku.setLength(20.0);
sku.setWidth(15.0);
sku.setHeight(10.0);
sku.setWeight(2.5);
sku.setQuantity(10);
Pallet pallet = new Pallet();
pallet.setId("PAL001");
pallet.setLength(120.0);
pallet.setWidth(80.0);
pallet.setHeight(150.0);
pallet.setMaxWeight(1000.0);
request.setSkus(Collections.singletonList(sku));
request.setPallets(Collections.singletonList(pallet));
try {
PackingResponse response = client.packing().calculate(request);
System.out.println("Total pallets: " + response.getTotalPallets());
} catch (AuthenticationException e) {
System.out.println("Auth failed: " + e.getMessage());
} catch (ValidationException e) {
System.out.println("Validation: " + e.getDetails());
}
}
}Async API
java
// Using CompletableFuture
client.packing().calculateAsync(request)
.thenApply(response -> {
System.out.println("Total pallets: " + response.getTotalPallets());
return response;
})
.exceptionally(ex -> {
System.out.println("Error: " + ex.getMessage());
return null;
});Go SDK
Installation
bash
go get github.com/alaikis/alaikis-goQuick Start
go
package main
import (
"fmt"
"github.com/alaikis/alaikis-go"
)
func main() {
client := alai kis.NewClient("alaikis_sk_your_key")
// Packing calculation
skus := []alaikis.Sku{
{
ID: "SKU001",
Length: 20.0,
Width: 15.0,
Height: 10.0,
Weight: 2.5,
Quantity: 10,
},
}
pallets := []alaikis.Pallet{
{
ID: "PAL001",
Length: 120.0,
Width: 80.0,
Height: 150.0,
MaxWeight: 1000.0,
},
}
result, err := client.Packing.Calculate(skus, pallets, nil)
if err != nil {
if err, ok := err.(*alaikis.AuthenticationError); ok {
fmt.Println("Auth failed:", err)
} else {
fmt.Println("Error:", err)
}
return
}
fmt.Printf("Total pallets: %d\n", result.TotalPallets)
}Product Trace Example
go
// Record a product
record := &alaikis.ProductRecordRequest{
SKU: "PRODUCT-123",
IdentificationCode: "BATCH-001",
ImageURL: "https://your-storage.com/product.jpg",
ProductName: "Premium Widget",
}
result, err := client.ProductTrace.Record(record)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Recorded with ID: %d\n", result.ID)PHP SDK
Installation
bash
composer require alai kis/alaikis-phpQuick Start
php
<?php
require 'vendor/autoload.php';
use Alaikis\AlaikisClient;
use Alaikis\Exceptions\AuthenticationException;
use Alaikis\Exceptions\ValidationException;
$client = new AlaikisClient('alaikis_sk_your_key');
try {
$result = $client->packing->calculate([
'skus' => [[
'id' => 'SKU001',
'length' => 20,
'width' => 15,
'height' => 10,
'weight' => 2.5,
'quantity' => 10
]],
'pallets' => [[
'id' => 'PAL001',
'length' => 120,
'width' => 80,
'height' => 150,
'max_weight' => 1000
]]
]);
echo "Total pallets: " . $result['total_pallets'];
} catch (AuthenticationException $e) {
echo "Auth failed: " . $e->getMessage();
} catch (ValidationException $e) {
echo "Validation: " . json_encode($e->getDetails());
}Rust SDK
Installation (Cargo.toml)
toml
[dependencies]
alaikis = "1.0.0"Quick Start
rust
use alai kis::{AlaikisClient, PackingRequest, Sku, Pallet};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = AlaikisClient::new("alaikis_sk_your_key");
let request = PackingRequest {
skus: vec![Sku {
id: "SKU001".to_string(),
length: 20.0,
width: 15.0,
height: 10.0,
weight: 2.5,
quantity: 10,
..Default::default()
}],
pallets: vec![Pallet {
id: "PAL001".to_string(),
length: 120.0,
width: 80.0,
height: 150.0,
max_weight: 1000.0,
..Default::default()
}],
..Default::default()
};
match client.packing.calculate(request).await {
Ok(result) => {
println!("Total pallets: {}", result.total_pallets);
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
Ok(())
}SDK Features Comparison
| Feature | Python | JS/TS | Java | Go | PHP | Rust |
|---|---|---|---|---|---|---|
| Type Safety | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Async/Await | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
| Retry Logic | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Error Handling | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Request Logging | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Custom Timeouts | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Packing API | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Product Trace | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Address API | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Classification | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| User Management | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Token Management | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
SDK Best Practices
1. Reuse Client Instances
Good:
python
# Create once, reuse many times
client = AlaikisClient(api_key="...")
for _ in range(100):
result = client.packing.calculate(...)Bad:
python
# Don't