Code Examples

Practical examples of integrating Moon API in different programming languages and frameworks.

JavaScript/Node.js

Using Moon API with JavaScript in both browser and Node.js environments.

javascript
// Using Fetch API
const options = {
  method: 'GET',
  headers: {
    'X-RapidAPI-Key': 'YOUR_API_KEY',
    'X-RapidAPI-Host': 'moon-phase.p.rapidapi.com'
  }
};

fetch('https://moon-phase.p.rapidapi.com/phase', options)
  .then(response => response.json())
  .then(data => {
    console.log('Current moon phase:', data.phase);
    console.log('Illumination:', data.illumination + '%');
  })
  .catch(err => console.error(err));
javascript
// Using Async/Await with Axios
const axios = require('axios');

async function getMoonPhase() {
  try {
    const response = await axios.get('https://moon-phase.p.rapidapi.com/phase', {
      headers: {
        'X-RapidAPI-Key': 'YOUR_API_KEY',
        'X-RapidAPI-Host': 'moon-phase.p.rapidapi.com'
      }
    });
    
    return response.data;
  } catch (error) {
    console.error('Error fetching moon phase:', error);
    throw error;
  }
}

Python

Integration examples using Python with the requests library.

python
import requests

url = "https://moon-phase.p.rapidapi.com/phase"

headers = {
    "X-RapidAPI-Key": "YOUR_API_KEY",
    "X-RapidAPI-Host": "moon-phase.p.rapidapi.com"
}

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    data = response.json()
    
    print(f"Moon Phase: {data['phase']}")
    print(f"Illumination: {data['illumination']}%")
except requests.exceptions.RequestException as e:
    print(f"Error fetching moon phase: {e}")

PHP

Using Moon API with PHP's cURL extension.

php
<?php
$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => "https://moon-phase.p.rapidapi.com/phase",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTPHEADER => [
        "X-RapidAPI-Key: YOUR_API_KEY",
        "X-RapidAPI-Host: moon-phase.p.rapidapi.com"
    ]
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "Error: " . $err;
} else {
    $data = json_decode($response, true);
    echo "Moon Phase: " . $data['phase'] . "\n";
    echo "Illumination: " . $data['illumination'] . "%";
}

React Integration

Example of using Moon API in a React component.

jsx
import React, { useState, useEffect } from 'react';

function MoonPhase() {
  const [moonData, setMoonData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchMoonPhase = async () => {
      try {
        const response = await fetch('https://moon-phase.p.rapidapi.com/phase', {
          headers: {
            'X-RapidAPI-Key': 'YOUR_API_KEY',
            'X-RapidAPI-Host': 'moon-phase.p.rapidapi.com'
          }
        });
        
        if (!response.ok) throw new Error('API request failed');
        
        const data = await response.json();
        setMoonData(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchMoonPhase();
  }, []);

  if (loading) return 
Loading...
; if (error) return
Error: {error}
; return (

Current Moon Phase

Phase: {moonData.phase}

Illumination: {moonData.illumination}%

); }

Error Handling Examples

Best practices for handling API errors in different languages.

💡

Error Handling Tips

  • Always implement proper error handling
  • Check response status codes
  • Handle network timeouts
  • Implement retry logic for transient failures