Todos los Paises
Descripcion general
El endpoint de Todos los Paises devuelve una lista completa de todos los paises registrados en la base de datos de CountryDataAPI. Con mas de 200 paises disponibles, este endpoint es perfecto para construir selectores de paises, analisis de datos geograficos y aplicaciones globales.
Autenticacion
Todas las solicitudes requieren una clave API pasada como parametro de consulta. Puedes obtener tu clave API registrandote en CountryDataAPI.
Peticion
HTTP GET
https://api.countrydataapi.com/v1/countries/all
Devuelve una lista de todos los paises registrados.
Hay 4 tipos de operaciones:
BASIC: Devuelve los campos id, lang, country_name, country_short_iso, country_phone_code, country_cca2, country_ccn3, country_cca3, country_cioc.
NORMAL: Devuelve los campos anteriores y anade country_independent, country_status, country_unMember, country_flag, country_map_googleMaps, country_map_openStreetMaps, country_fifa, country_flag_png, country_flag_svg, country_flag_alt, country_coatOfArms_png, country_coatOfArms_svg, country_startofWeek, country_continent_code, country_current_currency, country_GDP, country_location, country_land, country_terrain, country_climate, country_natural_hazards, country_note, country_history, country_GDP_per_capita_PPP, country_life_expectancy, country_median_age, country_birth_rate, country_death_rate, country_sex_ratio, country_literacy, country_roadways, country_airports, country_railways, country_waterways, country_heliports, country_airports_paved, country_wikipedia_url.
ADVANCED: Devuelve los campos anteriores y anade country_car_info, country_idd_info.
ALL: Devuelve los campos anteriores y anade country_tld, country_capital, country_altSpellings, country_latLng, country_borders, country_timezones, country_continents, country_currencies, country_languages, country_translations, country_capital_info, country_demonyms, country_name_additional_info.
Cada peticion BASIC consumira 1 tokens.
Cada peticion NORMAL consumira 2 tokens.
Cada peticion ADVANCED consumira 3 tokens.
Cada peticion ALL consumira 4 tokens.
Parametros de consulta
| Parametro | Tipo | Descripcion |
|---|---|---|
| apikey | requerido, token | Clave API de autenticacion de tu cuenta |
| limit | opcional, numero | 100 (por defecto). Numero maximo de paises a devolver |
| limitToken | opcional, numero | 1000 (por defecto). Numero maximo de tokens que deseas gastar en esta peticion |
| fields | opcional, string | id,lang,country_name (por defecto). Campos esperados en la respuesta |
| lang | opcional, lang | en (por defecto). Idioma esperado de la respuesta |
Respuesta
Ejemplo de respuesta
[
{
"id": "a0436505-66a2-4e7a-8010-9a003d59e786",
"lang": "en",
"country_name": "Afghanistan",
"country_short_iso": "AF",
"country_phone_code": "93",
"country_cca2": "AF",
"country_ccn3": "004",
"country_cca3": "AFG",
"country_cioc": "AFG"
},
{
"id": "33be30c5-80fc-429d-bf10-bd11f2e3e84c",
"lang": "en",
"country_name": "Albania",
"country_short_iso": "AL",
"country_phone_code": "355",
"country_cca2": "AL",
"country_ccn3": "008",
"country_cca3": "ALB",
"country_cioc": "ALB"
}
]
Ejemplos de codigo
cURL
curl -X GET "https://api.countrydataapi.com/v1/countries/all?apikey=YOUR_API_KEY&limit=10"
JavaScript (Fetch)
const API_KEY = 'YOUR_API_KEY';
async function getAllCountries() {
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/countries/all?apikey=${API_KEY}&limit=100`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const countries = await response.json();
console.log(countries);
return countries;
} catch (error) {
console.error('Error fetching countries:', error);
throw error;
}
}
getAllCountries();
JavaScript (Axios)
import axios from 'axios';
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1';
async function getAllCountries() {
try {
const { data } = await axios.get(`${BASE_URL}/countries/all`, {
params: {
apikey: API_KEY,
limit: 100,
fields: 'id,country_name,country_short_iso,country_flag_png'
}
});
console.log(data);
return data;
} catch (error) {
console.error('Error fetching countries:', error.response?.data || error.message);
throw error;
}
}
getAllCountries();
React
import { useState, useEffect } from 'react';
const API_KEY = 'YOUR_API_KEY';
function CountryList() {
const [countries, setCountries] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchCountries() {
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/countries/all?apikey=${API_KEY}&limit=50`
);
if (!response.ok) {
throw new Error('Failed to fetch countries');
}
const data = await response.json();
setCountries(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCountries();
}, []);
if (loading) return <div className="loading">Loading countries...</div>;
if (error) return <div className="error">Error: {error}</div>;
return (
<div className="country-list">
<h2>All Countries ({countries.length})</h2>
<ul>
{countries.map((country) => (
<li key={country.id}>
<span className="country-flag">{country.country_flag}</span>
<span className="country-name">{country.country_name}</span>
<span className="country-code">({country.country_cca2})</span>
</li>
))}
</ul>
</div>
);
}
export default CountryList;
Vue 3
<script setup>
import { ref, onMounted } from 'vue';
const API_KEY = 'YOUR_API_KEY';
const countries = ref([]);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/countries/all?apikey=${API_KEY}&limit=50`
);
if (!response.ok) {
throw new Error('Failed to fetch countries');
}
countries.value = await response.json();
} catch (err) {
error.value = err.message;
} finally {
loading.value = false;
}
});
</script>
<template>
<div class="country-list">
<div v-if="loading" class="loading">Loading countries...</div>
<div v-else-if="error" class="error">Error: {{ error }}</div>
<template v-else>
<h2>All Countries ({{ countries.length }})</h2>
<ul>
<li v-for="country in countries" :key="country.id">
<span class="country-flag">{{ country.country_flag }}</span>
<span class="country-name">{{ country.country_name }}</span>
<span class="country-code">({{ country.country_cca2 }})</span>
</li>
</ul>
</template>
</div>
</template>
Angular
import { Component, OnInit, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
interface Country {
id: string;
lang: string;
country_name: string;
country_short_iso: string;
country_phone_code: string;
country_cca2: string;
country_flag?: string;
}
@Component({
selector: 'app-country-list',
standalone: true,
imports: [CommonModule],
template: `
<div class="country-list">
<div *ngIf="loading" class="loading">Loading countries...</div>
<div *ngIf="error" class="error">Error: {{ error }}</div>
<ng-container *ngIf="!loading && !error">
<h2>All Countries ({{ countries.length }})</h2>
<ul>
<li *ngFor="let country of countries">
<span class="country-flag">{{ country.country_flag }}</span>
<span class="country-name">{{ country.country_name }}</span>
<span class="country-code">({{ country.country_cca2 }})</span>
</li>
</ul>
</ng-container>
</div>
`
})
export class CountryListComponent implements OnInit {
private http = inject(HttpClient);
private readonly API_KEY = 'YOUR_API_KEY';
private readonly BASE_URL = 'https://api.countrydataapi.com/v1';
countries: Country[] = [];
loading = true;
error: string | null = null;
ngOnInit(): void {
this.http.get<Country[]>(
`${this.BASE_URL}/countries/all?apikey=${this.API_KEY}&limit=50`
).subscribe({
next: (data) => {
this.countries = data;
this.loading = false;
},
error: (err) => {
this.error = err.message;
this.loading = false;
}
});
}
}
Python
import requests
API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://api.countrydataapi.com/v1'
def get_all_countries(limit=100):
"""Fetch all countries from the API."""
try:
response = requests.get(
f'{BASE_URL}/countries/all',
params={
'apikey': API_KEY,
'limit': limit,
'fields': 'id,country_name,country_short_iso,country_phone_code'
}
)
response.raise_for_status()
countries = response.json()
return countries
except requests.exceptions.RequestException as e:
print(f'Error fetching countries: {e}')
raise
# Usage
if __name__ == '__main__':
countries = get_all_countries(limit=50)
for country in countries:
print(f"{country['country_name']} ({country['country_short_iso']})")
PHP
<?php
$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.countrydataapi.com/v1';
function getAllCountries($apiKey, $baseUrl, $limit = 100) {
$url = sprintf(
'%s/countries/all?apikey=%s&limit=%d',
$baseUrl,
urlencode($apiKey),
$limit
);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Accept: application/json']
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP Error: $httpCode");
}
return json_decode($response, true);
}
// Usage
try {
$countries = getAllCountries($apiKey, $baseUrl, 50);
foreach ($countries as $country) {
echo sprintf(
"%s (%s) - Phone: +%s\n",
$country['country_name'],
$country['country_short_iso'],
$country['country_phone_code']
);
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
Manejo de errores
| Codigo de estado | Descripcion |
|---|---|
| 200 | Exito - Devuelve array de paises |
| 401 | No autorizado - Clave API invalida o faltante |
| 429 | Demasiadas peticiones - Limite de tasa excedido |
| 500 | Error interno del servidor - Algo salio mal en nuestro lado |
Ejemplo de respuesta de error
{
"statusCode": 401,
"message": "Invalid API key",
"error": "Unauthorized"
}