Passa al contenuto principale
Versione: 1.0.0 (beta)

Smart Customer Management API

API Version

Smart Customer Management v1.0.0 (beta)
API basata su OpenAPI 3.1.0 con AI-enhanced metadata

Panoramica

La Smart Customer Management API è un servizio AI-enhanced per la gestione intelligente dei clienti aziendali. Utilizza algoritmi di machine learning per ottimizzare le operazioni CRUD e fornire insights predittivi sui dati dei clienti.

Versione API

Versione attuale: 1.0.0
OpenAPI: 3.1.0
AI-Enhanced: Con metadati AI per ogni endpoint

Caratteristiche principali

  • Gestione clienti intelligente con validazione AI
  • Estensioni AI native per ogni operazione
  • Pattern URL standardizzato multi-tenant
  • Validazione automatica dati cliente
  • Intent recognition per categorizzazione automatica

Endpoint disponibili

Base URL Pattern

/api/\{product\}/\{version\}/company/\{companyId\}/customer

Parametri globali

ParametroTipoDescrizione
productstringIdentificativo del prodotto TSE
versionstringVersione API (es. "v1")
companyIdstringID univoco dell'azienda

Operazioni API

1. Creare un nuovo cliente

Endpoint: POST /api/\{product\}/\{version\}/company/\{companyId\}/customer

AI Metadata:

  • Purpose: customer_creation
  • Entity: Customer
  • Intent: create

Request Body

{
"first-name": "Mario",
"last-name": "Rossi",
"email": "mario.rossi@example.com",
"vat-number": "IT12345678901"
}

Schema dei dati

CampoTipoObbligatorioDescrizione
first-namestringObbligatorioNome del cliente
last-namestringObbligatorioCognome del cliente
emailstringObbligatorioEmail (formato valido)
vat-numberstringObbligatorioPartita IVA cliente

Risposte

CodiceDescrizione
201Cliente creato con successo
400Richiesta non valida

Esempio JavaScript

const createCustomer = async (companyId, customerData) => {
try {
const response = await fetch(`/api/tse/v1/company/${companyId}/customer`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(customerData)
});

if (response.status === 201) {
console.log('Cliente creato con successo');
return await response.json();
}
throw new Error(`Errore ${response.status}`);
} catch (error) {
console.error('Errore creazione cliente:', error);
}
};

// Utilizzo
const nuovoCliente = {
"first-name": "Mario",
"last-name": "Rossi",
"email": "mario.rossi@example.com",
"vat-number": "IT12345678901"
};

await createCustomer("company123", nuovoCliente);

2. Recuperare tutti i clienti

Endpoint: GET /api/\{product\}/\{version\}/company/\{companyId\}/customer

AI Metadata:

  • Purpose: customer_listing
  • Entity: Customer
  • Intent: retrieve

Parametri

Solo i parametri path globali (product, version, companyId).

Risposte

CodiceDescrizione
200Elenco clienti restituito con successo
404Clienti non trovati

Esempio C#

using System.Text.Json;

public async Task<List<Customer>> GetAllCustomersAsync(string companyId)
{
try
{
var url = $"/api/tse/v1/company/{companyId}/customer";
var response = await httpClient.GetAsync(url);

if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var customers = JsonSerializer.Deserialize<List<Customer>>(json);
Console.WriteLine($"Recuperati {customers.Count} clienti");
return customers;
}

throw new HttpRequestException($"Errore {response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($"Errore recupero clienti: {ex.Message}");
return new List<Customer>();
}
}

// Utilizzo
var clienti = await GetAllCustomersAsync("company123");

3. Recuperare un cliente specifico

Endpoint: GET /api/\{product\}/\{version\}/company/\{companyId\}/customer/\{customerId\}

AI Metadata:

  • Purpose: customer_detail
  • Entity: Customer
  • Intent: retrieve

Parametri aggiuntivi

ParametroTipoDescrizione
customerIdstringID univoco del cliente

Risposte

CodiceDescrizione
200Dettagli cliente restituiti con successo
404Cliente non trovato

Esempio Python

import requests
import json

