跳到主要内容

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​

LanguagePackageVersion
Pythonalaikis1.0.0
JavaScript/TypeScript@alaikis/sdk1.0.0
Javacom.alaikis:alaikis-sdk1.0.0
Gogithub.com/alaikis/alaikis-go1.0.0
PHPalaikis/alaikis-php1.0.0
Rustalaikis1.0.0

Python SDK​

Installation​

pip install alaikis
# or
pip install git+https://github.com/alaikis/alaikis-python.git

Quick Start​

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,
ldm_width=2.44,
ldm_mode="projection"
)

print(f"Total pallets used: {result['total_pallets']}")
print(f"Total cost: {result.get('total_cost', 0)}")
print(f"Total LDM: {result.get('total_ldm', 0)}")

Product Trace Example​

# 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​

# 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​

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​

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​

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​

npm install @alaikis/sdk
# or
yarn add @alaikis/sdk

Quick Start​

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,
ldmWidth: 2.44,
ldmMode: 'projection'
});

console.log(`Total pallets: ${result.totalPallets}`);
console.log(`Total LDM: ${result.totalLdm}`);

Product Trace Example​

// 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​

// Parallel requests
const [packing, address] = await Promise.all([
client.packing.calculate({...}),
client.address.parse({ address: '123 Main St...' })
]);

Error Handling​

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​

const client = new AlaikisClient({
apiKey: 'alaikis_sk_your_key',
baseUrl: 'https://api.alaikis.com',
timeout: 30000,
maxRetries: 3,
retryDelay: 1000
});

Java SDK​

Installation (Maven)​

<dependency>
<groupId>com.alaikis</groupId>
<artifactId>alaikis-sdk</artifactId>
<version>1.0.0</version>
</dependency>

Quick Start​

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));
request.setLdmWidth(2.44);
request.setLdmMode("projection");

try {
PackingResponse response = client.packing().calculate(request);
System.out.println("Total pallets: " + response.getTotalPallets());
System.out.println("Total LDM: " + response.getTotalLdm());
} catch (AuthenticationException e) {
System.out.println("Auth failed: " + e.getMessage());
} catch (ValidationException e) {
System.out.println("Validation: " + e.getDetails());
}
}
}

Async API​

// 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​

go get github.com/alaikis/alaikis-go

Quick Start​

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​

// 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​

composer require alai kis/alaikis-php

Quick Start​

<?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
]],
'ldm_width' => 2.44,
'ldm_mode' => 'projection'
]);

echo "Total pallets: " . $result['total_pallets'];
echo "Total LDM: " . $result['total_ldm'];

} catch (AuthenticationException $e) {
echo "Auth failed: " . $e->getMessage();
} catch (ValidationException $e) {
echo "Validation: " . json_encode($e->getDetails());
}

Rust SDK​

Installation (Cargo.toml)​

[dependencies]
alaikis = "1.0.0"

Quick Start​

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()
}],
ldm_width: Some(2.44),
ldm_mode: Some("projection".to_string()),
..Default::default()
};

match client.packing.calculate(request).await {
Ok(result) => {
println!("Total pallets: {}", result.total_pallets);
println!("Total LDM: {}", result.total_ldm);
}
Err(e) => {
eprintln!("Error: {}", e);
}
}

Ok(())
}

SDK Features Comparison​

FeaturePythonJS/TSJavaGoPHPRust
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:

# Create once, reuse many times
client = AlaikisClient(api_key="...")

for _ in range(100):
result = client.packing.calculate(...)

Bad:

# Don't