API Documentation - Endpoints & Examples

All Countries

Overview

The All Countries endpoint returns a comprehensive list of all registered countries in the CountryDataAPI database. With over 200 countries available, this endpoint is perfect for building country selection dropdowns, geographic data analysis, and global applications.


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

Returns a list of all registered countries.

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

Each BASIC request will spend 1 tokens.

Each NORMAL request will spend 2 tokens.

Each ADVANCED request will spend 3 tokens.

Each ALL request will spend 4 tokens.

Query Params


Parametro Tipo Descripcion
apikey required, token Your account's authentication API key
limit optional, number 100 (default). Maximum number of countries to be returned
limitToken optional, number 1000 (default). Maximum number of tokens you want to spend on this request
fields optional, string id,lang,country_name (default). Expected fields in the response
lang optional, lang en (default). Expected language of the response

Response

Example Response

[
  {
    "id": "a0436505-66a2-4e7a-8010-9a003d59e786",
    "lang": "en",
    "country_name": "Afghanistan",
    "country_short_iso": "AF",
    "country_phone_code": "93",
    "country_cca2": "AF",
    "country_ccn3": "004",
    "country_cca3": "AFG",
    "country_cioc": "AFG"
  },
  {
    "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"
  }
]

Code Examples

cURL

curl -X GET "https://api.countrydataapi.com/v1/countries/all?apikey=YOUR_API_KEY&limit=10"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

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

getAllCountries();

JavaScript (Axios)

import axios from 'axios';

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

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

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

getAllCountries();

React

import { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';

function CountryList() {
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchCountries() {
      try {
        const response = await fetch(
          `https://api.countrydataapi.com/v1/countries/all?apikey=${API_KEY}&limit=50`
        );

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

  if (loading) return <div className="loading">Loading countries...</div>;
  if (error) return <div className="error">Error: {error}</div>;

  return (
    <div className="country-list">
      <h2>All Countries ({countries.length})</h2>
      <ul>
        {countries.map((country) => (
          <li key={country.id}>
            <span className="country-flag">{country.country_flag}</span>
            <span className="country-name">{country.country_name}</span>
            <span className="country-code">({country.country_cca2})</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default CountryList;

Vue 3

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

const API_KEY = 'YOUR_API_KEY';

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

onMounted(async () => {
  try {
    const response = await fetch(
      `https://api.countrydataapi.com/v1/countries/all?apikey=${API_KEY}&limit=50`
    );

    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="country-list">
    <div v-if="loading" class="loading">Loading countries...</div>
    <div v-else-if="error" class="error">Error: {{ error }}</div>
    <template v-else>
      <h2>All Countries ({{ countries.length }})</h2>
      <ul>
        <li v-for="country in countries" :key="country.id">
          <span class="country-flag">{{ country.country_flag }}</span>
          <span class="country-name">{{ country.country_name }}</span>
          <span class="country-code">({{ country.country_cca2 }})</span>
        </li>
      </ul>
    </template>
  </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;
  lang: string;
  country_name: string;
  country_short_iso: string;
  country_phone_code: string;
  country_cca2: string;
  country_flag?: string;
}

@Component({
  selector: 'app-country-list',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="country-list">
      <div *ngIf="loading" class="loading">Loading countries...</div>
      <div *ngIf="error" class="error">Error: {{ error }}</div>
      <ng-container *ngIf="!loading && !error">
        <h2>All Countries ({{ countries.length }})</h2>
        <ul>
          <li *ngFor="let country of countries">
            <span class="country-flag">{{ country.country_flag }}</span>
            <span class="country-name">{{ country.country_name }}</span>
            <span class="country-code">({{ country.country_cca2 }})</span>
          </li>
        </ul>
      </ng-container>
    </div>
  `
})
export class CountryListComponent implements OnInit {
  private http = inject(HttpClient);

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

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

  ngOnInit(): void {
    this.http.get<Country[]>(
      `${this.BASE_URL}/countries/all?apikey=${this.API_KEY}&limit=50`
    ).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_all_countries(limit=100):
    """Fetch all countries from the API."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/all',
            params={
                'apikey': API_KEY,
                'limit': limit,
                'fields': 'id,country_name,country_short_iso,country_phone_code'
            }
        )
        response.raise_for_status()

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

# Usage
if __name__ == '__main__':
    countries = get_all_countries(limit=50)

    for country in countries:
        print(f"{country['country_name']} ({country['country_short_iso']})")

PHP

<?php

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

function getAllCountries($apiKey, $baseUrl, $limit = 100) {
    $url = sprintf(
        '%s/countries/all?apikey=%s&limit=%d',
        $baseUrl,
        urlencode($apiKey),
        $limit
    );

    $options = [
        'http' => [
            'method' => 'GET',
            'header' => 'Accept: application/json'
        ]
    ];

    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

    if ($response === false) {
        throw new Exception('Failed to fetch countries');
    }

    return json_decode($response, true);
}

// Usage
try {
    $countries = getAllCountries($apiKey, $baseUrl, 50);

    foreach ($countries as $country) {
        echo sprintf(
            "%s (%s)\n",
            $country['country_name'],
            $country['country_short_iso']
        );
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

PHP (cURL)

<?php

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

function getAllCountries($apiKey, $baseUrl, $limit = 100) {
    $url = sprintf(
        '%s/countries/all?apikey=%s&limit=%d',
        $baseUrl,
        urlencode($apiKey),
        $limit
    );

    $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 {
    $countries = getAllCountries($apiKey, $baseUrl, 50);

    foreach ($countries as $country) {
        echo sprintf(
            "%s (%s) - Phone: +%s\n",
            $country['country_name'],
            $country['country_short_iso'],
            $country['country_phone_code']
        );
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Error Handling

Status Code Description
200 Success - Returns array of countries
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": 401,
  "message": "Invalid API key",
  "error": "Unauthorized"
}