Documentación de la API - Endpoints y Ejemplos

Buscar pais por independencia

Descripcion general

El endpoint de paises por independencia retorna una lista de todos los paises filtrados por su estado de independencia. Esto te permite obtener ya sea todas las naciones soberanas independientes o todos los territorios y regiones dependientes.


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

Retorna una lista de todos los paises segun su estado de independencia.

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
independent requerido, boolean Indica si retornar paises independientes (true) o territorios dependientes (false)
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",
    "country_independent": true
  }
]

Ejemplos de codigo

cURL

# Get all independent countries
curl -X GET "https://api.countrydataapi.com/v1/countries/independecy?apikey=YOUR_API_KEY&independent=true"

# Get all dependent territories
curl -X GET "https://api.countrydataapi.com/v1/countries/independecy?apikey=YOUR_API_KEY&independent=false"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

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

    const countries = await response.json();
    console.log(`${isIndependent ? 'Independent' : 'Dependent'} countries:`, countries);
    return countries;
  } catch (error) {
    console.error('Error fetching countries by independency:', error);
    throw error;
  }
}

// Get all independent countries
getCountriesByIndependency(true);

// Get all dependent territories
getCountriesByIndependency(false);

JavaScript (Axios)

import axios from 'axios';

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

async function getCountriesByIndependency(isIndependent) {
  try {
    const { data } = await axios.get(`${BASE_URL}/countries/independecy`, {
      params: {
        apikey: API_KEY,
        independent: isIndependent,
        fields: 'id,country_name,country_short_iso,country_flag_png,country_independent'
      }
    });

    console.log(`${isIndependent ? 'Independent' : 'Dependent'} countries:`, data);
    return data;
  } catch (error) {
    console.error('Error fetching countries by independency:', error.response?.data || error.message);
    throw error;
  }
}

getCountriesByIndependency(true);

React

import { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';

function IndependencyFilter() {
  const [isIndependent, setIsIndependent] = useState(true);
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchCountries() {
      setLoading(true);
      setError(null);

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

        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();
  }, [isIndependent]);

  return (
    <div className="independency-filter">
      <h2>Filter Countries by Independence Status</h2>

      <div className="toggle-buttons">
        <button
          onClick={() => setIsIndependent(true)}
          className={isIndependent ? 'active' : ''}
        >
          Independent Countries
        </button>
        <button
          onClick={() => setIsIndependent(false)}
          className={!isIndependent ? 'active' : ''}
        >
          Dependent Territories
        </button>
      </div>

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

      {!loading && !error && (
        <div className="results">
          <h3>
            {isIndependent ? 'Independent Countries' : 'Dependent Territories'}
            ({countries.length})
          </h3>
          <ul>
            {countries.map((country) => (
              <li key={country.id}>
                <img src={country.country_flag_png} alt={country.country_name} width="24" />
                <span>{country.country_name}</span>
                <span className="code">({country.country_cca2})</span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

export default IndependencyFilter;

Vue 3

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

const API_KEY = 'YOUR_API_KEY';

const isIndependent = ref(true);
const countries = ref([]);
const loading = ref(false);
const error = ref(null);

async function fetchCountries() {
  loading.value = true;
  error.value = null;

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

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

watch(isIndependent, fetchCountries, { immediate: true });
</script>

<template>
  <div class="independency-filter">
    <h2>Filter Countries by Independence Status</h2>

    <div class="toggle-buttons">
      <button
        @click="isIndependent = true"
        :class="{ active: isIndependent }"
      >
        Independent Countries
      </button>
      <button
        @click="isIndependent = false"
        :class="{ active: !isIndependent }"
      >
        Dependent Territories
      </button>
    </div>

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

    <div v-if="!loading && !error" class="results">
      <h3>
        {{ isIndependent ? 'Independent Countries' : 'Dependent Territories' }}
        ({{ countries.length }})
      </h3>
      <ul>
        <li v-for="country in countries" :key="country.id">
          <img :src="country.country_flag_png" :alt="country.country_name" width="24" />
          <span>{{ country.country_name }}</span>
          <span class="code">({{ country.country_cca2 }})</span>
        </li>
      </ul>
    </div>
  </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;
  country_name: string;
  country_short_iso: string;
  country_cca2: string;
  country_flag_png?: string;
  country_independent: boolean;
}

@Component({
  selector: 'app-independency-filter',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="independency-filter">
      <h2>Filter Countries by Independence Status</h2>

      <div class="toggle-buttons">
        <button
          (click)="setIndependent(true)"
          [class.active]="isIndependent"
        >
          Independent Countries
        </button>
        <button
          (click)="setIndependent(false)"
          [class.active]="!isIndependent"
        >
          Dependent Territories
        </button>
      </div>

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

      <div *ngIf="!loading && !error" class="results">
        <h3>
          {{ isIndependent ? 'Independent Countries' : 'Dependent Territories' }}
          ({{ countries.length }})
        </h3>
        <ul>
          <li *ngFor="let country of countries">
            <img [src]="country.country_flag_png" [alt]="country.country_name" width="24" />
            <span>{{ country.country_name }}</span>
            <span class="code">({{ country.country_cca2 }})</span>
          </li>
        </ul>
      </div>
    </div>
  `
})
export class IndependencyFilterComponent implements OnInit {
  private http = inject(HttpClient);
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  isIndependent = true;
  countries: Country[] = [];
  loading = false;
  error: string | null = null;

  ngOnInit(): void {
    this.fetchCountries();
  }

  setIndependent(value: boolean): void {
    this.isIndependent = value;
    this.fetchCountries();
  }

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

    this.http.get<Country[]>(
      `${this.BASE_URL}/countries/independecy`,
      {
        params: {
          apikey: this.API_KEY,
          independent: String(this.isIndependent)
        }
      }
    ).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_independency(is_independent):
    """Find all countries by their independence status."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/independecy',
            params={
                'apikey': API_KEY,
                'independent': str(is_independent).lower()
            }
        )
        response.raise_for_status()

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

# Usage
if __name__ == '__main__':
    # Get all independent countries
    independent_countries = get_countries_by_independency(True)
    print(f"Independent Countries ({len(independent_countries)}):")
    for country in independent_countries[:10]:  # Show first 10
        print(f"  - {country['country_name']} ({country['country_short_iso']})")
    print(f"  ... and {len(independent_countries) - 10} more\n")

    # Get all dependent territories
    dependent_territories = get_countries_by_independency(False)
    print(f"Dependent Territories ({len(dependent_territories)}):")
    for territory in dependent_territories:
        print(f"  - {territory['country_name']} ({territory['country_short_iso']})")

PHP

<?php

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

function getCountriesByIndependency($apiKey, $baseUrl, $isIndependent) {
    $url = sprintf(
        '%s/countries/independecy?apikey=%s&independent=%s',
        $baseUrl,
        urlencode($apiKey),
        $isIndependent ? 'true' : 'false'
    );

    $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 {
    // Get all independent countries
    $independentCountries = getCountriesByIndependency($apiKey, $baseUrl, true);
    echo "Independent Countries (" . count($independentCountries) . "):\n";
    foreach (array_slice($independentCountries, 0, 10) as $country) {
        echo sprintf("  - %s (%s)\n", $country['country_name'], $country['country_short_iso']);
    }
    echo "  ... and " . (count($independentCountries) - 10) . " more\n\n";

    // Get all dependent territories
    $dependentTerritories = getCountriesByIndependency($apiKey, $baseUrl, false);
    echo "Dependent Territories (" . count($dependentTerritories) . "):\n";
    foreach ($dependentTerritories as $territory) {
        echo sprintf("  - %s (%s)\n", $territory['country_name'], $territory['country_short_iso']);
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Manejo de errores

Codigo de estado Descripcion
200 Exito - Retorna array de paises
400 Solicitud incorrecta - Falta el parametro requerido independent
401 No autorizado - Clave API invalida o faltante
429 Demasiadas solicitudes - Limite de tasa excedido
500 Error interno del servidor - Algo salio mal de nuestro lado

Ejemplo de respuesta de error

{
  "statusCode": 400,
  "message": "Missing required parameter: independent",
  "error": "Bad Request"
}

Notas

  • Paises independientes: Naciones soberanas reconocidas como estados independientes (ej., Estados Unidos, Francia, Japon)
  • Territorios dependientes: Regiones que son parte de o administradas por otros paises (ej., Puerto Rico, Groenlandia, Hong Kong)
  • El parametro independent debe ser true o false