Documentación de la API - Endpoints y Ejemplos

Buscar pais por codigo ISO

Descripcion general

El endpoint de pais por codigo te permite buscar paises usando sus codigos ISO (CCA2, CCA3, CCN3 o CIOC). Esto es esencial para aplicaciones internacionales que necesitan validar o correlacionar datos de paises usando codigos internacionales estandarizados.


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

Retorna datos del pais segun el codigo del pais (CCA2, CCA3, CCN3 o CIOC)

Tipos de codigo soportados:

  • CCA2: Codigo de pais de dos letras (ej., "US", "ES", "FR")
  • CCA3: Codigo de pais de tres letras (ej., "USA", "ESP", "FRA")
  • CCN3: Codigo numerico de tres digitos (ej., "840", "724", "250")
  • CIOC: Codigo del Comite Olimpico Internacional (ej., "USA", "ESP", "FRA")

Hay 4 tipos de operaciones:

  • BASIC: Retorna los campos id, lang, country_name, country_short_iso, country_phone_code, country_cca2, country_ccn3, country_cca3, country_cioc.

  • NORMAL: Retorna los campos anteriores y agrega 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: Retorna los campos anteriores y agrega country_car_info, _country_idd_info.

  • ALL: Retorna los campos anteriores y agrega 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 retornado con el metodo BASIC costara 1 tokens.

Cada pais retornado con el metodo NORMAL costara 2 tokens.

Cada pais retornado con el metodo ADVANCED costara 3 tokens.

Cada pais retornado con el metodo ALL costara 4 tokens.

Parametros de consulta


Parametro Tipo Descripcion
apikey requerido, token Clave de autenticacion de la cuenta
code requerido, string Codigo CCA2, CCA3, CCN3 o CIOC del pais
limitToken opcional, number 1000 (por defecto). Numero maximo de paises a retornar
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"
  }
]

Ejemplos de codigo

cURL

# Using CCA2 code
curl -X GET "https://api.countrydataapi.com/v1/countries/code?apikey=YOUR_API_KEY&code=US"

# Using CCA3 code
curl -X GET "https://api.countrydataapi.com/v1/countries/code?apikey=YOUR_API_KEY&code=USA"

# Using CCN3 numeric code
curl -X GET "https://api.countrydataapi.com/v1/countries/code?apikey=YOUR_API_KEY&code=840"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

    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 country by code:', error);
    throw error;
  }
}

// Using different code types
getCountryByCode('US');   // CCA2
getCountryByCode('USA');  // CCA3
getCountryByCode('840');  // CCN3

JavaScript (Axios)

import axios from 'axios';

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

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

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

// Get country by ISO code
getCountryByCode('ES');

React

import { useState } from 'react';

const API_KEY = 'YOUR_API_KEY';

