API URLW in JavaScript: integrazione Node.js completa con fetch
Integrate l'API URLW nella vostra applicazione Node.js o JavaScript. Codice completo con fetch, gestione degli errori ed esempi di automazione. Guida sviluppatore.
Che stiate costruendo un backend Node.js, un worker Cloudflare o uno script di automazione, integrare l'API URLW in JavaScript è rapido e senza dipendenze esterne. Ecco una guida completa con codice pronto al deployment.
Configurazione e autenticazione
L'API URLW si autentica tramite un Bearer token negli header HTTP. In Node.js, archiviate la vostra chiave API in una variabile d'ambiente:
# Nel vostro file .env (mai versionato!)
URLW_API_KEY=la_vostra_chiave_api_qui
// config.js
const URLW_API_BASE = 'https://urlw.fr/api/v1';
const URLW_API_KEY = process.env.URLW_API_KEY;
if (!URLW_API_KEY) {
throw new Error('La variabile d\'ambiente URLW_API_KEY è richiesta');
}
module.exports = { URLW_API_BASE, URLW_API_KEY };
Abbreviare un URL con fetch in Node.js
Ecco una classe UrlwClient completa che utilizza l'API fetch nativa (disponibile in Node.js 18+):
// urlw-client.js
const { URLW_API_BASE, URLW_API_KEY } = require('./config');
class UrlwClient {
constructor(apiKey = URLW_API_KEY) {
this.apiKey = apiKey;
this.baseUrl = URLW_API_BASE;
}
get headers() {
return {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
};
}
async shorten(url, options = {}) {
const body = { url, ...options };
const response = await fetch(`${this.baseUrl}/links`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(body),
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(
`Errore API URLW (${response.status}): ${error.message || 'Errore sconosciuto'}`
);
}
return response.json();
}
async getStats(linkId) {
const response = await fetch(`${this.baseUrl}/links/${linkId}/stats`, {
headers: this.headers,
});
if (!response.ok) {
throw new Error(`Impossibile recuperare le statistiche: HTTP ${response.status}`);
}
return response.json();
}
async list(page = 1, limit = 50) {
const params = new URLSearchParams({ page, limit });
const response = await fetch(`${this.baseUrl}/links?${params}`, {
headers: this.headers,
});
if (!response.ok) {
throw new Error(`Errore durante il recupero dei link: HTTP ${response.status}`);
}
return response.json();
}
}
module.exports = UrlwClient;
Esempio di utilizzo pratico
Ecco come utilizzare questo client in uno script Node.js:
// main.js
const UrlwClient = require('./urlw-client');
async function main() {
const client = new UrlwClient();
try {
// Creare un link breve con slug personalizzato
const link = await client.shorten(
'https://esempio.com/articolo-molto-lungo-con-parametri?utm_source=newsletter',
{
slug: 'articolo-giugno',
domain: 'go.vostro-brand.it',
}
);
console.log('Link breve:', link.short_url);
console.log('ID del link:', link.id);
// Recuperare le statistiche 24h dopo
const stats = await client.getStats(link.id);
console.log(`Clic: ${stats.total_clicks} (${stats.unique_clicks} unici)`);
} catch (error) {
console.error('Errore:', error.message);
process.exit(1);
}
}
main();
Gestione degli errori e retry automatico
Per un'applicazione in produzione, implementate un meccanismo di retry con backoff esponenziale per gestire gli errori transitori e i rate limit:
async function withRetry(fn, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries) throw error;
// Attendere prima di riprovare: 1s, 2s, 4s...
const delayMs = Math.pow(2, attempt - 1) * 1000;
console.warn(`Tentativo ${attempt} fallito, nuovo tentativo tra ${delayMs}ms`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}
// Utilizzo
const link = await withRetry(() => client.shorten('https://esempio.com/pagina'));
Per un utilizzo TypeScript, le interfacce e i tipi dell'API URLW sono disponibili nella documentazione ufficiale. Per iniziare, create il vostro account URLW e generate la vostra chiave API.
Prova URLW gratuitamente
50 link brevi, API REST inclusa, nessuna carta di credito richiesta.