Esempi di chiamata
L’API dei dati è HTTP e JSON semplice: non serve una libreria dedicata, basta il client HTTP del tuo linguaggio. In ogni esempio:
- la chiave arriva dalla variabile d’ambiente
MANTLE_KEYe l’indirizzo daMANTLE_URL(predefinitohttp://127.0.0.1:7400); - si leggono i prodotti sotto i 20 euro, dal più caro, con la loro categoria;
- si seguono le pagine con
nextCursor; - un errore si riconosce dal
codenella busta{ "error": { "code", "message" } }.
Elenco con filtri e paginazione
Sezione intitolata “Elenco con filtri e paginazione”curl -sg -H "Authorization: Bearer $MANTLE_KEY" \ "${MANTLE_URL:-http://127.0.0.1:7400}/api/Prodotto?prezzo[lt]=20&sort=-prezzo&include=categoriaDettaglio&limit=100"-g (--globoff) serve: senza, curl legge le parentesi quadre di prezzo[lt] come un intervallo e rifiuta l’indirizzo. In alternativa scrivi prezzo%5Blt%5D=20.
const base = process.env.MANTLE_URL ?? "http://127.0.0.1:7400";const key = process.env.MANTLE_KEY;
async function* prodotti() { let cursor; do { const url = new URL("/api/Prodotto", base); url.searchParams.set("prezzo[lt]", "20"); url.searchParams.set("sort", "-prezzo"); url.searchParams.set("include", "categoriaDettaglio"); url.searchParams.set("limit", "100"); if (cursor) url.searchParams.set("cursor", cursor);
const res = await fetch(url, { headers: { Authorization: `Bearer ${key}` } }); const body = await res.json(); if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
yield* body.data; cursor = body.nextCursor; } while (cursor);}
for await (const p of prodotti()) console.log(p.nome, p.prezzo, p.categoriaDettaglio?.nome);import osimport requests
BASE = os.environ.get("MANTLE_URL", "http://127.0.0.1:7400")session = requests.Session()session.headers["Authorization"] = f"Bearer {os.environ['MANTLE_KEY']}"
def prodotti(): params = {"prezzo[lt]": "20", "sort": "-prezzo", "include": "categoriaDettaglio", "limit": 100} while True: res = session.get(f"{BASE}/api/Prodotto", params=params, timeout=10) body = res.json() if not res.ok: raise RuntimeError(f"{res.status_code} {body['error']['code']}: {body['error']['message']}") yield from body["data"] if "nextCursor" not in body: break params["cursor"] = body["nextCursor"]
for p in prodotti(): print(p["nome"], p["prezzo"])import osimport httpx
client = httpx.Client( base_url=os.environ.get("MANTLE_URL", "http://127.0.0.1:7400"), headers={"Authorization": f"Bearer {os.environ['MANTLE_KEY']}"}, timeout=10,)
def prodotti(): params = {"prezzo[lt]": "20", "sort": "-prezzo", "include": "categoriaDettaglio", "limit": 100} while True: res = client.get("/api/Prodotto", params=params) body = res.json() if res.is_error: raise RuntimeError(f"{res.status_code} {body['error']['code']}: {body['error']['message']}") yield from body["data"] if "nextCursor" not in body: break params["cursor"] = body["nextCursor"]
for p in prodotti(): print(p["nome"], p["prezzo"])package main
import ( "encoding/json" "fmt" "log" "net/http" "net/url" "os")
type page struct { Data []map[string]any `json:"data"` NextCursor string `json:"nextCursor"` Error *struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"`}
func main() { base := os.Getenv("MANTLE_URL") if base == "" { base = "http://127.0.0.1:7400" } q := url.Values{"prezzo[lt]": {"20"}, "sort": {"-prezzo"}, "include": {"categoriaDettaglio"}, "limit": {"100"}} for { req, _ := http.NewRequest("GET", base+"/api/Prodotto?"+q.Encode(), nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("MANTLE_KEY")) res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } var p page err = json.NewDecoder(res.Body).Decode(&p) res.Body.Close() if err != nil { log.Fatal(err) } if p.Error != nil { log.Fatalf("%d %s: %s", res.StatusCode, p.Error.Code, p.Error.Message) } for _, row := range p.Data { fmt.Println(row["nome"], row["prezzo"]) } if p.NextCursor == "" { break } q.Set("cursor", p.NextCursor) }}using System.Net.Http.Headers;using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("MANTLE_URL") ?? "http://127.0.0.1:7400";using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("MANTLE_KEY"));
string? cursor = null;do{ var path = "/api/Prodotto?prezzo[lt]=20&sort=-prezzo&include=categoriaDettaglio&limit=100" + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); using var res = await http.GetAsync(path); using var doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync()); var root = doc.RootElement; if (!res.IsSuccessStatusCode) { var e = root.GetProperty("error"); throw new Exception($"{(int)res.StatusCode} {e.GetProperty("code")}: {e.GetProperty("message")}"); } foreach (var p in root.GetProperty("data").EnumerateArray()) Console.WriteLine($"{p.GetProperty("nome")} {p.GetProperty("prezzo")}"); cursor = root.TryGetProperty("nextCursor", out var next) ? next.GetString() : null;} while (cursor is not null);<?php$base = getenv('MANTLE_URL') ?: 'http://127.0.0.1:7400';$params = ['prezzo[lt]' => '20', 'sort' => '-prezzo', 'include' => 'categoriaDettaglio', 'limit' => 100];
do { $ch = curl_init($base . '/api/Prodotto?' . http_build_query($params)); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MANTLE_KEY')], CURLOPT_TIMEOUT => 10, ]); $body = json_decode(curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
if ($status >= 400) { throw new RuntimeException("$status {$body['error']['code']}: {$body['error']['message']}"); } foreach ($body['data'] as $p) { echo $p['nome'], ' ', $p['prezzo'], PHP_EOL; } $params['cursor'] = $body['nextCursor'] ?? null;} while ($params['cursor'] !== null);Le librerie codificano le parentesi quadre come %5B e %5D (prezzo%5Blt%5D=20): Mantle le legge allo stesso modo.
Un conteggio
Sezione intitolata “Un conteggio”curl -s -X POST "${MANTLE_URL:-http://127.0.0.1:7400}/api/Prodotto/aggregate" \ -H "Authorization: Bearer $MANTLE_KEY" \ -H "Content-Type: application/json" \ -d '{"groupBy":["marca"],"metrics":[{"fn":"count"},{"fn":"avg","field":"prezzo"}]}'const res = await fetch(`${base}/api/Prodotto/aggregate`, { method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify({ groupBy: ["marca"], metrics: [{ fn: "count" }, { fn: "avg", field: "prezzo" }] }),});const { data, truncated } = await res.json();res = session.post(f"{BASE}/api/Prodotto/aggregate", json={ "groupBy": ["marca"], "metrics": [{"fn": "count"}, {"fn": "avg", "field": "prezzo"}],}, timeout=10)data = res.json()["data"]res = client.post("/api/Prodotto/aggregate", json={ "groupBy": ["marca"], "metrics": [{"fn": "count"}, {"fn": "avg", "field": "prezzo"}],})data = res.json()["data"]body := strings.NewReader(`{"groupBy":["marca"],"metrics":[{"fn":"count"},{"fn":"avg","field":"prezzo"}]}`)req, _ := http.NewRequest("POST", base+"/api/Prodotto/aggregate", body)req.Header.Set("Authorization", "Bearer "+os.Getenv("MANTLE_KEY"))req.Header.Set("Content-Type", "application/json")res, err := http.DefaultClient.Do(req)using System.Net.Http.Json;
var res = await http.PostAsJsonAsync("/api/Prodotto/aggregate", new{ groupBy = new[] { "marca" }, metrics = new object[] { new { fn = "count" }, new { fn = "avg", field = "prezzo" } },});$ch = curl_init($base . '/api/Prodotto/aggregate');curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MANTLE_KEY'), 'Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode(['groupBy' => ['marca'], 'metrics' => [['fn' => 'count'], ['fn' => 'avg', 'field' => 'prezzo']]]),]);$data = json_decode(curl_exec($ch), true)['data'];Generare un client
Sezione intitolata “Generare un client”Se preferisci classi tipizzate, genera un client dal documento OpenAPI della tua chiave con lo strumento che usi già (openapi-generator, NSwag, oapi-codegen…). Il documento contiene solo le entità e i campi che quella chiave può leggere.