API Documentation - Endpoints & Examples

Find Country by ISO Code

Overview

The Country by Code endpoint allows you to search for countries using their ISO codes (CCA2, CCA3, CCN3, or CIOC). This is essential for international applications that need to validate or correlate country data using standardized international codes.


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

Returns country data according to the country code (CCA2, CCA3, CCN3, or CIOC)

Supported Code Types:

  • CCA2: Two-letter country code (e.g., "US", "ES", "FR")
  • CCA3: Three-letter country code (e.g., "USA", "ESP", "FRA")
  • CCN3: Three-digit numeric code (e.g., "840", "724", "250")
  • CIOC: International Olympic Committee code (e.g., "USA", "ESP", "FRA")

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 Account authentication key
code required, string CCA2, CCA3, CCN3, or CIOC code of the country
limitToken optional, number 1000 (default). Maximum number of countries to be returned
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"
  }
]

Code Examples

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

Error Handling

Status Code Description
200 Success - Returns country data
400 Bad Request - Missing required code parameter
401 Unauthorized - Invalid or missing API key
404 Not Found - No country found with that code
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Something went wrong on our end

Error Response Example

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

ISO Code Reference

Code Type Description Example
CCA2 ISO 3166-1 alpha-2 (2 letters) US, ES
CCA3 ISO 3166-1 alpha-3 (3 letters) USA, ESP
CCN3 ISO 3166-1 numeric (3 digits) 840, 724
CIOC International Olympic Committee code USA, ESP