Smart Customer Management API
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 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
| Parametro | Tipo | Descrizione |
|---|---|---|
product | string | Identificativo del prodotto TSE |
version | string | Versione API (es. "v1") |
companyId | string | ID 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
| Campo | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
first-name | string | Obbligatorio | Nome del cliente |
last-name | string | Obbligatorio | Cognome del cliente |
email | string | Obbligatorio | Email (formato valido) |
vat-number | string | Obbligatorio | Partita IVA cliente |
Risposte
| Codice | Descrizione |
|---|---|
201 | Cliente creato con successo |
400 | Richiesta 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
| Codice | Descrizione |
|---|---|
200 | Elenco clienti restituito con successo |
404 | Clienti 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
| Parametro | Tipo | Descrizione |
|---|---|---|
customerId | string | ID univoco del cliente |
Risposte
| Codice | Descrizione |
|---|---|
200 | Dettagli cliente restituiti con successo |
404 | Cliente 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
| Parametro | Tipo | Descrizione |
|---|---|---|
customerId | string | ID del cliente da eliminare |
Risposte
| Codice | Descrizione |
|---|---|
204 | Cliente eliminato con successo |
404 | Cliente 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
| Intent | Descrizione | Endpoint |
|---|---|---|
create | Creazione nuovo cliente | POST /customer |
retrieve | Recupero dati cliente/i | GET /customer |
delete | Eliminazione cliente | DELETE /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;
};
Link correlati
- Getting Started - Setup iniziale
- Autenticazione - Configurazione token
- SDK Overview - Librerie client
- AI Services Overview - Altri servizi AI
📞 Supporto
Per domande specifiche sulla Smart Customer API:
- 📧 Email: smart-services@tse.it
- 📚 Documentazione: TSE Smart Services Hub
- 🐛 Bug Report: GitHub Issues