Documentación de la API - Endpoints y Ejemplos

Buscar paises por region

Descripcion general

El endpoint de Paises por Region devuelve una lista de todos los paises en una region o continente especifico. Esto es util para construir filtros regionales, herramientas de analisis geografico y aplicaciones basadas en ubicacion.


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/region

Devuelve una lista de todos los paises en una region.

Regiones disponibles:

  • Africa
  • Americas
  • Asia
  • Europe
  • Oceania
  • Antarctic

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.nativeName.

Cada pais devuelto con el metodo BASIC costara 1 tokens.

Cada pais devuelto con el metodo NORMAL costara 2 tokens.

Cada pais devuelto con el metodo ADVANCED costara 3 tokens.

Cada pais devuelto con el metodo ALL costara 4 tokens.

Parametros de consulta


Parametro Tipo Descripcion
apikey requerido, token Clave de autenticacion de la cuenta
region requerido, string Region o continente a buscar. Ej., "Europe", "Africa"
limitToken opcional, numero 1000 (por defecto). Numero maximo de paises a devolver
lang opcional, lang en (por defecto). Idioma esperado de la respuesta
fields opcional, string id,lang,country_name (por defecto). Campos esperados en la respuesta

Respuesta

Ejemplo de respuesta

[
  {
    "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",
    "country_region": "Europe"
  }
]

Ejemplos de codigo

cURL

# Get all European countries
curl -X GET "https://api.countrydataapi.com/v1/countries/region?apikey=YOUR_API_KEY&region=Europe"

# Get all African countries
curl -X GET "https://api.countrydataapi.com/v1/countries/region?apikey=YOUR_API_KEY&region=Africa"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

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

    const countries = await response.json();
    console.log(`Countries in ${region}:`, countries);
    return countries;
  } catch (error) {
    console.error('Error fetching countries by region:', error);
    throw error;
  }
}

// Get all European countries
getCountriesByRegion('Europe');

JavaScript (Axios)

import axios from 'axios';

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

async function getCountriesByRegion(region) {
  try {
    const { data } = await axios.get(`${BASE_URL}/countries/region`, {
      params: {
        apikey: API_KEY,
        region: region,
        fields: 'id,country_name,country_short_iso,country_flag_png,country_region'
      }
    });

    console.log(`Countries in ${region}:`, data);
    return data;
  } catch (error) {
    console.error('Error fetching countries by region:', error.response?.data || error.message);
    throw error;
  }
}

// Get all Asian countries
getCountriesByRegion('Asia');

React

import { useState } from 'react';

const API_KEY = 'YOUR_API_KEY';

const REGIONS = [
  { name: 'Africa', color: '#f59e0b' },
  { name: 'Americas', color: '#ef4444' },
  { name: 'Asia', color: '#10b981' },
  { name: 'Europe', color: '#3b82f6' },
  { name: 'Oceania', color: '#8b5cf6' }
];

