Installez le SDK avec npm, yarn ou pnpm :
npm install @countrydataapi/sdk
yarn add @countrydataapi/sdk
pnpm add @countrydataapi/sdk
import { CountryDataApi } from '@countrydataapi/sdk';
const api = new CountryDataApi({
apiKey: 'votre-cle-api'
});
// Obtenir tous les pays
const countries = await api.countries.getAll({ lang: 'fr' });
console.log(countries.data);
// Obtenir un pays par code ISO
const france = await api.countries.getByCode({ code: 'FR' });
console.log(france.data[0].country_name); // "France"
const api = new CountryDataApi({
apiKey: 'votre-cle-api', // Obligatoire
baseUrl: 'https://api.countrydataapi.com', // Optionnel
timeout: 30000, // Optionnel (ms)
defaultLanguage: 'fr' // Optionnel
});
// Obtenir tous les pays
const countries = await api.countries.getAll({
fields: 'id,country_name,country_flag_svg',
lang: 'fr',
limit: 50
});
// Obtenir un pays par nom
const france = await api.countries.getByName({ name: 'France' });
// Obtenir un pays par code ISO (alpha-2, alpha-3 ou numérique)
const country = await api.countries.getByCode({ code: 'FR' });
// Obtenir des pays par région
const european = await api.countries.getByRegion({ region: 'Europe' });
// Obtenir des pays par devise
const euroCountries = await api.countries.getByCurrency({ currency: 'EUR' });
// Obtenir des pays par langue
const frenchSpeaking = await api.countries.getByLanguage({ language: 'fra' });
// Obtenir des pays par fuseau horaire
const parisTime = await api.countries.getByTimezone({ timezone: 'Europe/Paris' });
// Obtenir tous les états/régions
const allStates = await api.states.getAll();
// Obtenir les régions par pays
const frenchRegions = await api.states.getByCountry({ country: 'France' });
// Obtenir les régions par ville
const states = await api.states.getByCity({ city: 'Paris' });
// Obtenir les régions par code postal
const statesByZip = await api.states.getByZipcode({ zipcode: '75001' });
// Obtenir toutes les villes
const allCities = await api.cities.getAll({ limitToken: 100 });
// Obtenir une ville par nom
const paris = await api.cities.get({ city: 'Paris' });
// Obtenir les villes par pays
const frenchCities = await api.cities.getByCountry({ country: 'France' });
// Obtenir les villes par région
const ileDeFranceCities = await api.cities.getByState({ state: 'Île-de-France' });
// Obtenir les codes postaux par pays
const zipcodes = await api.zipcodes.getByCountry({ country: 'France' });
// Obtenir les codes postaux par région
const stateZipcodes = await api.zipcodes.getByState({ state: 'Île-de-France' });
// Obtenir les codes postaux par région géographique
const europeanZipcodes = await api.zipcodes.getByRegion({ region: 'Europe' });
Ces endpoints ne coûtent que 1 token quel que soit le nombre de résultats, parfaits pour remplir des listes déroulantes :
// Obtenir les pays pour liste déroulante
const countriesSelect = await api.select.countries({ lang: 'fr' });
// Retourne: [{ id: 'FR', name: 'France', code: 'FR', phone_code: '+33', flag: '🇫🇷' }, ...]
// Obtenir les régions pour liste déroulante
const statesSelect = await api.select.states({ country: 'FR' });
// Retourne: [{ id: 'IDF', name: 'Île-de-France' }, ...]
// Obtenir les villes pour liste déroulante
const citiesSelect = await api.select.cities({ state: 'Île-de-France', country: 'FR' });
// Retourne: [{ id: '75001', name: 'Paris' }, ...]
const status = await api.getStatus();
console.log(`Tokens restants: ${status.remainingTokens}`);
Toutes les méthodes acceptent ces options communes :
| Option | Type | Description |
|---|---|---|
fields |
string |
Liste de champs séparés par des virgules à retourner |
lang |
'en' | 'es' | 'pt' | 'fr' | 'de' | 'it' |
Langue de la réponse |
limit |
number |
Nombre maximum d'éléments à retourner |
limitToken |
number |
Maximum de tokens à utiliser pour cette requête |
import {
CountryDataApi,
AuthenticationError,
InsufficientTokensError
} from '@countrydataapi/sdk';
try {
const countries = await api.countries.getAll();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Clé API invalide');
} else if (error instanceof InsufficientTokensError) {
console.error('Plus de tokens disponibles');
} else {
console.error('Erreur API:', error.message);
}
}
Support complet TypeScript avec tous les types exportés :
import type {
Country,
State,
City,
ApiResponse,
Language
} from '@countrydataapi/sdk';
const response: ApiResponse<Country> = await api.countries.getByCode({
code: 'FR'
});
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: 'votre-cle-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>
);
}
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { CountryDataApi, Country } from '@countrydataapi/sdk';
const api = new CountryDataApi({ apiKey: 'votre-cle-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>