Um pacote npm para 128 APIs de dados
dataandapis é o cliente oficial em JavaScript e TypeScript para o catálogo. Cada API é uma propriedade do cliente e cada endpoint é um método tipado, então seu editor completa a chamada e você nunca monta uma URL à mão.
npm install dataandapis- Versão 0.1.0
- Licença MIT
- Sem dependências
- import e require
- Node.js 18 ou superior
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"Instalação
npm install dataandapisCom outro gerenciador de pacotes:
pnpm add dataandapis
yarn add dataandapis
bun add dataandapisInício rápido
Crie uma conta gratuita e gere uma chave no seu painel. O plano Free inclui 500 tokens por mês e não exige cartão; a maioria das chamadas custa 1 token. Obter uma chave de API 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);
});Se você omitir apiKey, o cliente lê a variável de ambiente DATAANDAPIS_API_KEY.
Como as chamadas são nomeadas
A propriedade é o endereço da API neste site em camelCase, então /apis/barcode-lookup é client.barcodeLookup. O método é o nome do endpoint, então Lookup By Barcode é lookupByBarcode.
Os parâmetros de caminho e de consulta vão em um único objeto. Um corpo JSON vai em 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 mostra a chamada exata para cada um dos seus endpoints, pronta para copiar.
Erros
Toda falha é uma instância de DataAndApisError, com uma classe para cada caso.
| Classe | Quando |
|---|---|
| AuthenticationError | 401: a chave está ausente ou não é válida |
| PaymentRequiredError | 402: a assinatura está com o pagamento em atraso; paymentUrl contém o link para pagar |
| QuotaExceededError | 429: a cota mensal de tokens foi esgotada |
| ApiError | Qualquer outro status de erro, como 400 ou 404 |
| TimeoutError | Nenhuma resposta dentro do tempo limite |
| ConnectionError | A requisição não recebeu nenhuma resposta |
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;
}
}Novas tentativas, tempos limite e saldo de tokens
Requisições GET são repetidas até duas vezes após um erro de rede ou uma resposta 408, 502, 503 ou 504. Requisições POST e respostas 429 nunca são repetidas. Cada tentativa tem um tempo limite de 30 segundos. Os dois números podem ser alterados para o cliente ou para uma única chamada. Chamadas que falham não consomem tokens.
Cada resposta informa quantos tokens restam na sua chave, e onResponse recebe esse 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 retornam um arquivo
Endpoints de imagem e de documento resolvem para um 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
Os tipos vêm com o pacote. Os tipos de resposta são inferidos a partir de uma resposta de exemplo por endpoint, então trate-os como um guia: um campo pode ser null ou estar ausente para outras entradas. Passe seu próprio tipo como argumento de tipo quando precisar de um mais restrito.
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";Onde ele roda
Node.js 18 ou superior; os testes rodam no Node.js 18, 20, 22 e 25. O pacote só precisa do fetch nativo, então Bun, Deno e Cloudflare Workers também devem funcionar, embora não façam parte da execução dos testes.
Chame as APIs a partir do seu servidor. Elas não enviam cabeçalhos CORS, então o navegador bloqueia requisições feitas a partir de uma página web, e uma chave no código de front-end ficaria visível para todos os visitantes.
Todas as 128 APIs do pacote
A versão 0.1.0 cobre 128 APIs e 529 endpoints. Busque uma API para ver o nome dela no 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
Não usa JavaScript?
O Python tem seu próprio pacote: pip install dataandapis. Toda API também é REST puro com um cabeçalho X-Api-Key, então qualquer cliente HTTP funciona, e cada página de API tem exemplos em PHP e Go e um documento OpenAPI 3.1.