Country Info Finder (API) with HTML, CSS & JavaScript
30 DAYS 30 PROJECT CHALLENGE
Day #21
Project Overview
The Country Info Finder is a beginner-friendly web project built with HTML, CSS, and JavaScript. It connects to the REST Countries API to fetch real-time information about countries and display the results in a clean and simple interface. Users can enter a country name and click the search button to get important details such as the country flag, name, capital, region, and population. The project also handles different search situations by trying an exact country match first and then checking for a partial match when needed.
This project is a great way to understand how JavaScript can communicate with an external API and use the returned data to update a webpage dynamically.
Key Features
- Country Search: Users can enter the name of a country in the search field and click the search button to retrieve its information from the API.
- REST API Integration: The project connects with the REST Countries API to retrieve real country data. This helps beginners understand how JavaScript applications can request and use information from external services.
- Exact Country Search: This project first performs an exact country-name search using the API. This approach helps return a more precise result when the user enters the complete country name.
- Partial Search Support: If the exact search does not return a result, the project performs another request that allows a partial country-name match.
- Country Details: After a successful search, the application displays information such as the country flag, common name, capital, region, and population. The information appears directly inside the result section.
- Dynamic API Results: JavaScript receives the API response and updates the webpage dynamically. Therefore, users can search for different countries without manually refreshing or changing the page.
- Loading Message: Result area displays a loading message while the application waits for the API response. This gives users immediate feedback after they start a search.
- Input Validation: The project checks whether the search field contains a country name before making an API request. If the field is empty, it shows an appropriate error message.
- Error Handling: The application handles unsuccessful API requests and displays a
"Country not found"message when it cannot retrieve matching country information. - Population Formatting: The country population is formatted with
toLocaleString(), which makes large numbers easier to read. For example, thousands and millions appear with appropriate separators. - Simple User Interface: The project uses a clean card-based layout with a search field, button, and result area. This keeps the main focus on searching for and viewing country information.
- Beginner-Friendly Structure: The project separates the HTML, CSS, and JavaScript responsibilities clearly. Therefore, beginners can easily understand how the interface, styling, and API functionality work together.
- Easy to Extend: The API provides additional country information that you can use to improve the project later. For example, you can add currencies, languages, time zones, borders, or other available country details.
What You'll Learn
- How to connect a JavaScript project with a public REST API.
- How to use
fetch()to request data from an external API. - How to handle API responses with
.then()and.catch(). - How to check an API response with
res.okbefore using the data. - How to work with JSON data returned from an API.
- How to display API data dynamically using
innerHTML. - How to use fallback API requests when an exact search does not return a result.
- How to use optional chaining with
country.capital?.[0]. - How to format population numbers with
toLocaleString().
HTML Code
HTML creates the basic structure of the Country Info Finder. The .country-container holds the complete application, while the <h2> displays the project title and the #countryInput field allows users to enter a country name, and the search button calls getCountryInfo() when clicked.
Additionally, the <div> with the result ID provides an empty area where JavaScript can display the country information or error messages. Finally, the page loads script.js at the bottom so the JavaScript can interact with these elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Country Info Finder</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="country-container">
<h2>Country Info Finder</h2>
<input
type="text"
id="countryInput"
placeholder="Enter country name"
/>
<button onclick="getCountryInfo()">Search</button>
<div class="result" id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Code
CSS controls the layout and appearance of the Country Info Finder. The universal selector sets box-sizing and the Segoe UI font, while the body uses Flexbox to center the application vertically and horizontally against the blue background. This .country-container creates the main white card with a fixed width, padding, rounded corners, centered text, and a shadow. Next, the input and button selectors make the search controls full width and give them consistent spacing and rounded edges.
The .result class adds space above the API response and aligns the information to the left. Finally, .result img styles the country flag, while .error displays failed searches and validation messages in red.
* {
box-sizing: border-box;
font-family: "Segoe UI", sans-serif;
}
body {
min-height: 100vh;
background: #042453;
display: flex;
justify-content: center;
align-items: center;
}
.country-container {
background: #ffffff;
width: 360px;
padding: 25px;
border-radius: 12px;
text-align: center;
box-shadow: 0 15px 30px rgba(0,0,0,0.1);
}
h2 {
margin-bottom: 15px;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border-radius: 6px;
border: 1px solid #ccc;
}
button {
width: 100%;
padding: 10px;
border: none;
border-radius: 6px;
background: #4f46e5;
color: white;
cursor: pointer;
}
.result {
margin-top: 15px;
text-align: left;
}
.result img {
width: 100%;
border-radius: 6px;
margin-bottom: 10px;
}
.error {
color: red;
text-align: center;
}
Javascript Code
JavaScript handles the complete API search process. The getCountryInfo() function first reads the country name from #countryInput and checks whether the user entered a value. If the input is empty, it displays an error message. Otherwise, it shows "Loading..." and sends a request to the REST Countries API using fetch().
First, the code tries an exact country name search with fullText=true. If that request fails, the .catch() block makes another API request without the exact-match option, which allows partial searches. When the API returns data, the showCountry() function displays the flag, common country name, capital, region, and formatted population. Finally, if both requests fail, the code displays "Country not found" instead of leaving the result area empty.
function getCountryInfo() {
const input = document.getElementById("countryInput").value.trim();
const result = document.getElementById("result");
if (!input) {
result.innerHTML = `<p class="error">Please enter a country name</p>`;
return;
}
result.innerHTML = "Loading...";
// 1️⃣ Try exact match first
fetch(`https://restcountries.com/v3.1/name/${input}?fullText=true`)
.then(res => {
if (!res.ok) throw new Error("Exact not found");
return res.json();
})
.then(data => showCountry(data[0]))
.catch(() => {
// 2️⃣ Fallback to partial match
fetch(`https://restcountries.com/v3.1/name/${input}`)
.then(res => {
if (!res.ok) throw new Error("Not found");
return res.json();
})
.then(data => showCountry(data[0]))
.catch(() => {
result.innerHTML = `<p class="error">Country not found</p>`;
});
});
function showCountry(country) {
result.innerHTML = `
<img src="${country.flags.svg}" alt="Flag">
<p><strong>Name:</strong> ${country.name.common}</p>
<p><strong>Capital:</strong> ${country.capital?.[0] || "N/A"}</p>
<p><strong>Region:</strong> ${country.region}</p>
<p><strong>Population:</strong> ${country.population.toLocaleString()}</p>
`;
}
}
Related Projects
Day 19 : Loan EMI Calculator
Calculates monthly loan EMI based on amount, interest rate, and tenure.
Concepts: Mathematical calculations, form handling, dynamic UI updates.
Day 23 : GitHub User Finder
Searches and displays GitHub user profiles using the GitHub public API.
Concepts: API fetching, async data handling, dynamic UI rendering.
Day 25 : Stock Price UI (Mock / API)
Displays stock prices and daily changes using mock data with API-ready structure.
Concepts: UI state management, dynamic rendering, data simulation.