Un paquete npm para 128 APIs de datos
dataandapis es el cliente oficial de JavaScript y TypeScript del catálogo. Cada API es una propiedad del cliente y cada endpoint es un método tipado, así que tu editor completa la llamada y nunca armas una URL a mano.
npm install dataandapis- Versión 0.1.0
- Licencia MIT
- Sin dependencias
- import y require
- Node.js 18 o posterior
import { DataAndApis } from "dataandapis";
// reads DATAANDAPIS_API_KEY from the environment
const client = new DataAndApis();
const check = await client.vat.validateVatNumber({
vat: "IE6388047V",
});
console.log(check.valid, check.name);
// true "GOOGLE IRELAND LIMITED"Instalación
npm install dataandapisCon otro gestor de paquetes:
pnpm add dataandapis
yarn add dataandapis
bun add dataandapisInicio rápido
Crea una cuenta gratuita y genera una clave en tu panel. El plan Free incluye 500 tokens al mes y no pide tarjeta; la mayoría de las llamadas cuesta 1 token. Consigue una clave gratuita →
import { DataAndApis } from "dataandapis";
const client = new DataAndApis({ apiKey: process.env.DATAANDAPIS_API_KEY });
const check = await client.vat.validateVatNumber({ vat: "IE6388047V" });
console.log(check.valid, check.name); // true "GOOGLE IRELAND LIMITED"const { DataAndApis } = require("dataandapis");
const client = new DataAndApis({ apiKey: process.env.DATAANDAPIS_API_KEY });
client.vat.validateVatNumber({ vat: "IE6388047V" }).then((check) => {
console.log(check.valid, check.name);
});Si no pasas apiKey, el cliente lee la variable de entorno DATAANDAPIS_API_KEY.
Cómo se nombran las llamadas
La propiedad es la dirección de la API en este sitio en camelCase: /apis/barcode-lookup es client.barcodeLookup. El método es el nombre del endpoint: Lookup By Barcode es lookupByBarcode.
Los parámetros de ruta y de consulta van en un solo objeto. Un cuerpo JSON va en body.
// GET /v1/products/{barcode}: the path parameter goes in the object
const product = await client.barcodeLookup.lookupByBarcode({ barcode: "3017620422003" });
// Query parameters go in the same object
const result = await client.sanctions.screenName({ name: "Viktor Bout", min_score: 0.85 });
// POST: the JSON body goes in "body"
const batch = await client.sanctions.screenNamesBatch({
body: { names: ["Viktor Bout", "Acme Trading LLC"] },
});Cada página de API muestra la llamada exacta de cada uno de sus endpoints, lista para copiar.
Errores
Todo fallo es una instancia de DataAndApisError, con una clase para cada caso.
| Clase | Cuándo |
|---|---|
| AuthenticationError | 401: falta la clave o no es válida |
| PaymentRequiredError | 402: la suscripción tiene un pago pendiente; paymentUrl trae el enlace para pagar |
| QuotaExceededError | 429: se agotaron los tokens del mes |
| ApiError | Cualquier otro estado de error, como 400 o 404 |
| TimeoutError | No hubo respuesta dentro del tiempo de espera |
| ConnectionError | La petición nunca recibió respuesta |
import { ApiError, DataAndApis, QuotaExceededError } from "dataandapis";
try {
await client.barcodeLookup.lookupByBarcode({ barcode: "0000000000000" });
} catch (err) {
if (err instanceof QuotaExceededError) {
// upgrade the plan or wait for the monthly reset
} else if (err instanceof ApiError && err.status === 404) {
console.log("Not in the catalogue:", err.message);
} else {
throw err;
}
}Reintentos, tiempos de espera y saldo de tokens
Las peticiones GET se reintentan hasta dos veces tras un error de red o una respuesta 408, 502, 503 o 504. Las peticiones POST y las respuestas 429 nunca se reintentan. Cada intento tiene un tiempo de espera de 30 segundos. Ambos valores se pueden cambiar para el cliente o para una sola llamada. Las llamadas fallidas no consumen tokens.
Cada respuesta informa cuántos tokens le quedan a tu clave, y onResponse recibe ese número.
const client = new DataAndApis({
timeout: 30_000, // milliseconds per attempt
maxRetries: 2, // retries for GET requests
onResponse: ({ api, status, tokensRemaining }) => {
if (tokensRemaining !== undefined && tokensRemaining < 50) console.warn("Running low on tokens");
},
});
// Or for one call
await client.vat.validateVatNumber({ vat: "FR40303265045" }, { timeout: 45_000, maxRetries: 0 });Endpoints que devuelven un archivo
Los endpoints de imágenes y documentos devuelven un Blob.
import { writeFile } from "node:fs/promises";
const png = await client.qrCodeGenerator.generateQrCode({ data: "https://dataandapis.com", size: 400 });
await writeFile("qr.png", Buffer.from(await png.arrayBuffer()));TypeScript
Los tipos vienen dentro del paquete. Los tipos de respuesta se infieren de una respuesta de ejemplo por endpoint, así que tómalos como guía: un campo puede ser null o faltar con otras entradas. Pasa tu propio tipo como argumento de tipo cuando necesites uno más estricto.
interface Holiday {
date: string;
name: string;
}
const next = await client.publicHolidays.nextHolidays<{ holidays: Holiday[] }>({ country: "MX" });
// Every parameter and response type is exported
import type { VatValidateVatNumberParams, VatValidateVatNumberResponse } from "dataandapis";Dónde funciona
Node.js 18 o posterior; las pruebas corren en Node.js 18, 20, 22 y 25. El paquete solo necesita el fetch integrado, así que Bun, Deno y Cloudflare Workers también deberían funcionar, aunque no forman parte de las pruebas.
Llama a las APIs desde tu servidor. No envían cabeceras CORS, así que el navegador bloquea las peticiones hechas desde una página web, y una clave en el código del front-end quedaría a la vista de cualquier visitante.
Las 128 APIs del paquete
La versión 0.1.0 cubre 128 APIs y 529 endpoints. Busca una API para ver su nombre en el cliente.
- Air Quality API
client.airQuality - Aircraft API
client.aircraft - Aircraft Registrations API
client.aircraftRegistrations - Airlines API
client.airlines - Airport Status API
client.airportStatus - Airports API
client.airports - Animals API
client.animals - Anime API
client.anime - Artworks API
client.artworks - Astronomy API
client.astronomy - Attractions API
client.attractions - BIN & Card Validator API
client.binCardValidator - Baby Names API
client.babyNames - Banks API
client.banks - Barcode Generator API
client.barcodeGenerator - Barcode Lookup API
client.barcodeLookup - Bible Multi-Translation API
client.bibleMultiTranslation - Business Patterns API
client.businessPatterns - Calories Burned API
client.caloriesBurned - Cars API
client.cars - Cats API
client.cats - Chemical Elements API
client.elements - Climate Normals API
client.climateNormals - Cocktails API
client.cocktails - Colors API
client.colors - Company Enrichment API
client.companies - Company Financials API
client.companyFinancials - Continents, Countries And Cities API
client.continentsCountriesAndCities - Country Flags API
client.countryFlags - Country Indicators API
client.countryIndicators - Crypto Price API
client.cryptoPrices - Currency Exchange Rates API
client.currencyRates - DNS & WHOIS Lookup API
client.dnsWhoisLookup - Day In History API
client.dayInHistory - Demographics API
client.demographics - Dictionary API
client.dictionary - Disposable Email Checker API
client.disposableEmailChecker - Dogs API
client.dogs - Drugs API
client.drugs - EV Chargers API
client.evChargers - Earthquakes API
client.earthquakes - Email Validation API
client.emailValidation - Emission Factors API
client.emissionFactors - Emoji API
client.emoji - Federal Contracts API
client.federalContracts - Federal Grants API
client.grants - Federal Register API
client.federalRegister - Food Nutrition Information API
client.foodNutritionInformation - Food Recalls API
client.foodRecalls - Fuel Stations API
client.fuelStations - Geocoding API
client.geocoding - HTML Render
client.htmlRender - Healthcare Providers API
client.healthcareProviders - Hearthstone API
client.hearthstone - Horoscope & Zodiac API
client.horoscopeZodiac - Hospitals API
client.hospitals - Hurricanes API
client.hurricanes - IBAN & SWIFT/BIC Validator API
client.ibanSwiftValidator - IP Intelligence API
client.ipIntelligence - Image to Text API
client.imageToText - Inflation API
client.inflation - Jokes API
client.jokes - Language Detection API
client.languageDetection - Logos API
client.logos - Lorem Ipsum API
client.loremIpsum - Lottery API
client.lottery - Manga, Manhua And Manhwa API
client.mangaManhuaManhwa - Marine Buoys API
client.buoys - Mobile Devices API
client.mobileDevices - Mortgage & Loan Calculator API
client.mortgageLoanCalculator - Motorcycles API
client.motorcycles - Movies & TV API
client.movies - Name Intelligence API
client.nameIntelligence - Nonprofits API
client.nonprofits - Notable People API
client.notablePeople - Novels API
client.novel - Object Detection API
client.objectDetection - Occupations API
client.occupations - Password Generator API
client.passwordGenerator - Phone Number Validation API
client.phoneValidation - Pokemon Unite Pokemons API
client.pokemonUnite - Population API
client.population - Power Plants API
client.powerPlants - Product Recalls API
client.productRecalls - Profanity Filter API
client.profanityFilter - Public Domain Books API
client.books - Public Holidays API
client.publicHolidays - QR Code Generator API
client.qrCodeGenerator - Quotes API
client.quotes - Random Image & Placeholder API
client.randomImage - Random User API
client.randomUser - Recipes API
client.recipes - Riddles API
client.riddles - River Conditions API
client.rivers - SSL Checker Api
client.sslChecker - Salary Benchmarks API
client.salaryBenchmarks - Sales Tax & VAT API
client.salesTaxVat - Sanctions Screening API
client.sanctions - Seaports API
client.seaports - Sentiment Analysis API
client.sentimentAnalysis - Space Launches API
client.spaceLaunches - Spell Check API
client.spellCheck - Stock Tickers API
client.stockTickers - Tariff Codes API
client.tariffCodes - Tech Stack API
client.techStack - Text Embeddings API
client.textEmbeddings - Thesaurus API
client.thesaurus - Tides API
client.tides - Timezone & World Time API
client.timezoneWorldTime - Trading Calendar API
client.tradingCalendar - Traffic Fatalities API
client.trafficFatalities - Translation API
client.translation - Travel Advisories API
client.travelAdvisories - Trending API
client.trending - Trivia API
client.trivia - URL Metadata API
client.urlMetadata - US Lawyers API
client.usLawyers - Unit Converter API
client.unitConverter - Universities API
client.universities - User Agent Parser API
client.userAgentParser - VAT Validation API
client.vat - VIN Decoder API
client.vinDecoder - Vehicle Recalls API
client.vehicleRecalls - Video Games API
client.videoGames - Watches API
client.watches - Weather API
client.weather - Wildfires API
client.wildfires - Zip & Postal Code API
client.zipPostalCode
¿No usas JavaScript?
Todas las APIs son REST con una cabecera X-Api-Key, así que sirve cualquier cliente HTTP. Cada página de API tiene ejemplos en Python, PHP y Go y un documento OpenAPI 3.1.