function CountryCodeLookup() {
  const [code, setCode] = useState('');
  const [country, setCountry] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  async function handleSearch(e) {
    e.preventDefault();
    if (!code.trim()) return;

    setLoading(true);
    setError(null);
    setCountry(null);

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

      if (!response.ok) {
        throw new Error('Country not found');
      }

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

  return (
    <div className="code-lookup">
      <h2>Find Country by ISO Code</h2>

      <form onSubmit={handleSearch}>
        <input
          type="text"
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="Enter ISO code (e.g., US, USA, 840)"
          maxLength={3}
        />
        <button type="submit" disabled={loading}>
          {loading ? 'Searching...' : 'Search'}
        </button>
      </form>

      <p className="hint">Supports: CCA2 (US), CCA3 (USA), CCN3 (840), CIOC (USA)</p>

      {error && <div className="error">Error: {error}</div>}

      {country && (
        <div className="country-result">
          <img src={country.country_flag_png} alt={country.country_name} />
          <h3>{country.country_name}</h3>
          <table>
            <tbody>
              <tr><td>CCA2:</td><td>{country.country_cca2}</td></tr>
              <tr><td>CCA3:</td><td>{country.country_cca3}</td></tr>
              <tr><td>CCN3:</td><td>{country.country_ccn3}</td></tr>
              <tr><td>CIOC:</td><td>{country.country_cioc}</td></tr>
              <tr><td>Phone:</td><td>+{country.country_phone_code}</td></tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

export default CountryCodeLookup;

Vue 3

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

const API_KEY = 'YOUR_API_KEY';

const code = ref('');
const country = ref(null);
const loading = ref(false);
const error = ref(null);

async function searchByCode() {
  if (!code.value.trim()) return;

  loading.value = true;
  error.value = null;
  country.value = null;

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

    if (!response.ok) {
      throw new Error('Country not found');
    }

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

<template>
  <div class="code-lookup">
    <h2>Find Country by ISO Code</h2>

    <form @submit.prevent="searchByCode">
      <input
        v-model="code"
        type="text"
        placeholder="Enter ISO code (e.g., US, USA, 840)"
        maxlength="3"
        @input="code = code.toUpperCase()"
      />
      <button type="submit" :disabled="loading">
        {{ loading ? 'Searching...' : 'Search' }}
      </button>
    </form>

    <p class="hint">Supports: CCA2 (US), CCA3 (USA), CCN3 (840), CIOC (USA)</p>

    <div v-if="error" class="error">Error: {{ error }}</div>

    <div v-if="country" class="country-result">
      <img :src="country.country_flag_png" :alt="country.country_name" />
      <h3>{{ country.country_name }}</h3>
      <table>
        <tbody>
          <tr><td>CCA2:</td><td>{{ country.country_cca2 }}</td></tr>
          <tr><td>CCA3:</td><td>{{ country.country_cca3 }}</td></tr>
          <tr><td>CCN3:</td><td>{{ country.country_ccn3 }}</td></tr>
          <tr><td>CIOC:</td><td>{{ country.country_cioc }}</td></tr>
          <tr><td>Phone:</td><td>+{{ country.country_phone_code }}</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

Angular

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

interface Country {
  id: string;
  country_name: string;
  country_short_iso: string;
  country_cca2: string;
  country_cca3: string;
  country_ccn3: string;
  country_cioc: string;
  country_phone_code: string;
  country_flag_png?: string;
}

@Component({
  selector: 'app-code-lookup',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="code-lookup">
      <h2>Find Country by ISO Code</h2>

      <form (ngSubmit)="searchByCode()">
        <input
          [(ngModel)]="code"
          name="code"
          type="text"
          placeholder="Enter ISO code (e.g., US, USA, 840)"
          maxlength="3"
          (input)="code = code.toUpperCase()"
        />
        <button type="submit" [disabled]="loading">
          {{ loading ? 'Searching...' : 'Search' }}
        </button>
      </form>

      <p class="hint">Supports: CCA2 (US), CCA3 (USA), CCN3 (840), CIOC (USA)</p>

      <div *ngIf="error" class="error">Error: {{ error }}</div>

      <div *ngIf="country" class="country-result">
        <img [src]="country.country_flag_png" [alt]="country.country_name" />
        <h3>{{ country.country_name }}</h3>
        <table>
          <tbody>
            <tr><td>CCA2:</td><td>{{ country.country_cca2 }}</td></tr>
            <tr><td>CCA3:</td><td>{{ country.country_cca3 }}</td></tr>
            <tr><td>CCN3:</td><td>{{ country.country_ccn3 }}</td></tr>
            <tr><td>CIOC:</td><td>{{ country.country_cioc }}</td></tr>
            <tr><td>Phone:</td><td>+{{ country.country_phone_code }}</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  `
})
export class CodeLookupComponent {
  private http = inject(HttpClient);
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  code = '';
  country: Country | null = null;
  loading = false;
  error: string | null = null;

  searchByCode(): void {
    if (!this.code.trim()) return;

    this.loading = true;
    this.error = null;
    this.country = null;

    this.http.get<Country[]>(
      `${this.BASE_URL}/countries/code`,
      {
        params: {
          apikey: this.API_KEY,
          code: this.code
        }
      }
    ).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_by_code(code):
    """Find a country by its ISO code (CCA2, CCA3, CCN3, or CIOC)."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/code',
            params={
                'apikey': API_KEY,
                'code': code
            }
        )
        response.raise_for_status()

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

# Usage
if __name__ == '__main__':
    # Using CCA2 code
    country = get_country_by_code('US')
    if country:
        print(f"CCA2 'US': {country['country_name']}")

    # Using CCA3 code
    country = get_country_by_code('ESP')
    if country:
        print(f"CCA3 'ESP': {country['country_name']}")

    # Using CCN3 numeric code
    country = get_country_by_code('250')
    if country:
        print(f"CCN3 '250': {country['country_name']}")

    # Print all codes for a country
    country = get_country_by_code('DE')
    if country:
        print(f"\nAll codes for {country['country_name']}:")
        print(f"  CCA2: {country['country_cca2']}")
        print(f"  CCA3: {country['country_cca3']}")
        print(f"  CCN3: {country['country_ccn3']}")
        print(f"  CIOC: {country['country_cioc']}")

PHP

<?php

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

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

    $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 {
    // Using CCA2 code
    $country = getCountryByCode($apiKey, $baseUrl, 'US');
    if ($country) {
        echo "CCA2 'US': " . $country['country_name'] . "\n";
    }

    // Using CCA3 code
    $country = getCountryByCode($apiKey, $baseUrl, 'ESP');
    if ($country) {
        echo "CCA3 'ESP': " . $country['country_name'] . "\n";
    }

    // Using CCN3 numeric code
    $country = getCountryByCode($apiKey, $baseUrl, '250');
    if ($country) {
        echo "CCN3 '250': " . $country['country_name'] . "\n";
    }

    // Print all codes for a country
    $country = getCountryByCode($apiKey, $baseUrl, 'DE');
    if ($country) {
        echo "\nAll codes for " . $country['country_name'] . ":\n";
        echo "  CCA2: " . $country['country_cca2'] . "\n";
        echo "  CCA3: " . $country['country_cca3'] . "\n";
        echo "  CCN3: " . $country['country_ccn3'] . "\n";
        echo "  CIOC: " . $country['country_cioc'] . "\n";
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Manejo de errores

Codigo de estado Descripcion
200 Exito - Retorna datos del pais
400 Solicitud incorrecta - Falta el parametro requerido code
401 No autorizado - Clave API invalida o faltante
404 No encontrado - No se encontro ningun pais con ese codigo
429 Demasiadas solicitudes - Limite de tasa excedido
500 Error interno del servidor - Algo salio mal de nuestro lado

Ejemplo de respuesta de error

{
  "statusCode": 404,
  "message": "No country found with code: XYZ",
  "error": "Not Found"
}

Referencia de codigos ISO

Tipo de codigo Descripcion Ejemplo
CCA2 ISO 3166-1 alfa-2 (2 letras) US, ES
CCA3 ISO 3166-1 alfa-3 (3 letras) USA, ESP
CCN3 ISO 3166-1 numerico (3 digitos) 840, 724
CIOC Codigo del Comite Olimpico Internacional USA, ESP