async def get_customer_details(company_id: str, customer_id: str) -> dict:
"""
Recupera i dettagli di un cliente specifico

Args:
company_id: ID dell'azienda
customer_id: ID del cliente

Returns:
dict: Dati del cliente o None se non trovato
"""
try:
url = f"/api/tse/v1/company/{company_id}/customer/{customer_id}"
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
customer_data = response.json()
print(f"Cliente {customer_id} recuperato con successo")
return customer_data
elif response.status_code == 404:
print(f"Cliente {customer_id} non trovato")
return None
else:
raise requests.HTTPError(f"Errore {response.status_code}")

except Exception as e:
print(f"Errore recupero cliente: {e}")
return None

# Utilizzo
cliente = await get_customer_details("company123", "456")

4. Eliminare un cliente

Endpoint: DELETE /api/{product}/{version}/company/{companyId}/customer/{customerId}

AI Metadata:

  • Purpose: customer_deletion
  • Entity: Customer
  • Intent: delete

Parametri

ParametroTipoDescrizione
customerIdstringID del cliente da eliminare

Risposte

CodiceDescrizione
204Cliente eliminato con successo
404Cliente non trovato

Esempio JavaScript con conferma

const deleteCustomer = async (companyId, customerId) => {
// Conferma eliminazione
const confirmed = confirm(`Sei sicuro di voler eliminare il cliente ${customerId}?`);
if (!confirmed) return false;

try {
const response = await fetch(`/api/tse/v1/company/${companyId}/customer/${customerId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});

if (response.status === 204) {
console.log(`Cliente ${customerId} eliminato con successo`);
return true;
} else if (response.status === 404) {
console.warn(`Cliente ${customerId} non trovato`);
return false;
}

throw new Error(`Errore ${response.status}`);
} catch (error) {
console.error('Errore eliminazione cliente:', error);
return false;
}
};

// Utilizzo
const eliminated = await deleteCustomer("company123", "456");

Funzionalità AI integrate

Metadati AI per ogni endpoint

Ogni operazione include metadati AI specifici:

{
"x-ai-purpose": "customer_creation",
"x-ai-entity": "Customer",
"x-ai-intent": "create",
"x-ai-sample": {
"first-name": "Mario",
"last-name": "Rossi",
"email": "mario.rossi@example.com",
"vat-number": "IT12345678901"
}
}

Intent Recognition

IntentDescrizioneEndpoint
createCreazione nuovo clientePOST /customer
retrieveRecupero dati cliente/iGET /customer
deleteEliminazione clienteDELETE /customer/{id}

🔧 Configurazione

Autenticazione

// Setup headers per tutte le richieste
const defaultHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
'X-API-Version': '1.0.0'
};

Gestione errori centralizzata

const handleApiError = (response) => {
switch(response.status) {
case 400:
throw new Error('Dati richiesta non validi');
case 401:
throw new Error('Token di autenticazione non valido');
case 404:
throw new Error('Risorsa non trovata');
case 500:
throw new Error('Errore interno del server');
default:
throw new Error(`Errore API: ${response.status}`);
}
};

Best practices

1. Validazione lato client

const validateCustomerData = (customer) => {
const errors = [];

if (!customer['first-name']?.trim()) {
errors.push('Nome obbligatorio');
}

if (!customer['email']?.includes('@')) {
errors.push('Email non valida');
}

if (!customer['vat-number']?.match(/^[A-Z]{2}\d{11}$/)) {
errors.push('Partita IVA formato non valido');
}

return errors;
};

2. Retry logic per resilienza

const apiCallWithRetry = async (apiCall, maxRetries = 3) => {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await apiCall();
} catch (error) {
if (attempt === maxRetries) throw error;

// Exponential backoff
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};

3. Caching intelligente

const customerCache = new Map();

const getCachedCustomer = async (companyId, customerId) => {
const cacheKey = `${companyId}:${customerId}`;

if (customerCache.has(cacheKey)) {
const cached = customerCache.get(cacheKey);
if (Date.now() - cached.timestamp < 300000) { // 5 minuti
return cached.data;
}
}

const customer = await getCustomerDetails(companyId, customerId);
customerCache.set(cacheKey, {
data: customer,
timestamp: Date.now()
});

return customer;
};

📞 Supporto

Per domande specifiche sulla Smart Customer API: