API Documentation - Endpoints & Examples

Search Country by Language

Overview

The Countries by Language endpoint returns a list of all countries where a specific language is spoken. This is valuable for localization projects, language learning applications, and international communication tools.


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

Returns a list of all countries that use a selected language.

Common Language Codes:

  • eng: English
  • spa: Spanish
  • fra: French
  • deu: German
  • por: Portuguese
  • ara: Arabic
  • zho: Chinese

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
language required, string ISO 639-3 language code. Example: "eng" for English
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": "f7a8b9c0-1234-5678-90ab-cdef12345678",
    "lang": "en",
    "country_name": "United States",
    "country_short_iso": "US",
    "country_phone_code": "1",
    "country_cca2": "US",
    "country_ccn3": "840",
    "country_cca3": "USA",
    "country_cioc": "USA"
  },
  {
    "id": "a1b2c3d4-5678-90ab-cdef-123456789012",
    "lang": "en",
    "country_name": "United Kingdom",
    "country_short_iso": "GB",
    "country_phone_code": "44",
    "country_cca2": "GB",
    "country_ccn3": "826",
    "country_cca3": "GBR",
    "country_cioc": "GBR"
  }
]

Code Examples

cURL

# Find all English-speaking countries
curl -X GET "https://api.countrydataapi.com/v1/countries/language?apikey=YOUR_API_KEY&language=eng"

# Find all Spanish-speaking countries
curl -X GET "https://api.countrydataapi.com/v1/countries/language?apikey=YOUR_API_KEY&language=spa"

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';

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

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

    const countries = await response.json();
    console.log(`Countries speaking ${languageCode}:`, countries);
    return countries;
  } catch (error) {
    console.error('Error fetching countries by language:', error);
    throw error;
  }
}

// Find all Spanish-speaking countries
getCountriesByLanguage('spa');

JavaScript (Axios)

import axios from 'axios';

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

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

    console.log(`Countries speaking ${languageCode}:`, data);
    return data;
  } catch (error) {
    console.error('Error fetching countries by language:', error.response?.data || error.message);
    throw error;
  }
}

// Find all French-speaking countries
getCountriesByLanguage('fra');

React

import { useState } from 'react';

const API_KEY = 'YOUR_API_KEY';

const POPULAR_LANGUAGES = [
  { code: 'eng', name: 'English' },
  { code: 'spa', name: 'Spanish' },
  { code: 'fra', name: 'French' },
  { code: 'deu', name: 'German' },
  { code: 'por', name: 'Portuguese' },
  { code: 'ara', name: 'Arabic' },
  { code: 'zho', name: 'Chinese' }
];

