Explore the World with the REST Countries API

Are you looking to access data about countries from around the world? REST Countries API is here to help! This public API allows developers to access a collection of information about countries covering topics like geography, demographics, and economics.

The REST Countries API provides data in JSON format for over 250 countries, with information on everything from country codes to national currencies. Here are some examples of how you can use the API to access and parse data in JavaScript.

Prerequisites

Make sure you have the following installed:

  • Node.js and npm

Making API Requests

Let's get started!

Installation

First, make sure to install the node-fetch package by typing the command below into your terminal:

$ npm install node-fetch

This package will allow you to make HTTP requests using JavaScript.

Example 1: List of All Countries

To retrieve a list of all the countries included in the API, you can use the following code:

const fetch = require('node-fetch');
 
fetch('https://restcountries.eu/rest/v2/all')
  .then(response => response.json())
  .then(data => console.log(data));

Example 2: Specific Country Data

To retrieve information about a specific country from the API, use the following code:

const fetch = require('node-fetch');
 
fetch('https://restcountries.eu/rest/v2/name/united kingdom')
  .then(response => response.json())
  .then(data => console.log(data));

The above code will return information on the United Kingdom.

Example 3: Country Capital

To retrieve the capital city of a specific country using the REST Countries API, use the following code:

const fetch = require('node-fetch');
 
fetch('https://restcountries.eu/rest/v2/name/united kingdom?fields=capital')
  .then(response => response.json())
  .then(data => console.log(data[0].capital));

This will return 'London', the capital city of the United Kingdom.

Example 4: Currency Exchange Rates

To return the exchange rate for a specific country, use the following code:

const fetch = require('node-fetch');
 
fetch('https://restcountries.eu/rest/v2/currency/gbp')
  .then(response => response.json())
  .then(data => console.log(data));

Example 5: Country Flag

To retrieve the flag image for a specific country, use the following code:

const fetch = require('node-fetch');
 
fetch('https://restcountries.eu/rest/v2/name/united kingdom?fields=flag')
  .then(response => response.json())
  .then(data => console.log(data[0].flag));

This will return the URL for the flag image for the United Kingdom.

Conclusion

The REST Countries API is a powerful tool that can help you access a wide range of information about countries around the world. With the examples above, you should now have a better understanding of how to make API requests using JavaScript and how to parse the resulting data. Happy exploring!

Related APIs