In this tutorial, we’ll walk you through creating a simple web application that displays the current moon phase using the Moon Phase API. We’ll use HTML, CSS, and JavaScript to build the application.
To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. You will also need a RapidAPI account and access to the Moon Phase API (https://rapidapi.com/MoonAPIcom/api/moon-phase).
Download this HTML file: https://pastebin.com/C03aNDd3 and call it index.html
This creates a basic webpage with a title and a section to display the moon phase.
Create a styles.css
file in the same directory as your index.html
file and add the following CSS:
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f0f0f0;
}
h1 {
color: #333;
}
#moon-phase {
background-color: #fff;
border-radius: 5px;
padding: 20px;
display: inline-block;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
#phase-text {
font-size: 1.2em;
font-weight: bold;
}
This will give your web page a simple and clean look.
Create an app.js
file in the same directory as your index.html
file and add the following JavaScript code:
const fetchMoonPhaseData = async () => {
try {
const response = await fetch("https://moon-phase.p.rapidapi.com/basic", {
"method": "GET",
"headers": {
"x-rapidapi-host": "moon-phase.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const data = await response.json();
displayMoonPhase(data.phase_name);
} catch (error) {
console.error("Error fetching data:", error);
displayMoonPhase("Error fetching moon phase data");
}
};
const displayMoonPhase = (text) => {
const phaseTextElement = document.getElementById("phase-text");
phaseTextElement.innerText = text;
};
fetchMoonPhaseData();
Replace YOUR_RAPIDAPI_KEY
with your actual RapidAPI key. This JavaScript code fetches the current moon phase data from the Moon Phase API’s Main Endpoint and displays it on the web page.
Open the index.html
file in your web browser, and you should see the current moon phase displayed on the page. You’ve successfully created a basic Moon Phase application