Documentação

SDK TypeScript/JavaScript

Instalação

Instale o SDK usando npm, yarn ou pnpm:

npm install @countrydataapi/sdk
yarn add @countrydataapi/sdk
pnpm add @countrydataapi/sdk

Início Rápido

import { CountryDataApi } from '@countrydataapi/sdk';

const api = new CountryDataApi({
  apiKey: 'sua-chave-api'
});

// Obter todos os países
const countries = await api.countries.getAll({ lang: 'pt' });
console.log(countries.data);

// Obter país por código ISO
const brasil = await api.countries.getByCode({ code: 'BR' });
console.log(brasil.data[0].country_name); // "Brasil"

Configuração

const api = new CountryDataApi({
  apiKey: 'sua-chave-api',           // Obrigatório
  baseUrl: 'https://api.countrydataapi.com', // Opcional
  timeout: 30000,                    // Opcional (ms)
  defaultLanguage: 'pt'              // Opcional
});

Países

// Obter todos os países
const countries = await api.countries.getAll({
  fields: 'id,country_name,country_flag_svg',
  lang: 'pt',
  limit: 50
});

// Obter país por nome
const brasil = await api.countries.getByName({ name: 'Brazil' });

// Obter país por código ISO (alpha-2, alpha-3 ou numérico)
const country = await api.countries.getByCode({ code: 'BR' });

// Obter países por região
const southAmerican = await api.countries.getByRegion({ region: 'South America' });

// Obter países por moeda
const brlCountries = await api.countries.getByCurrency({ currency: 'BRL' });

// Obter países por idioma
const portugueseSpeaking = await api.countries.getByLanguage({ language: 'por' });

// Obter países por fuso horário
const brasiliaTime = await api.countries.getByTimezone({ timezone: 'America/Sao_Paulo' });

Estados

// Obter todos os estados
const allStates = await api.states.getAll();

// Obter estados por país
const brazilianStates = await api.states.getByCountry({ country: 'Brazil' });

// Obter estados por cidade
const states = await api.states.getByCity({ city: 'São Paulo' });

// Obter estados por CEP
const statesByZip = await api.states.getByZipcode({ zipcode: '01310-100' });

Cidades

// Obter todas as cidades
const allCities = await api.cities.getAll({ limitToken: 100 });

// Obter cidade por nome
const saoPaulo = await api.cities.get({ city: 'São Paulo' });

// Obter cidades por país
const brazilianCities = await api.cities.getByCountry({ country: 'Brazil' });

// Obter cidades por estado
const spCities = await api.cities.getByState({ state: 'São Paulo' });

CEPs

// Obter CEPs por país
const zipcodes = await api.zipcodes.getByCountry({ country: 'Brazil' });

// Obter CEPs por estado
const stateZipcodes = await api.zipcodes.getByState({ state: 'São Paulo' });

// Obter CEPs por região
const southAmericanZipcodes = await api.zipcodes.getByRegion({ region: 'South America' });

Select (Otimizado para Dropdowns)

Estes endpoints custam apenas 1 token independentemente do número de resultados, sendo perfeitos para preencher dropdowns:

// Obter países para dropdown
const countriesSelect = await api.select.countries({ lang: 'pt' });
// Retorna: [{ id: 'BR', name: 'Brasil', code: 'BR', phone_code: '+55', flag: '🇧🇷' }, ...]

// Obter estados para dropdown
const statesSelect = await api.select.states({ country: 'BR' });
// Retorna: [{ id: 'SP', name: 'São Paulo' }, ...]

// Obter cidades para dropdown
const citiesSelect = await api.select.cities({ state: 'São Paulo', country: 'BR' });
// Retorna: [{ id: '01310-100', name: 'São Paulo' }, ...]

Verificar Status de Tokens

const status = await api.getStatus();
console.log(`Tokens restantes: ${status.remainingTokens}`);

Opções de Requisição

Todos os métodos aceitam estas opções comuns:

Opção Tipo Descrição
fields string Lista de campos separados por vírgula para retornar
lang 'en' | 'es' | 'pt' | 'fr' | 'de' | 'it' Idioma da resposta
limit number Número máximo de itens a retornar
limitToken number Máximo de tokens a usar nesta requisição

Tratamento de Erros

import {
  CountryDataApi,
  AuthenticationError,
  InsufficientTokensError
} from '@countrydataapi/sdk';

try {
  const countries = await api.countries.getAll();
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Chave de API inválida');
  } else if (error instanceof InsufficientTokensError) {
    console.error('Sem tokens restantes');
  } else {
    console.error('Erro na API:', error.message);
  }
}

Suporte TypeScript

Suporte completo a TypeScript com todos os tipos exportados:

import type {
  Country,
  State,
  City,
  ApiResponse,
  Language
} from '@countrydataapi/sdk';

const response: ApiResponse<Country> = await api.countries.getByCode({
  code: 'BR'
});

const country: Country = response.data[0];
console.log(country.country_name);

Exemplo React

import { useEffect, useState } from 'react';
import { CountryDataApi, Country } from '@countrydataapi/sdk';

const api = new CountryDataApi({ apiKey: 'sua-chave-api' });

function CountryList() {
  const [countries, setCountries] = useState<Country[]>([]);

  useEffect(() => {
    api.countries.getAll({ limit: 10 })
      .then(response => setCountries(response.data));
  }, []);

  return (
    <ul>
      {countries.map(country => (
        <li key={country.id}>{country.country_name}</li>
      ))}
    </ul>
  );
}

Exemplo Vue

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { CountryDataApi, Country } from '@countrydataapi/sdk';

const api = new CountryDataApi({ apiKey: 'sua-chave-api' });
const countries = ref<Country[]>([]);

onMounted(async () => {
  const response = await api.countries.getAll({ limit: 10 });
  countries.value = response.data;
});
</script>

<template>
  <ul>
    <li v-for="country in countries" :key="country.id">
      {{ country.country_name }}
    </li>
  </ul>
</template>

Links