Instala el SDK usando npm, yarn o pnpm:
npm install @countrydataapi/sdk
yarn add @countrydataapi/sdk
pnpm add @countrydataapi/sdk
import { CountryDataApi } from '@countrydataapi/sdk';
const api = new CountryDataApi({
apiKey: 'tu-api-key'
});
// Obtener todos los países
const countries = await api.countries.getAll({ lang: 'es' });
console.log(countries.data);
// Obtener país por código ISO
const spain = await api.countries.getByCode({ code: 'ES' });
console.log(spain.data[0].country_name); // "España"
const api = new CountryDataApi({
apiKey: 'tu-api-key', // Requerido
baseUrl: 'https://api.countrydataapi.com', // Opcional
timeout: 30000, // Opcional (ms)
defaultLanguage: 'es' // Opcional
});
// Obtener todos los países
const countries = await api.countries.getAll({
fields: 'id,country_name,country_flag_svg',
lang: 'es',
limit: 50
});
// Obtener país por nombre
const spain = await api.countries.getByName({ name: 'España' });
// Obtener país por código ISO (alpha-2, alpha-3, o numérico)
const country = await api.countries.getByCode({ code: 'ES' });
// Obtener países por región
const europeos = await api.countries.getByRegion({ region: 'Europe' });
// Obtener países por moneda
const paisesEuro = await api.countries.getByCurrency({ currency: 'EUR' });
// Obtener países por idioma
const hispanohablantes = await api.countries.getByLanguage({ language: 'spa' });
// Obtener países por zona horaria
const paisesUTC = await api.countries.getByTimezone({ timezone: 'UTC' });
// Obtener todos los estados
const todosEstados = await api.states.getAll();
// Obtener estados por país
const estadosEspana = await api.states.getByCountry({ country: 'Spain' });
// Obtener estados por ciudad
const estados = await api.states.getByCity({ city: 'Madrid' });
// Obtener estados por código postal
const estadosPorZip = await api.states.getByZipcode({ zipcode: '28001' });
// Obtener todas las ciudades
const todasCiudades = await api.cities.getAll({ limitToken: 100 });
// Obtener ciudad por nombre
const madrid = await api.cities.get({ city: 'Madrid' });
// Obtener ciudades por país
const ciudadesEspana = await api.cities.getByCountry({ country: 'Spain' });
// Obtener ciudades por estado
const ciudadesMadrid = await api.cities.getByState({ state: 'Madrid' });
// Obtener códigos postales por país
const codigosPostales = await api.zipcodes.getByCountry({ country: 'Spain' });
// Obtener códigos postales por estado
const codigosEstado = await api.zipcodes.getByState({ state: 'Madrid' });
// Obtener códigos postales por región
const codigosEuropa = await api.zipcodes.getByRegion({ region: 'Europe' });
Estos endpoints cuestan solo 1 token sin importar la cantidad de resultados, perfectos para poblar dropdowns:
// Obtener países para dropdown
const paisesSelect = await api.select.countries({ lang: 'es' });
// Retorna: [{ id: 'ES', name: 'España', code: 'ES', phone_code: '+34', flag: '🇪🇸' }, ...]
// Obtener estados para dropdown
const estadosSelect = await api.select.states({ country: 'ES' });
// Retorna: [{ id: 'MD', name: 'Madrid' }, ...]
// Obtener ciudades para dropdown
const ciudadesSelect = await api.select.cities({ state: 'Madrid', country: 'ES' });
// Retorna: [{ id: '28001', name: 'Madrid' }, ...]
const status = await api.getStatus();
console.log(`Tokens restantes: ${status.remainingTokens}`);
Todos los métodos aceptan estas opciones comunes:
| Opción | Tipo | Descripción |
|---|---|---|
fields |
string |
Lista de campos separados por comas |
lang |
'en' | 'es' | 'pt' | 'fr' | 'de' | 'it' |
Idioma de respuesta |
limit |
number |
Número máximo de elementos |
limitToken |
number |
Máximo de tokens a usar |
import {
CountryDataApi,
AuthenticationError,
InsufficientTokensError
} from '@countrydataapi/sdk';
try {
const countries = await api.countries.getAll();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('API key inválida');
} else if (error instanceof InsufficientTokensError) {
console.error('Sin tokens disponibles');
} else {
console.error('Error de API:', error.message);
}
}
Soporte completo de TypeScript con todos los tipos exportados:
import type {
Country,
State,
City,
ApiResponse,
Language
} from '@countrydataapi/sdk';
const response: ApiResponse<Country> = await api.countries.getByCode({
code: 'ES'
});
const country: Country = response.data[0];
console.log(country.country_name);
import { useEffect, useState } from 'react';
import { CountryDataApi, Country } from '@countrydataapi/sdk';
const api = new CountryDataApi({ apiKey: 'tu-api-key' });
function ListaPaises() {
const [countries, setCountries] = useState<Country[]>([]);
useEffect(() => {
api.countries.getAll({ limit: 10, lang: 'es' })
.then(response => setCountries(response.data));
}, []);
return (
<ul>
{countries.map(country => (
<li key={country.id}>{country.country_name}</li>
))}
</ul>
);
}
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { CountryDataApi, Country } from '@countrydataapi/sdk';
const api = new CountryDataApi({ apiKey: 'tu-api-key' });
const countries = ref<Country[]>([]);
onMounted(async () => {
const response = await api.countries.getAll({ limit: 10, lang: 'es' });
countries.value = response.data;
});
</script>
<template>
<ul>
<li v-for="country in countries" :key="country.id">
{{ country.country_name }}
</li>
</ul>
</template>