Documentación de la API - Endpoints y Ejemplos

Todos los datos de un pais

Descripcion general

El endpoint de Todos los Datos devuelve informacion completa sobre un pais especifico, incluyendo datos demograficos, economicos, geograficos y culturales. Este endpoint es ideal cuando necesitas perfiles completos de paises para analisis detallado o visualizacion.


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/

Devuelve todos los datos de un pais especifico.

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 costara 1 tokens.

Cada peticion NORMAL costara 2 tokens.

Cada peticion ADVANCED costara 3 tokens.

Cada peticion ALL costara 4 tokens.

Parametros de consulta


Parametro Tipo Descripcion
apikey requerido, token Clave API asociada a tu cuenta
country requerido, id o codigo ISO ID del pais o codigo ISO
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. Ver Idiomas.

Respuesta

Ejemplo de respuesta

[
  {
    "id": "33be30c5-80fc-429d-bf10-bd11f2e3e84c",
    "lang": "en",
    "country_name": "Albania",
    "country_short_iso": "AL",
    "country_phone_code": "355",
    "country_tld": [".al"],
    "country_cca2": "AL",
    "country_ccn3": "008",
    "country_cca3": "ALB",
    "country_cioc": "ALB",
    "country_independent": true,
    "country_status": "officially-assigned",
    "country_unMember": true,
    "country_capital": ["Tirana"],
    "country_region": "Europe",
    "country_subregion": "Southeast Europe",
    "country_latLng": ["41", "20"],
    "country_flag_png": "https://flagcdn.com/w320/al.png",
    "country_flag_svg": "https://flagcdn.com/al.svg",
    "country_current_currency": "Lek (ALL)",
    "country_GDP": "$21.8 billion",
    "country_life_expectancy": "77.96 years"
  }
]

Ejemplos de codigo

cURL

curl -X GET "https://api.countrydataapi.com/v1/countries/?apikey=YOUR_API_KEY&country=AL"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

