API Documentation - Endpoints & Examples

Search a Country by Independency

Overview

The Countries by Independency endpoint returns a list of all countries filtered by their independence status. This allows you to retrieve either all sovereign independent nations or all dependent territories and regions.


Authentication

All requests require an API key passed as a query parameter. You can obtain your API key by registering at CountryDataAPI.

Request

HTTP GET

https://api.countrydataapi.com/v1/countries/independecy

Returns a list of all countries according to their independence status.

There are 4 types of operations:

  • BASIC: Returns the fields id, lang, country_name, country_short_iso, country_phone_code, country_cca2, country_ccn3, country_cca3, country_cioc.

  • NORMAL: Returns the previous fields and adds 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: Returns the previous fields and adds country_car_info, _country_idd_info.

  • ALL: Returns the previous fields and adds 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.

Each country returned with the BASIC method will cost 1 tokens.

Each country returned with the NORMAL method will cost 2 tokens.

Each country returned with the ADVANCED method will cost 3 tokens.

Each country returned with the ALL method will cost 4 tokens.

Query Params


Parameter Type Description
apikey required, token Authentication key for the account
independent required, boolean Indicates whether to return independent countries (true) or dependent territories (false)
limitToken optional, number 1000 (default). Maximum number of countries to return
lang optional, lang en (default). Expected language of the response
fields optional, string id,lang,country_name (default). Expected fields in the response

Response

Example Response

[
  {
    "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
  }
]

Code Examples

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

Error Handling

Status Code Description
200 Success - Returns array of countries
400 Bad Request - Missing required independent parameter
401 Unauthorized - Invalid or missing API key
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Something went wrong on our end

Error Response Example

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

Notes

  • Independent Countries: Sovereign nations recognized as independent states (e.g., United States, France, Japan)
  • Dependent Territories: Regions that are part of or administered by other countries (e.g., Puerto Rico, Greenland, Hong Kong)
  • The independent parameter must be either true or false