Documentación de la API - Endpoints y Ejemplos

Buscar pais por idioma

Descripcion general

El endpoint de Paises por Idioma devuelve una lista de todos los paises donde se habla un idioma especifico. Esto es util para aplicaciones de localizacion, plataformas de contenido multilingue y herramientas de analisis linguistico.


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

Devuelve una lista de todos los paises que hablan un idioma especifico.

Codigos de idioma comunes:

  • spa: Espanol
  • eng: Ingles
  • por: Portugues
  • fra: Frances
  • deu: Aleman
  • ara: Arabe
  • zho: Chino

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
language requerido, string Codigo del idioma a buscar. Ej: "spa", "eng", "por"
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": "f7a8b9c0-1234-5678-90ab-cdef12345678",
    "lang": "en",
    "country_name": "Spain",
    "country_short_iso": "ES",
    "country_phone_code": "34",
    "country_cca2": "ES",
    "country_ccn3": "724",
    "country_cca3": "ESP",
    "country_cioc": "ESP"
  },
  {
    "id": "a1b2c3d4-5678-90ab-cdef-123456789012",
    "lang": "en",
    "country_name": "Mexico",
    "country_short_iso": "MX",
    "country_phone_code": "52",
    "country_cca2": "MX",
    "country_ccn3": "484",
    "country_cca3": "MEX",
    "country_cioc": "MEX"
  }
]

Ejemplos de codigo

cURL

# Find all Spanish-speaking countries
curl -X GET "https://api.countrydataapi.com/v1/countries/language?apikey=YOUR_API_KEY&language=spa"

# Find all English-speaking countries
curl -X GET "https://api.countrydataapi.com/v1/countries/language?apikey=YOUR_API_KEY&language=eng"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

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

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

// Find all Spanish-speaking countries
getCountriesByLanguage('spa');

JavaScript (Axios)

import axios from 'axios';

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

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

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

// Find all Portuguese-speaking countries
getCountriesByLanguage('por');

React

import { useState } from 'react';

const API_KEY = 'YOUR_API_KEY';

const LANGUAGES = [
  { code: 'spa', name: 'Spanish' },
  { code: 'eng', name: 'English' },
  { code: 'por', name: 'Portuguese' },
  { code: 'fra', name: 'French' },
  { code: 'deu', name: 'German' },
  { code: 'ara', name: 'Arabic' }
];

function LanguageCountrySearch() {
  const [language, setLanguage] = useState('');
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  async function handleSearch(languageCode) {
    if (!languageCode) return;

    setLoading(true);
    setError(null);
    setLanguage(languageCode);

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

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

      <div className="language-buttons">
        {LANGUAGES.map((lang) => (
          <button
            key={lang.code}
            onClick={() => handleSearch(lang.code)}
            className={language === lang.code ? 'active' : ''}
          >
            {lang.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 speaking {LANGUAGES.find(l => l.code === language)?.name} ({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 LanguageCountrySearch;

Python

import requests

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

def get_countries_by_language(language_code):
    """Find all countries that speak a specific language."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/language',
            params={
                'apikey': API_KEY,
                'language': language_code
            }
        )
        response.raise_for_status()

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

# Usage
if __name__ == '__main__':
    # Find all Spanish-speaking countries
    spanish_countries = get_countries_by_language('spa')
    print(f"Spanish-speaking countries ({len(spanish_countries)}):")
    for country in spanish_countries:
        print(f"  - {country['country_name']} ({country['country_short_iso']})")

    print()

    # Find all English-speaking countries
    english_countries = get_countries_by_language('eng')
    print(f"English-speaking countries ({len(english_countries)}):")
    for country in english_countries:
        print(f"  - {country['country_name']} ({country['country_short_iso']})")

PHP

<?php

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

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

    $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 {
    // Find all Spanish-speaking countries
    $spanishCountries = getCountriesByLanguage($apiKey, $baseUrl, 'spa');
    echo "Spanish-speaking countries (" . count($spanishCountries) . "):\n";
    foreach ($spanishCountries as $country) {
        echo sprintf("  - %s (%s)\n", $country['country_name'], $country['country_short_iso']);
    }
} 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 language
401 No autorizado - Clave API invalida o faltante
404 No encontrado - No se encontraron paises con ese idioma
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 with language: xyz",
  "error": "Not Found"
}