function LanguageCountrySearch() {
  const [language, setLanguage] = useState('');
  const [languageName, setLanguageName] = useState('');
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  async function handleSearch(langCode, langName) {
    if (!langCode) return;

    setLoading(true);
    setError(null);
    setLanguage(langCode);
    setLanguageName(langName);

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

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

  return (
    <div className="language-search">
      <h2>Find Countries by Language</h2>

      <div className="language-buttons">
        {POPULAR_LANGUAGES.map((lang) => (
          <button
            key={lang.code}
            onClick={() => handleSearch(lang.code, lang.name)}
            className={language === lang.code ? 'active' : ''}
          >
            {lang.name}
          </button>
        ))}
      </div>

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

      {countries.length > 0 && (
        <div className="results">
          <h3>{languageName}-speaking countries ({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 LanguageCountrySearch;

Vue 3

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

const API_KEY = 'YOUR_API_KEY';

const POPULAR_LANGUAGES = [
  { code: 'eng', name: 'English' },
  { code: 'spa', name: 'Spanish' },
  { code: 'fra', name: 'French' },
  { code: 'deu', name: 'German' },
  { code: 'por', name: 'Portuguese' },
  { code: 'ara', name: 'Arabic' }
];

const language = ref('');
const languageName = ref('');
const countries = ref([]);
const loading = ref(false);
const error = ref(null);

async function searchByLanguage(langCode, langName) {
  if (!langCode) return;

  loading.value = true;
  error.value = null;
  language.value = langCode;
  languageName.value = langName;

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

    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="language-search">
    <h2>Find Countries by Language</h2>

    <div class="language-buttons">
      <button
        v-for="lang in POPULAR_LANGUAGES"
        :key="lang.code"
        @click="searchByLanguage(lang.code, lang.name)"
        :class="{ active: language === lang.code }"
      >
        {{ lang.name }}
      </button>
    </div>

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

    <div v-if="countries.length > 0" class="results">
      <h3>{{ languageName }}-speaking countries ({{ 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, 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;
}

interface Language {
  code: string;
  name: string;
}

@Component({
  selector: 'app-language-search',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="language-search">
      <h2>Find Countries by Language</h2>

      <div class="language-buttons">
        <button
          *ngFor="let lang of languages"
          (click)="searchByLanguage(lang.code, lang.name)"
          [class.active]="language === lang.code"
        >
          {{ lang.name }}
        </button>
      </div>

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

      <div *ngIf="countries.length > 0" class="results">
        <h3>{{ languageName }}-speaking countries ({{ 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 LanguageSearchComponent {
  private http = inject(HttpClient);
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  languages: Language[] = [
    { code: 'eng', name: 'English' },
    { code: 'spa', name: 'Spanish' },
    { code: 'fra', name: 'French' },
    { code: 'deu', name: 'German' },
    { code: 'por', name: 'Portuguese' },
    { code: 'ara', name: 'Arabic' }
  ];

  language = '';
  languageName = '';
  countries: Country[] = [];
  loading = false;
  error: string | null = null;

  searchByLanguage(langCode: string, langName: string): void {
    this.loading = true;
    this.error = null;
    this.language = langCode;
    this.languageName = langName;

    this.http.get<Country[]>(
      `${this.BASE_URL}/countries/language`,
      {
        params: {
          apikey: this.API_KEY,
          language: langCode
        }
      }
    ).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_language(language_code):
    """Find all countries where a specific language is spoken."""
    try:
        response = requests.get(
            f'{BASE_URL}/countries/language',
            params={
                'apikey': API_KEY,
                'language': language_code
            }
        )
        response.raise_for_status()

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

# Usage
if __name__ == '__main__':
    # Find all Spanish-speaking countries
    spanish_countries = get_countries_by_language('spa')
    print(f"Spanish-speaking countries ({len(spanish_countries)}):")
    for country in spanish_countries:
        print(f"  - {country['country_name']} ({country['country_short_iso']})")

    print()

    # Find all French-speaking countries
    french_countries = get_countries_by_language('fra')
    print(f"French-speaking countries ({len(french_countries)}):")
    for country in french_countries:
        print(f"  - {country['country_name']} ({country['country_short_iso']})")

PHP

<?php

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

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

    $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 {
    // Find all Spanish-speaking countries
    $spanishCountries = getCountriesByLanguage($apiKey, $baseUrl, 'spa');
    echo "Spanish-speaking countries (" . count($spanishCountries) . "):\n";
    foreach ($spanishCountries as $country) {
        echo sprintf("  - %s (%s)\n", $country['country_name'], $country['country_short_iso']);
    }

    echo "\n";

    // Find all French-speaking countries
    $frenchCountries = getCountriesByLanguage($apiKey, $baseUrl, 'fra');
    echo "French-speaking countries (" . count($frenchCountries) . "):\n";
    foreach ($frenchCountries as $country) {
        echo sprintf("  - %s (%s)\n", $country['country_name'], $country['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 language parameter
401 Unauthorized - Invalid or missing API key
404 Not Found - No countries found with that language
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Something went wrong on our end

Error Response Example

{
  "statusCode": 404,
  "message": "No countries found with language: xyz",
  "error": "Not Found"
}

ISO 639-3 Language Codes

Code Language Countries
eng English USA, UK, Australia, Canada...
spa Spanish Spain, Mexico, Argentina...
fra French France, Canada, Belgium...
deu German Germany, Austria, Switzerland
por Portuguese Portugal, Brazil, Angola...
ara Arabic Saudi Arabia, Egypt, Morocco...
zho Chinese China, Taiwan, Singapore
jpn Japanese Japan
hin Hindi India
rus Russian Russia, Belarus, Kazakhstan