function RegionCountrySearch() {
  const [region, setRegion] = useState('');
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  async function handleRegionSelect(selectedRegion) {
    if (!selectedRegion) return;

    setLoading(true);
    setError(null);
    setRegion(selectedRegion);

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

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

  return (
    <div className="region-search">
      <h2>Find Countries by Region</h2>

      <div className="region-buttons">
        {REGIONS.map((r) => (
          <button
            key={r.name}
            onClick={() => handleRegionSelect(r.name)}
            className={region === r.name ? 'active' : ''}
            style={{ '--region-color': r.color }}
          >
            {r.name}
          </button>
        ))}
      </div>

      {loading && <div className="loading">Loading countries...</div>}
      {error && <div className="error">Error: {error}</div>}

      {countries.length > 0 && (
        <div className="results">
          <h3>Countries in {region} ({countries.length})</h3>
          <div className="country-grid">
            {countries.map((country) => (
              <div key={country.id} className="country-card">
                <img src={country.country_flag_png} alt={country.country_name} />
                <span>{country.country_name}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

export default RegionCountrySearch;

Vue 3

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

const API_KEY = 'YOUR_API_KEY';

const REGIONS = [
  { name: 'Africa', color: '#f59e0b' },
  { name: 'Americas', color: '#ef4444' },
  { name: 'Asia', color: '#10b981' },
  { name: 'Europe', color: '#3b82f6' },
  { name: 'Oceania', color: '#8b5cf6' }
];

const region = ref('');
const countries = ref([]);
const loading = ref(false);
const error = ref(null);

async function selectRegion(selectedRegion) {
  if (!selectedRegion) return;

  loading.value = true;
  error.value = null;
  region.value = selectedRegion;

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

    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="region-search">
    <h2>Find Countries by Region</h2>

    <div class="region-buttons">
      <button
        v-for="r in REGIONS"
        :key="r.name"
        @click="selectRegion(r.name)"
        :class="{ active: region === r.name }"
        :style="{ '--region-color': r.color }"
      >
        {{ r.name }}
      </button>
    </div>

    <div v-if="loading" class="loading">Loading countries...</div>
    <div v-if="error" class="error">Error: {{ error }}</div>

    <div v-if="countries.length > 0" class="results">
      <h3>Countries in {{ region }} ({{ countries.length }})</h3>
      <div class="country-grid">
        <div v-for="country in countries" :key="country.id" class="country-card">
          <img :src="country.country_flag_png" :alt="country.country_name" />
          <span>{{ country.country_name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

Angular

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

interface Country {
  id: string;
  country_name: string;
  country_short_iso: string;
  country_cca2: string;
  country_flag_png?: string;
  country_region?: string;
}

interface Region {
  name: string;
  color: string;
}

@Component({
  selector: 'app-region-search',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="region-search">
      <h2>Find Countries by Region</h2>

      <div class="region-buttons">
        <button
          *ngFor="let r of regions"
          (click)="selectRegion(r.name)"
          [class.active]="region === r.name"
          [style.--region-color]="r.color"
        >
          {{ r.name }}
        </button>
      </div>

      <div *ngIf="loading" class="loading">Loading countries...</div>
      <div *ngIf="error" class="error">Error: {{ error }}</div>

      <div *ngIf="countries.length > 0" class="results">
        <h3>Countries in {{ region }} ({{ countries.length }})</h3>
        <div class="country-grid">
          <div *ngFor="let country of countries" class="country-card">
            <img [src]="country.country_flag_png" [alt]="country.country_name" />
            <span>{{ country.country_name }}</span>
          </div>
        </div>
      </div>
    </div>
  `
})
export class RegionSearchComponent {
  private http = inject(HttpClient);
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  regions: Region[] = [
    { name: 'Africa', color: '#f59e0b' },
    { name: 'Americas', color: '#ef4444' },
    { name: 'Asia', color: '#10b981' },
    { name: 'Europe', color: '#3b82f6' },
    { name: 'Oceania', color: '#8b5cf6' }
  ];

  region = '';
  countries: Country[] = [];
  loading = false;
  error: string | null = null;

  selectRegion(selectedRegion: string): void {
    this.loading = true;
    this.error = null;
    this.region = selectedRegion;

    this.http.get<Country[]>(
      `${this.BASE_URL}/countries/region`,
      {
        params: {
          apikey: this.API_KEY,
          region: selectedRegion
        }
      }
    ).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_countries_by_region(region):
    """Find all countries in a specific region."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/region',
            params={
                'apikey': API_KEY,
                'region': region
            }
        )
        response.raise_for_status()

        countries = response.json()
        return countries
    except requests.exceptions.RequestException as e:
        print(f'Error fetching countries by region: {e}')
        raise

# Usage
if __name__ == '__main__':
    regions = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']

    for region in regions:
        countries = get_countries_by_region(region)
        print(f"\n{region} ({len(countries)} countries):")
        for country in countries[:5]:  # Show first 5 countries
            print(f"  - {country['country_name']} ({country['country_short_iso']})")
        if len(countries) > 5:
            print(f"  ... and {len(countries) - 5} more")

PHP

<?php

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

function getCountriesByRegion($apiKey, $baseUrl, $region) {
    $url = sprintf(
        '%s/countries/region?apikey=%s&region=%s',
        $baseUrl,
        urlencode($apiKey),
        urlencode($region)
    );

    $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 {
    $regions = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania'];

    foreach ($regions as $region) {
        $countries = getCountriesByRegion($apiKey, $baseUrl, $region);
        echo "\n$region (" . count($countries) . " countries):\n";
        foreach (array_slice($countries, 0, 5) as $country) {
            echo sprintf("  - %s (%s)\n", $country['country_name'], $country['country_short_iso']);
        }
        if (count($countries) > 5) {
            echo "  ... and " . (count($countries) - 5) . " more\n";
        }
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Manejo de errores

Codigo de estado Descripcion
200 Exito - Devuelve array de paises
400 Peticion incorrecta - Falta el parametro region
401 No autorizado - Clave API invalida o faltante
404 No encontrado - No se encontraron paises en esa region
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": "No countries found in region: Unknown",
  "error": "Not Found"
}

Regiones disponibles

Region Descripcion Paises
Africa Paises africanos 54+
Americas Paises de Norte, Centro y Sudamerica 35+
Asia Paises asiaticos 48+
Europe Paises europeos 44+
Oceania Paises de Oceania e islas del Pacifico 14+
Antarctic Territorios antarticos 1