Explore the restcountries.com API

Our dashboard needs a list of countries to populate the dropdown selector. The REST Countries API at https://restcountries.com/ gives us country names along with their ISO codes.

The endpoint we need is https://restcountries.com/v3.1/all?fields=name,cca2,cca3. Notice the fields query parameter. This API requires you to explicitly specify which fields you want in the response.

The response is a JSON array of objects, with each object representing a country:

[
  // ... other countries
  {
    "name": {
      "common": "Iran",
      "official": "Islamic Republic of Iran",
      "nativeName": {
        "fas": {
          "official": "جمهوری اسلامی ایران",
          "common": "ایران"
        }
      }
    },
    "cca2": "IR",
    "cca3": "IRN"
  }
  // ... other countries
]

Defining the country data types

Let’s create a src/types/country.ts file to define the types for the API response:

// API response from the https://restcountries.com/v3.1/all endpoint
export interface PartialCountryData {
  name: {
    common: string;
    official: string;
  };
  cca2: string; // ISO 3166-1 alpha-2 code
  cca3: string; // ISO 3166-1 alpha-3 code
}

We call it PartialCountryData because the full API response contains many more fields. We only define types for the ones we actually need.

Next, define a CountryData interface for the shape our app will actually use:

// Internal type for the country data that is used in the application
export interface CountryData {
  name: string;
  code: string; // ISO 3166-1 alpha-2 code
}

Fetching the country list

Now let’s write a function that fetches country data and maps it to our CountryData interface. Create a src/services/countries.ts file:

import type { CountryData, PartialCountryData } from "@/types/country";

const REST_COUNTRIES_API =
  "https://restcountries.com/v3.1/all?fields=name,cca2,cca3";

// Fetch the list of countries from the REST Countries API
export async function fetchCountries(): Promise<CountryData[]> {
  const response = await fetch(REST_COUNTRIES_API);
  if (!response.ok) {
    throw new Error(`API request failed! with status: ${response.status}`);
  }
  const data: PartialCountryData[] = await response.json();

  // Map the API data to the required format
  return data.map((country) => ({
    name: country.name.common,
    code: country.cca2,
  }));
}

Checkpoint: Commit your progress.

git add .
git commit -m "dashboard-03: Define types and API function for restcountries.com"
git push