30. Client REST Web
MALDA può chiamare API HTTP dal runtime host con RestClient e le funzioni one-shot httpGet / httpPost / httpPut / httpDelete / httpPatch. Questo capitolo è il riferimento lato client. Progettare e ospitare quelle API è 29. Server REST API. Il fetch del browser verso un'API MALDA è 31. Sviluppo full-stack con MALDA.
httpGet(url, ...) è il client HTTP di questo capitolo. webFetch è il fetch one-shot dell'host in 12.9. cap.httpGet(origin) crea un token GET non contraffabile per cap.fetch / webFetch — vedi 12.6.
Examples/Web/http_client_json.malda. Parti da 25. Panoramica Web UI. Corso: Imparare MALDA — Dopo il percorso core.
30.1 Mappa del capitolo
- 30.1.1 Primer sui concetti — client HTTP, status vs trasporto, Bearer vs Basic
- 30.2 Costruttore, proprietà e metodi di
RestClient - 30.3 Risoluzione URL, query parameter e body
- 30.4 Risposta di successo vs oggetto di errore di trasporto
- 30.5 Funzioni statiche
httpGet/httpPoste analoghe - 30.6 Autenticazione
- 30.7 Timeout
- 30.8 Redirect e retry
- 30.9 CORS: client host vs browser
- 30.10 Interpret vs transpile
- 30.11 Chiamare un
RestServerMALDA - 30.12 Esempi
30.1.1 Primer sui concetti
Questo capitolo è il chiamante. I termini server (middleware, CSRF, CORS, JWT) stanno in 29.1.1 Primer sui concetti.
Un client HTTP costruisce una richiesta, la invia e legge la risposta. RestClient e httpGet girano sull'host MALDA (non nel browser), quindi ignorano CORS. Gli http* transpilati in JS usano il fetch della pagina, che invece obbedisce a CORS.
Status vs trasporto: un HTTP 404 ha comunque prodotto una risposta — controlla response.status / ok. Se è fallito il livello TCP/TLS/DNS, ottieni un oggetto di errore di trasporto (status di solito 0, error impostato). Vedi 30.4.
Bearer vs Basic: Bearer invia un token così com'è nell'header Authorization. Basic invia username:password in Base64 (la codifica non è cifratura). Nessuno dei due nasconde le credenziali sul filo; usa HTTPS. Vedi 30.6.
Retry idempotenti: GET e PUT di solito si possono ripetere in sicurezza; POST spesso no (può creare una seconda risorsa). Riprova gli errori di trasporto e i 5xx quando il metodo è idempotente; non ritentare alla cieca i 4xx. Vedi 30.8.
30.2 Classe RestClient
Crea un client riusabile quando ti servono un URL di base, header di default, auth o un timeout diverso da 30 secondi. L'implementazione host è RestClientInstance (interprete e transpile C#).
30.2.1 Costruttore
var client = new RestClient(); // No base URL
var client = new RestClient("https://api.example.com"); // With base URL
var client = new RestClient("https://api.example.com", 60000); // With base URL and timeout (ms)
baseUrl(string, opzionale): anteposto agli URL relativi delle richieste. Vuoto se omesso.timeout(int, opzionale):HttpClient.Timeoutin millisecondi. Default:30000.
30.2.2 Proprietà
| Proprietà | Tipo | Note |
|---|---|---|
baseUrl | string | URL di base corrente |
timeout | int | Timeout corrente in millisecondi |
30.2.3 Metodi di richiesta
| Metodo | Argomenti |
|---|---|
get(url, headers?, queryParams?) | Nessun body |
delete(url, headers?, queryParams?) | Nessun body |
post(url, body?, headers?, queryParams?) | Body opzionale |
put(url, body?, headers?, queryParams?) | Body opzionale |
patch(url, body?, headers?, queryParams?) | Body opzionale |
url(string): relativo se è impostatobaseUrl, altrimenti assolutobody(object / string / altro, opzionale): vedi 30.3.3. Inviato solo per POST, PUT e PATCHheaders(object, opzionale): header extra della richiesta. Solo valori stringa. Passanullquando ti servono i query parameter senza headerqueryParams(object, opzionale): aggiunti come query string
30.2.4 Metodi di configurazione
| Metodo | Note |
|---|---|
setHeader(name, value) | Header di default su ogni richiesta successiva (entrambe stringhe) |
setAuth(type, credentials) | Solo "Bearer" o "Basic" (case-insensitive). Altri type vengono memorizzati e ignorati |
setTimeout(ms) | Millisecondi interi; aggiorna l'HttpClient sottostante |
setBaseUrl(url) | Sostituisce l'URL di base |
Non esistono setRetry, flag di redirect né un'API per il cookie jar. Vedi 30.8.
30.3 URL, query e body
30.3.1 Risoluzione URL
Se baseUrl non è vuoto e l'URL della richiesta non inizia con http:// o https://, il client li unisce: toglie lo / finale dalla base, assicura che il path inizi con /, poi concatena. Gli URL http(s) assoluti restano invariati.
var client = new RestClient("https://api.example.com/v1");
// "/users" -> https://api.example.com/v1/users
// "users" -> https://api.example.com/v1/users
// "https://other.example/x" stays absolute
30.3.2 Query parameter
Chiavi e valori dell'oggetto sono URI-encoded e uniti con &. Un ? già presente sull'URL diventa & per le coppie extra. Tipi di valore:
- string: così com'è
- int / float: forma decimale
- bool:
true/false(minuscolo) - qualsiasi altro:
AsString()
30.3.3 Serializzazione del body
POST / PUT / PATCH inviano sempre StringContent con media type application/json, a meno che non sovrascrivi Content-Type negli header della singola richiesta:
- body stringa: inviato come contenuto grezzo (comunque come contenuto JSON, salvo cambio di
Content-Type) - object: oggetto JSON dalle chiavi enumerabili
- altri valori:
JsonSerializerdel valore runtime (gli array diventano array JSON)
Content-Type è l'unico header che deve andare sul content, non su HttpRequestMessage.Headers. Gli altri header personalizzati sono aggiunti alla richiesta; un duplicato di un header già impostato da setAuth o setHeader può far fallire quell'add e venire saltato.
30.4 Formato della risposta
Uno scambio HTTP completato (inclusi 4xx / 5xx) restituisce:
| Campo | Tipo | Note |
|---|---|---|
status | int | Codice di stato HTTP |
statusText | string | Reason phrase ("OK", "Not Found", …) |
ok | bool | True quando lo stato è 200–299 |
headers | object | Header di risposta e di content; valori multipli uniti con ", " |
body | object / array / string | JSON parsato quando Content-Type contiene json e il payload è valido; altrimenti la stringa grezza |
Gli status HTTP di errore producono comunque questa forma. ok è false, ma error è assente. Controlla status, non solo error.
Se la richiesta non ottiene mai una risposta HTTP (DNS, connessione, timeout, send annullato), il client cattura l'eccezione e restituisce invece un oggetto di errore di trasporto:
error(string): messaggio dell'eccezioneok(bool):falsestatus(int): di solito0. Uno status c'è solo quando un'HttpRequestExceptionporta unStatusCodeinData
Gli oggetti di errore di trasporto non hanno body, headers né statusText. I nomi degli header host conservano il casing del server; il path JS fetch spesso li mette in minuscolo (30.10).
30.5 Funzioni HTTP statiche
Queste creano un RestClient nuovo (URL di base vuoto, timeout 30 s, nessun header di default, nessun setAuth) e chiamano il metodo corrispondente:
httpGet(url, headers?, queryParams?)httpPost(url, body?, headers?, queryParams?)httpPut(url, body?, headers?, queryParams?)httpDelete(url, headers?, queryParams?)httpPatch(url, body?, headers?, queryParams?)
Usale per URL assoluti una tantum. Usa un'istanza di RestClient quando più chiamate condividono host, token o timeout. Sul backend JS mappano a mlRuntime.http.get|post|put|delete|patch (fetch) con lo stesso ordine degli argomenti e le stesse forme di successo / errore di trasporto.
Non confonderle con cap.httpGet. Quel built-in di capability crea un token; non esegue la richiesta.
30.6 Autenticazione
setAuth riconosce solo due type (case-insensitive):
Bearer:Authorization: Bearer <credentials>così come passate (nessuna codifica extra)Basic: byte UTF-8 della stringa di credenziali, poi Base64. Passa"username:password"; non fare tu il Base64
var client = new RestClient("https://api.example.com");
client.setAuth("Bearer", "your-token-here");
var response = client.get("/protected-endpoint");
var client = new RestClient("https://api.example.com");
client.setAuth("Basic", "username:password");
var response = client.get("/protected-endpoint");
Qualsiasi altro type viene memorizzato e mai applicato. Per API key o schemi personalizzati, passa un header per-richiesta e non chiamare anche setAuth con un type fittizio:
var headers = {"Authorization": "Custom token123"};
var response = httpGet("https://api.example.com/endpoint", headers);
Gli header di default da setHeader sono applicati prima di setAuth e prima degli header per-richiesta.
30.7 Timeout
Sull'host il timeout è HttpClient.Timeout (costruttore o setTimeout). Allo scadere ottieni un oggetto di errore di trasporto: ok è false, status è 0 e error è il messaggio dell'eccezione (in genere menziona timeout o cancellazione). Le funzioni one-shot http* usano sempre il default di 30 s.
// Set timeout to 60 seconds
var client = new RestClient("https://api.example.com", 60000);
client.setTimeout(10000); // Change to 10 seconds
var response = client.get("/slow-endpoint");
if (!response.ok && response.status == 0) {
print("Transport error: " + response.error);
}
Gli helper JS mlRuntime.http.* non impostano un timeout di abort di fetch. Limita una chiamata JS con @within(ms) se ti serve una deadline lì.
30.8 Redirect e retry
Nessuna delle due superfici espone un'API di redirect o retry.
- Redirect: l'
HttpClienthost segue i redirect di default (auto-redirect dell'handler, tipicamente max 50). IlfetchJS usa il defaultredirect: "follow". Da MALDA non si può disattivare. Lostatusche vedi è la risposta finale dopo la catena di hop, non il 3xx. - Retry: non è built-in. Fai un loop nel programma. Riprova gli errori di trasporto (
status == 0) e i 5xx se l'API è idempotente; non ritentare alla cieca i 4xx.
function getWithRetry(client, url, attempts) {
var i = 0;
var last = null;
while (i < attempts) {
last = client.get(url);
if (last.ok) {
return last;
}
if (last.status > 0 && last.status < 500) {
return last;
}
i = i + 1;
sleep(200);
}
return last;
}
30.9 CORS: host vs browser
RestClient e gli http* interpretati / C# girano sull'host. Non sono un browser, quindi l'algoritmo CORS non si applica. Abilita CORS sul server che chiami solo se i browser lo chiameranno — vedi 29. Server REST API §29.12.
Gli httpGet / httpPost transpilati in JS usano fetch nella pagina. Le chiamate cross-origin richiedono allora che l'API remota consenta origine, metodo e header. Le chiamate same-origin a un'API MALDA montata sullo stesso host (capitolo 31) non necessitano di CORS.
enableCORS lato server non cambia il modo in cui RestClient invia le richieste.
30.10 Interpret vs transpile
- Interprete e transpile C#:
new RestClientehttp*condividonoRestClientInstance. Le chiamate sono sincrone (HttpClient.Send). Header di default,setAuth,setTimeoutesetBaseUrlfunzionano. - Transpile JS:
httpGet/httpPost/httpPut/httpDelete/httpPatchdiventanomlRuntime.http.*(fetch, async). Nel runtime JS non c'è la classeRestClient. Tieni la configurazione di istanza sul lato host /@server(), oppure passa gli header su ogni chiamatahttp*dal codice@client(). - Nomi degli header: le risposte host conservano il casing del server (
Content-Typeè comune). IlfetchJS spesso mette le chiavi in minuscolo. Non assumere la stessa grafia su entrambi i backend. - Timeout: l'host rispetta il timeout di
RestClient; glihttp*JS no (usa@within).
30.11 Chiamare un RestServer MALDA
Un 2xx da RestClient significa che il livello HTTP è andato a buon fine. Il body JSON può comunque essere un envelope del framework MALDA del capitolo 29:
{
"status": 401,
"error": "InvalidToken",
"message": "Invalid token signature.",
"correlationId": "..."
}
- Sui fallimenti leggi
response.body.error/response.body.message/response.body.correlationId. Lo stesso id è suX-Correlation-ID. - I fallimenti di validazione includono
details:{location, field, message}. - Se l'API ha
enableCsrf, le chiamate che mutano servono il cookie CSRF piùX-CSRF-Token(o l'header configurato). Vedi 29.9. - Non trattare un envelope applicativo restituito
{"status": 200, "data": ...}come status HTTP. Lo status HTTP èresponse.status.
Smoke test in loopback nel repo: docs/llm/few-shot/13_http_client.malda (RestServer locale + httpGet / httpPost).
30.12 Esempi
30.12.1 Istanza RestClient
// Create client with base URL
var client = new RestClient("https://api.example.com");
// Set authentication
client.setAuth("Bearer", "your-token-here");
// GET request
var response = client.get("/users");
if (response.ok) {
print("Users: " + toJSON(response.body));
} else {
print("Error: " + response.error);
}
// GET with query parameters
var response = client.get("/users", null, {"limit": "10", "offset": "0"});
// POST request with JSON body
var body = parseJSON("{\"name\": \"Alice\", \"email\": \"alice@example.com\"}");
var response = client.post("/users", body);
if (response.status == 201) {
print("User created: " + toJSON(response.body));
}
// PUT request
var updateData = parseJSON("{\"name\": \"Alice Updated\"}");
var response = client.put("/users/123", updateData);
// DELETE request
var response = client.delete("/users/123");
30.12.2 Funzioni statiche
// Simple GET request
var response = httpGet("https://api.example.com/users");
if (response.ok) {
print("Users: " + toJSON(response.body));
}
// GET with headers
var headers = {"Authorization": "Bearer token123"};
var response = httpGet("https://api.example.com/users", headers);
// GET with query parameters
var response = httpGet("https://api.example.com/users", null, {"limit": "10"});
// POST with JSON body
var body = parseJSON("{\"name\": \"Alice\"}");
var response = httpPost("https://api.example.com/users", body);
// POST with custom headers
var headers = {"Content-Type": "application/json", "X-API-Key": "key123"};
var body = parseJSON("{\"name\": \"Alice\"}");
var response = httpPost("https://api.example.com/users", body, headers);
30.12.3 Errori HTTP vs di trasporto
var response = httpGet("https://api.example.com/users/999");
if (!response.ok) {
if (response.status == 404) {
print("User not found");
} else if (response.error != null) {
print("Error: " + response.error);
} else {
print("HTTP Error: " + response.status + " " + response.statusText);
}
}
30.12.4 Body e header della risposta
var response = httpGet("https://api.example.com/users");
if (response.ok) {
var users = response.body; // Already parsed as object/array if JSON
if (users.length > 0) {
print("First user: " + users[0].name);
}
// Access response headers
var contentType = response.headers["Content-Type"];
print("Content-Type: " + contentType);
}
30.12.5 Walkthrough contro un'API pubblica
// Create REST client
var client = new RestClient("https://jsonplaceholder.typicode.com");
// GET all posts
var response = client.get("/posts");
if (response.ok) {
var posts = response.body;
print("Total posts: " + posts.length);
// GET specific post
var postResponse = client.get("/posts/1");
if (postResponse.ok) {
var post = postResponse.body;
print("Post title: " + post.title);
}
// POST new post
var newPost = parseJSON("{\"title\": \"My Post\", \"body\": \"Content\", \"userId\": 1}");
var createResponse = client.post("/posts", newPost);
if (createResponse.ok) {
print("Created post ID: " + createResponse.body.id);
}
// PUT update post
var update = parseJSON("{\"title\": \"Updated Title\"}");
var updateResponse = client.put("/posts/1", update);
// DELETE post
var deleteResponse = client.delete("/posts/1");
if (deleteResponse.ok) {
print("Post deleted");
}
}
Vedi anche
- 29. Server REST API - Creare server REST API
- 26. Componenti server Web UI - Pattern di integrazione Web UI + API
- 31. Sviluppo full-stack con MALDA - Architettura end-to-end e chiamate API dalla UI
- 12. Input/Output — console, file, path, ambiente,
cap.httpGet