Manuale di riferimento MALDA™

Il linguaggio di programmazione AI-First - Versione 1.0.50

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.

Non è lo stesso nome: 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.
Stop alla prima lettura. Le chiamate client richiedono la rete. Non possono girare nell'harness degli snippet del manuale. File più piccolo: 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

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)

30.2.2 Proprietà

ProprietàTipoNote
baseUrlstringURL di base corrente
timeoutintTimeout corrente in millisecondi

30.2.3 Metodi di richiesta

MetodoArgomenti
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

30.2.4 Metodi di configurazione

MetodoNote
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:

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:

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:

CampoTipoNote
statusintCodice di stato HTTP
statusTextstringReason phrase ("OK", "Not Found", …)
okboolTrue quando lo stato è 200–299
headersobjectHeader di risposta e di content; valori multipli uniti con ", "
bodyobject / array / stringJSON 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:

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:

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):

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.

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

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": "..."
}

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