Um pacote Python para 128 APIs de dados
dataandapis é o cliente oficial em Python para o catálogo. Cada API é um atributo do cliente e cada endpoint é um método com argumentos nomeados, uma docstring e type hints, então seu editor completa a chamada e você nunca monta uma URL à mão.
pip install dataandapis- Versão 0.1.0
- Licença MIT
- Sem dependências
- Type hints incluídos
- Python 3.9 ou superior
from dataandapis import DataAndApis
# reads DATAANDAPIS_API_KEY from the environment
client = DataAndApis()
check = client.vat.validate_vat_number(vat="IE6388047V")
print(check["valid"], check["name"])
# True GOOGLE IRELAND LIMITEDInstalação
pip install dataandapisCom outra ferramenta:
uv add dataandapis
poetry 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 os
from dataandapis import DataAndApis
client = DataAndApis(os.environ["DATAANDAPIS_API_KEY"])
check = client.vat.validate_vat_number(vat="IE6388047V")
print(check["valid"], check["name"]) # True GOOGLE IRELAND LIMITEDSe você omitir a chave, o cliente lê a variável de ambiente DATAANDAPIS_API_KEY.
Como as chamadas são nomeadas
O atributo é o endereço da API neste site em snake case, então /apis/barcode-lookup é client.barcode_lookup. O método é o nome do endpoint em snake case, então Lookup By Barcode é lookup_by_barcode.
Os parâmetros de caminho e de consulta são argumentos nomeados, com exatamente os nomes que a API usa. Um corpo JSON vai em body. Um parâmetro cujo nome é uma palavra reservada do Python recebe um sublinhado no final: from vira from_.
# GET /v1/products/{barcode}: the path parameter is a keyword argument
product = client.barcode_lookup.lookup_by_barcode(barcode="3017620422003")
# Query parameters are keyword arguments too
result = client.sanctions.screen_name(name="Viktor Bout", min_score=0.85)
# A Python keyword takes a trailing underscore: "from" is from_
fx = client.currency_rates.convert(from_="USD", to="GBP", amount=100)
# POST: the JSON body goes in "body"
batch = client.sanctions.screen_names_batch(
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; payment_url 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 |
| ApiTimeoutError | Nenhuma resposta dentro do tempo limite; também é um TimeoutError nativo |
| ApiConnectionError | A requisição não recebeu nenhuma resposta |
from dataandapis import ApiError, DataAndApis, QuotaExceededError
try:
client.barcode_lookup.lookup_by_barcode(barcode="0000000000000")
except QuotaExceededError:
... # upgrade the plan or wait for the monthly reset
except ApiError as err:
if err.status == 404:
print("Not in the catalogue:", err.message)
else:
raiseNovas 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.
O cliente mantém as conexões abertas entre as chamadas, então um loop de consultas não paga por um novo handshake TLS a cada vez. Um mesmo cliente pode ser compartilhado entre threads.
Cada resposta informa quantos tokens restam na sua chave, e on_response recebe esse número.
def watch(info):
if info.tokens_remaining is not None and info.tokens_remaining < 50:
print("Running low on tokens")
client = DataAndApis(
timeout=30, # seconds per attempt
max_retries=2, # retries for GET requests
on_response=watch,
)
# Or for one call
client.vat.validate_vat_number(
vat="FR40303265045",
options={"timeout": 45, "max_retries": 0},
)Endpoints que retornam um arquivo
Endpoints de imagem e de documento retornam bytes.
png = client.qr_code_generator.generate_qr_code(data="https://dataandapis.com", size=400)
with open("qr.png", "wb") as f:
f.write(png)Type hints
Os type hints vêm com o pacote, então o mypy e o Pyright verificam suas chamadas e seu editor completa as chaves de uma resposta. 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 None ou estar ausente para outras entradas.
from dataandapis.types import VatValidateVatNumberResponse
def is_valid(check: VatValidateVatNumberResponse) -> bool:
return check["valid"]asyncio
O cliente é síncrono. Em código assíncrono, execute a chamada em uma thread de trabalho.
import asyncio
check = await asyncio.to_thread(client.vat.validate_vat_number, vat="IE6388047V")Onde ele roda
Python 3.9 ou superior; os testes rodam no Python 3.9, 3.13 e 3.14. O pacote usa apenas a biblioteca padrão, então não há mais nada para instalar.
Mantenha sua chave no servidor: em uma variável de ambiente ou em um gerenciador de segredos, não em código que é enviado aos usuários.
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.air_quality - Aircraft API
client.aircraft - Aircraft Registrations API
client.aircraft_registrations - Airlines API
client.airlines - Airport Status API
client.airport_status - 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.bin_card_validator - Baby Names API
client.baby_names - Banks API
client.banks - Barcode Generator API
client.barcode_generator - Barcode Lookup API
client.barcode_lookup - Bible Multi-Translation API
client.bible_multi_translation - Business Patterns API
client.business_patterns - Calories Burned API
client.calories_burned - Cars API
client.cars - Cats API
client.cats - Chemical Elements API
client.elements - Climate Normals API
client.climate_normals - Cocktails API
client.cocktails - Colors API
client.colors - Company Enrichment API
client.companies - Company Financials API
client.company_financials - Continents, Countries And Cities API
client.continents_countries_and_cities - Country Flags API
client.country_flags - Country Indicators API
client.country_indicators - Crypto Price API
client.crypto_prices - Currency Exchange Rates API
client.currency_rates - DNS & WHOIS Lookup API
client.dns_whois_lookup - Day In History API
client.day_in_history - Demographics API
client.demographics - Dictionary API
client.dictionary - Disposable Email Checker API
client.disposable_email_checker - Dogs API
client.dogs - Drugs API
client.drugs - EV Chargers API
client.ev_chargers - Earthquakes API
client.earthquakes - Email Validation API
client.email_validation - Emission Factors API
client.emission_factors - Emoji API
client.emoji - Federal Contracts API
client.federal_contracts - Federal Grants API
client.grants - Federal Register API
client.federal_register - Food Nutrition Information API
client.food_nutrition_information - Food Recalls API
client.food_recalls - Fuel Stations API
client.fuel_stations - Geocoding API
client.geocoding - HTML Render
client.html_render - Healthcare Providers API
client.healthcare_providers - Hearthstone API
client.hearthstone - Horoscope & Zodiac API
client.horoscope_zodiac - Hospitals API
client.hospitals - Hurricanes API
client.hurricanes - IBAN & SWIFT/BIC Validator API
client.iban_swift_validator - IP Intelligence API
client.ip_intelligence - Image to Text API
client.image_to_text - Inflation API
client.inflation - Jokes API
client.jokes - Language Detection API
client.language_detection - Logos API
client.logos - Lorem Ipsum API
client.lorem_ipsum - Lottery API
client.lottery - Manga, Manhua And Manhwa API
client.manga_manhua_manhwa - Marine Buoys API
client.buoys - Mobile Devices API
client.mobile_devices - Mortgage & Loan Calculator API
client.mortgage_loan_calculator - Motorcycles API
client.motorcycles - Movies & TV API
client.movies - Name Intelligence API
client.name_intelligence - Nonprofits API
client.nonprofits - Notable People API
client.notable_people - Novels API
client.novel - Object Detection API
client.object_detection - Occupations API
client.occupations - Password Generator API
client.password_generator - Phone Number Validation API
client.phone_validation - Pokemon Unite Pokemons API
client.pokemon_unite - Population API
client.population - Power Plants API
client.power_plants - Product Recalls API
client.product_recalls - Profanity Filter API
client.profanity_filter - Public Domain Books API
client.books - Public Holidays API
client.public_holidays - QR Code Generator API
client.qr_code_generator - Quotes API
client.quotes - Random Image & Placeholder API
client.random_image - Random User API
client.random_user - Recipes API
client.recipes - Riddles API
client.riddles - River Conditions API
client.rivers - SSL Checker Api
client.ssl_checker - Salary Benchmarks API
client.salary_benchmarks - Sales Tax & VAT API
client.sales_tax_vat - Sanctions Screening API
client.sanctions - Seaports API
client.seaports - Sentiment Analysis API
client.sentiment_analysis - Space Launches API
client.space_launches - Spell Check API
client.spell_check - Stock Tickers API
client.stock_tickers - Tariff Codes API
client.tariff_codes - Tech Stack API
client.tech_stack - Text Embeddings API
client.text_embeddings - Thesaurus API
client.thesaurus - Tides API
client.tides - Timezone & World Time API
client.timezone_world_time - Trading Calendar API
client.trading_calendar - Traffic Fatalities API
client.traffic_fatalities - Translation API
client.translation - Travel Advisories API
client.travel_advisories - Trending API
client.trending - Trivia API
client.trivia - URL Metadata API
client.url_metadata - US Lawyers API
client.us_lawyers - Unit Converter API
client.unit_converter - Universities API
client.universities - User Agent Parser API
client.user_agent_parser - VAT Validation API
client.vat - VIN Decoder API
client.vin_decoder - Vehicle Recalls API
client.vehicle_recalls - Video Games API
client.video_games - Watches API
client.watches - Weather API
client.weather - Wildfires API
client.wildfires - Zip & Postal Code API
client.zip_postal_code
Não usa Python?
JavaScript e TypeScript têm seu próprio pacote: npm 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.