async function getCountryData(countryCode) {
  try {
    const response = await fetch(
      `https://api.countrydataapi.com/v1/countries/?apikey=${API_KEY}&country=${countryCode}`
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const countryData = await response.json();
    console.log(countryData);
    return countryData;
  } catch (error) {
    console.error('Error fetching country data:', error);
    throw error;
  }
}

// Get data for Albania
getCountryData('AL');

JavaScript (Axios)

import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1';

async function getCountryData(countryCode, fields = null) {
  try {
    const params = {
      apikey: API_KEY,
      country: countryCode
    };

    if (fields) {
      params.fields = fields;
    }

    const { data } = await axios.get(`${BASE_URL}/countries/`, { params });

    console.log(data);
    return data;
  } catch (error) {
    console.error('Error fetching country data:', error.response?.data || error.message);
    throw error;
  }
}

// Get all data for Spain
getCountryData('ES');

// Get specific fields only
getCountryData('ES', 'id,country_name,country_GDP,country_population');

React

import { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';

function CountryDetail({ countryCode }) {
  const [country, setCountry] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchCountryData() {
      try {
        setLoading(true);
        const response = await fetch(
          `https://api.countrydataapi.com/v1/countries/?apikey=${API_KEY}&country=${countryCode}`
        );

        if (!response.ok) {
          throw new Error('Failed to fetch country data');
        }

        const data = await response.json();
        setCountry(data[0]);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    if (countryCode) {
      fetchCountryData();
    }
  }, [countryCode]);

  if (loading) return <div className="loading">Loading country data...</div>;
  if (error) return <div className="error">Error: {error}</div>;
  if (!country) return <div>No country data found</div>;

  return (
    <div className="country-detail">
      <div className="country-header">
        <img src={country.country_flag_png} alt={country.country_flag_alt} />
        <h1>{country.country_name}</h1>
      </div>

      <div className="country-info">
        <div className="info-section">
          <h3>General Information</h3>
          <p><strong>Capital:</strong> {country.country_capital?.join(', ')}</p>
          <p><strong>Region:</strong> {country.country_region}</p>
          <p><strong>Subregion:</strong> {country.country_subregion}</p>
          <p><strong>Phone Code:</strong> +{country.country_phone_code}</p>
        </div>

        <div className="info-section">
          <h3>Economic Data</h3>
          <p><strong>GDP:</strong> {country.country_GDP}</p>
          <p><strong>GDP per Capita:</strong> {country.country_GDP_per_capita_PPP}</p>
          <p><strong>Currency:</strong> {country.country_current_currency}</p>
        </div>

        <div className="info-section">
          <h3>Demographics</h3>
          <p><strong>Life Expectancy:</strong> {country.country_life_expectancy}</p>
          <p><strong>Median Age:</strong> {country.country_median_age}</p>
          <p><strong>Literacy Rate:</strong> {country.country_literacy}</p>
        </div>
      </div>
    </div>
  );
}

export default CountryDetail;

Vue 3

<script setup>
import { ref, watch, onMounted } from 'vue';

const props = defineProps({
  countryCode: {
    type: String,
    required: true
  }
});

const API_KEY = 'YOUR_API_KEY';

const country = ref(null);
const loading = ref(true);
const error = ref(null);

async function fetchCountryData(code) {
  try {
    loading.value = true;
    error.value = null;

    const response = await fetch(
      `https://api.countrydataapi.com/v1/countries/?apikey=${API_KEY}&country=${code}`
    );

    if (!response.ok) {
      throw new Error('Failed to fetch country data');
    }

    const data = await response.json();
    country.value = data[0];
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}

watch(() => props.countryCode, (newCode) => {
  if (newCode) {
    fetchCountryData(newCode);
  }
}, { immediate: true });
</script>

<template>
  <div class="country-detail">
    <div v-if="loading" class="loading">Loading country data...</div>
    <div v-else-if="error" class="error">Error: {{ error }}</div>
    <template v-else-if="country">
      <div class="country-header">
        <img :src="country.country_flag_png" :alt="country.country_flag_alt" />
        <h1>{{ country.country_name }}</h1>
      </div>

      <div class="country-info">
        <div class="info-section">
          <h3>General Information</h3>
          <p><strong>Capital:</strong> {{ country.country_capital?.join(', ') }}</p>
          <p><strong>Region:</strong> {{ country.country_region }}</p>
          <p><strong>Currency:</strong> {{ country.country_current_currency }}</p>
        </div>

        <div class="info-section">
          <h3>Economic Data</h3>
          <p><strong>GDP:</strong> {{ country.country_GDP }}</p>
          <p><strong>Life Expectancy:</strong> {{ country.country_life_expectancy }}</p>
        </div>
      </div>
    </template>
  </div>
</template>

Angular

import { Component, Input, OnChanges, SimpleChanges, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';

interface CountryData {
  id: string;
  country_name: string;
  country_short_iso: string;
  country_flag_png: string;
  country_flag_alt: string;
  country_capital: string[];
  country_region: string;
  country_subregion: string;
  country_phone_code: string;
  country_GDP: string;
  country_GDP_per_capita_PPP: string;
  country_current_currency: string;
  country_life_expectancy: string;
  country_median_age: string;
  country_literacy: string;
}

@Component({
  selector: 'app-country-detail',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="country-detail">
      <div *ngIf="loading" class="loading">Loading country data...</div>
      <div *ngIf="error" class="error">Error: {{ error }}</div>

      <ng-container *ngIf="!loading && !error && country">
        <div class="country-header">
          <img [src]="country.country_flag_png" [alt]="country.country_flag_alt" />
          <h1>{{ country.country_name }}</h1>
        </div>

        <div class="country-info">
          <div class="info-section">
            <h3>General Information</h3>
            <p><strong>Capital:</strong> {{ country.country_capital?.join(', ') }}</p>
            <p><strong>Region:</strong> {{ country.country_region }}</p>
            <p><strong>Phone Code:</strong> +{{ country.country_phone_code }}</p>
          </div>

          <div class="info-section">
            <h3>Economic Data</h3>
            <p><strong>GDP:</strong> {{ country.country_GDP }}</p>
            <p><strong>Currency:</strong> {{ country.country_current_currency }}</p>
          </div>
        </div>
      </ng-container>
    </div>
  `
})
export class CountryDetailComponent implements OnChanges {
  @Input() countryCode!: string;

  private http = inject(HttpClient);
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  country: CountryData | null = null;
  loading = false;
  error: string | null = null;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['countryCode'] && this.countryCode) {
      this.fetchCountryData();
    }
  }

  private fetchCountryData(): void {
    this.loading = true;
    this.error = null;

    this.http.get<CountryData[]>(
      `${this.BASE_URL}/countries/?apikey=${this.API_KEY}&country=${this.countryCode}`
    ).subscribe({
      next: (data) => {
        this.country = data[0];
        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_country_data(country_code, fields=None):
    """Fetch all data for a specific country."""
    try:
        params = {
            'apikey': API_KEY,
            'country': country_code
        }

        if fields:
            params['fields'] = fields

        response = requests.get(f'{BASE_URL}/countries/', params=params)
        response.raise_for_status()

        country_data = response.json()
        return country_data[0] if country_data else None
    except requests.exceptions.RequestException as e:
        print(f'Error fetching country data: {e}')
        raise

# Usage
if __name__ == '__main__':
    # Get all data for Spain
    country = get_country_data('ES')

    if country:
        print(f"Country: {country['country_name']}")
        print(f"Capital: {', '.join(country.get('country_capital', []))}")
        print(f"Region: {country.get('country_region', 'N/A')}")
        print(f"GDP: {country.get('country_GDP', 'N/A')}")
        print(f"Currency: {country.get('country_current_currency', 'N/A')}")
        print(f"Life Expectancy: {country.get('country_life_expectancy', 'N/A')}")

PHP

<?php

$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.countrydataapi.com/v1';

function getCountryData($apiKey, $baseUrl, $countryCode, $fields = null) {
    $params = [
        'apikey' => $apiKey,
        'country' => $countryCode
    ];

    if ($fields) {
        $params['fields'] = $fields;
    }

    $url = $baseUrl . '/countries/?' . http_build_query($params);

    $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");
    }

    $data = json_decode($response, true);
    return $data[0] ?? null;
}

// Usage
try {
    $country = getCountryData($apiKey, $baseUrl, 'ES');

    if ($country) {
        echo "Country: " . $country['country_name'] . "\n";
        echo "Capital: " . implode(', ', $country['country_capital'] ?? []) . "\n";
        echo "Region: " . ($country['country_region'] ?? 'N/A') . "\n";
        echo "GDP: " . ($country['country_GDP'] ?? 'N/A') . "\n";
        echo "Currency: " . ($country['country_current_currency'] ?? 'N/A') . "\n";
        echo "Life Expectancy: " . ($country['country_life_expectancy'] ?? 'N/A') . "\n";
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Manejo de errores

Codigo de estado Descripcion
200 Exito - Devuelve datos del pais
400 Peticion incorrecta - Faltan parametros requeridos
401 No autorizado - Clave API invalida o faltante
404 No encontrado - Pais no encontrado
429 Demasiadas peticiones - Limite de tasa excedido
500 Error interno del servidor - Algo salio mal en nuestro lado

Ejemplo de respuesta de error

{
  "statusCode": 404,
  "message": "Country not found",
  "error": "Not Found"
}