API de URLW en JavaScript: integración completa con Node.js y fetch

Integre la API de URLW en su aplicación Node.js o JavaScript. Código completo con fetch, gestión de errores y ejemplos de automatización. Guía para desarrolladores.

Tanto si construye un backend Node.js, un worker de Cloudflare o un script de automatización, integrar la API de URLW en JavaScript es rápido y sin dependencias externas. Aquí tiene una guía completa con código listo para desplegar.

Configuración y autenticación

La API de URLW se autentica mediante un Bearer token en los encabezados HTTP. En Node.js, almacene su clave API en una variable de entorno:

# En su archivo .env (¡nunca versionado!)
URLW_API_KEY=su_clave_api_aqui
// 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 variable de entorno URLW_API_KEY es obligatoria');
}

module.exports = { URLW_API_BASE, URLW_API_KEY };

Acortar una URL con fetch en Node.js

Aquí tiene una clase UrlwClient completa utilizando la API fetch nativa (disponible en 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(
    `Error API URLW (${response.status}): ${error.message || 'Error desconocido'}`
  );
}

return response.json();
}

async getStats(linkId) {
const response = await fetch(`${this.baseUrl}/links/${linkId}/stats`, {
  headers: this.headers,
});

if (!response.ok) {
  throw new Error(`No se pueden obtener las estadísticas: 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(`Error al obtener los enlaces: HTTP ${response.status}`);
}

return response.json();
}
}

module.exports = UrlwClient;

Ejemplo de uso práctico

Aquí se muestra cómo utilizar este cliente en un script Node.js:

// main.js
const UrlwClient = require('./urlw-client');

async function main() {
const client = new UrlwClient();

try {
// Crear un enlace corto con un slug personalizado
const link = await client.shorten(
  'https://ejemplo.com/articulo-muy-largo-con-parametros?utm_source=newsletter',
  {
    slug: 'articulo-junio',
    domain: 'go.su-marca.es',
  }
);

console.log('Enlace corto:', link.short_url);
console.log('ID del enlace:', link.id);

// Obtener las estadísticas 24h después
const stats = await client.getStats(link.id);
console.log(`Clics: ${stats.total_clicks} (${stats.unique_clicks} únicos)`);

} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
}

main();

Gestión de errores y reintento automático

Para una aplicación en producción, implemente un mecanismo de reintento con backoff exponencial para gestionar errores transitorios y límites de tasa:

async function withRetry(fn, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
  return await fn();
} catch (error) {
  if (attempt === maxRetries) throw error;

  // Esperar antes de reintentar: 1s, 2s, 4s...
  const delayMs = Math.pow(2, attempt - 1) * 1000;
  console.warn(`Intento ${attempt} fallido, reintentando en ${delayMs}ms`);
  await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}

// Uso
const link = await withRetry(() => client.shorten('https://ejemplo.com/pagina'));

Para uso en TypeScript, las interfaces y tipos de la API de URLW están disponibles en la documentación oficial. Para empezar, cree su cuenta URLW y genere su clave API.

Pruebe URLW gratis

50 enlaces cortos, API REST incluida, sin tarjeta de crédito.