How to make an API Wrapper in Nodejs
Ever wanted to delve into the realm of APIs but felt daunted by the process? I'll be detailing the creation of a Nodejs NASA Open API Wrapper (mouthful!) – a beginner-friendly guide crafted from my own learning experiences.
Project Setup
Step 1: Create Folders and Files
- Create a folder for your project.
- Inside the root of the project, create three files:
app.js
,server.js
, and a folder namedlib
. - Inside the
lib
folder, create a file namedclient.js
.
Step 2: Add Initial Files
Your project structure should look like this:
- YourProjectName/
- lib/
- client.js
- app.js
Step 3: Initialize npm and Install Packages
In your terminal or command prompt, navigate to your project's root folder and run this command:
npm init -y npm install axios
This will initialize a package.json
file and install the necessary package (axios
) for your project.
client.js
1. Let's start by importing the Axios library, which is commonly used for making HTTP requests.
const axios = require('axios');
2. Create a constructor. It takes an apiKey
parameter and sets various base URLs required for different API endpoints.
module.exports = class NASA_OpenAPI {
constructor(apiKey) {
this.baseURL_APOD = 'https://api.nasa.gov/planetary/apod';
this.baseURL_MarsPhotos='https://api.nasa.gov/mars-photos/api/v1/rovers/';
this.apiKey = apiKey;
}}
3. Create a async methods to fetch Data
- This asynchronous method uses Axios to perform an HTTP GET request to fetch the Astronomy Picture of the Day (APOD) from NASA's API. It constructs the request URL using the
baseURL_APOD
andapiKey
.
async getAPOD() {
try {
const response = await axios.get(`${this.baseURL_APOD}?api_key=${this.apiKey}`);
return response.data;
} catch (error) {
throw new Error(`Failed to fetch APOD: ${error.message}`);
}
}
- Similarly, the
getRover()
method fetches data related to Mars rovers from the API. Depending on theroverName
parameter, it constructs the URL to request data for a specific rover or all rovers.
async getRover(roverName) {
try {
let url;
if (roverName === '') {
url = `${this.baseURL_MarsPhotos}?api_key=${this.apiKey}`;
} else {
url = `${this.baseURL_MarsPhotos}${roverName}?api_key=${this.apiKey}`;
}
const response = await axios.get(url);
return response.data;
} catch (error) {
throw new Error(`Failed to fetch Rover: ${error.message}`);
}
}
--Note
There are several endpoints used to interact with the NASA API. These endpoints are constructed using base URLs and appended with specific paths to access different functionalities of the API.
For your project, referring to the API documentation reveals these endpoints, tailoring your access to suit your needs.
Here are the endpoints utilized in the code:
-
this.baseURL_APOD
: Endpoint for Astronomy Picture of the Day (APOD)- Used to retrieve the Astronomy Picture of the Day (APOD) from NASA's API. It fetches the image, description, and other related information about the chosen day's astronomical picture.
-
this.baseURL_MarsPhotos
: Endpoint for Mars Rover Photos- Used for accessing information about Mars rovers and their photos. It's used in the
getRover()
method to retrieve data related to Mars rovers.
- Used for accessing information about Mars rovers and their photos. It's used in the
app.js
We use the NASA_OpenAPI
class, that we've crafted in our client.js
file. It encapsulates methods to interact with NASA's API.
const NASA_OpenAPI = require('./lib/client.js'); // Importing our custom NASA_OpenAPI class
const API_KEY = 'YOUR_NASA_API_KEY_HERE'; // Your NASA API key
const nasa_api = new NASA_OpenAPI(API_KEY); // Creating an instance of NASA_OpenAPI with your API key
Here's what's happening in the subsequent code block:
(async () => {
try {
const dataAPOD = await nasa_api.getAPOD();
console.log('Data on APOD', dataAPOD);
const DataRover = await nasa_api.getRover('');
console.log('Data on Rover', DataRover);
} catch (error) {
console.error('Error:', error.message);
}
})();
-
nasa_api.getAPOD()
: This method makes a request to NASA's Astronomy Picture of the Day (APOD) endpoint using the instantiatednasa_api
object. It fetches the APOD data and stores it in thedataAPOD
variable. -
nasa_api.getRover('')
: Invoking thegetRover()
method without a specified rover name retrieves data for all Mars rovers. The information is stored in theDataRover
variable.
Setting Up a Frontend Preview: Creating a Server with Express for Data Display
Should you desire to preview or test the data on a frontend, let's proceed by creating both a server.js
and an index.html
. We'll employ Express as our server.
Your project structure should now look like this:
- YourProjectName/
- lib/
- client.js
- app.js
- server.js
- index.html
In your terminal or command prompt, navigate to your project's root folder and run these commands:
npm install express
This will install Express in your project.
The provided code serves as an Express server
// server.js
const express = require('express');
const NASA_OpenAPI = require('./lib/client.js');
const API_KEY = 'YOUR_NASA_API_KEY_HERE';
const path = require('path');
const app = express();
const nasa_api = new NASA_OpenAPI(API_KEY);
// Serves the index.html file when the root URL '/' is accessed
app.get('/', (req, res) => {
try {
const indexPath = path.join(__dirname, 'index.html');
res.sendFile(indexPath);
} catch (error) {
console.error('Error sending index.html:', error);
res.status(500).send('Error sending index.html');
}
});
// Endpoint '/getAPOD' is used to fetch Astronomy Picture of the Day (APOD) data
app.get('/getAPOD', async (req, res) => {
try {
const apod = await nasa_api.getAPOD();
res.json(apod);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start the server and listen on the defined port
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
The following code is our frontend. It contains JavaScript logic to fetch the APOD data from the server and display the corresponding image upon a button click.
<!-- index.html-->
<body>
<h1>NASA Image of the Day</h1>
<button id="getAPOD">Get NASA Image of the Day</button>
<div id="imageContainer"></div>
<script>
document.getElementById('getAPOD').addEventListener('click', async () => {
try {
const response = await fetch('/getAPOD');
const data = await response.json();
// Check if the received data contains an image URL
if (data && data.url) {
const imageContainer = document.getElementById('imageContainer');
const imgElement = document.createElement('img');
imgElement.src = data.url;
imgElement.alt = 'NASA Image of the Day';
imageContainer.innerHTML = '';
imageContainer.appendChild(imgElement);
} else {
console.error('No image URL found in the data');
}
} catch (error) {
console.error('Error fetching image:', error);
}
});
</script>
</body>
This setup demonstrates a simple way to interact with a server hosting NASA API data and showcase the APOD image on a frontend interface.
I hope this guide proves helpful! Feel free to reach out if you have any questions or need further assistance on your API wrapper.
Happy coding!