API's Are Awesome: Using Nasa's open API

Photo by Kai Pilger on Unsplash

API's Are Awesome: Using Nasa's open API

Using NodeJS

·

4 min read

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

In this blog, we are going to make a website that shows the APOD (Astronomy Picture of the Day)

The code will be available at:

Setting up the Coding Environment

Make a new folder called "apod" and in the folder make a new file called index.js

Adding the basic modules

In this project, we are going to use node-fetch for fetching the API responses and express to make the website. So install these by typing out the following lines in a terminal:

$ cd apod
$ npm install node-fetch express

After the following packages have finished installing, import them to your file by adding the following lines at the start of index.js:

const express = require('express')
const fetch = require('node-fetch')

Starting the Express server

We need to start the Express server in order for our website to work, add these lines to the file:

let app = express()

app.get('/', (req, res) => {
    res.send('Hello World')
})

app.listen(8080, () => {
    console.log('Server running at 8080')
})

Now if we run the index.js file and head over to localhost:8080 we should see: Screenshot 2022-03-22 at 1.43.16 PM.png

Start using the API

Head over to api.nasa.gov and sign yourself up for an API key. Screenshot 2022-03-22 at 1.34.59 PM.png Once you get your API key you can test it out by going to api.nasa.gov/planetary/apod?api_key=YOUR_AP..

And there's your data: Screenshot 2022-03-22 at 1.47.43 PM.png

Using node-fetch to retrieve the data from the URL

By default, node-fetch's syntax is

fetch(URL, options)
.then(res => res.json())
.then(data => {
    // Do something with the data
})

Plugging in the URL with the syntax we get

fetch('https://api.nasa.gov/planetary/apod?api_key=YOUR_API_KEY')
.then(res => res.json())
.then(data => {
    // Do something with the data
})

We haven't added our options variable in the node-fetch function as the default GET request is the only method we need to fetch from the API.

We can add the lines above in our app.get() function, this will make it so that whenever the page is loaded, the API gets fetched. The total code should look something like this:

const express = require('express')
const fetch = require('node-fetch')

let app = express()

app.get('/', (req, res) => {
    fetch('https://api.nasa.gov/planetary/apod?api_key=YOUR_API_KEY')
    .then(res => res.json())
    .then(data => {
        // Do something with the data
    })
    res.send('Hello World')
})

app.listen(8080, () => {
    console.log('Server running at 8080')
})

Inspecting the JSON object to get the Image URL

If we add a console.log(data) in the fetch function just like this

fetch('https://api.nasa.gov/planetary/apod?api_key=YOUR_API_KEY')
.then(res => res.json())
.then(data => {
    console.log(data)
})

and re-run the code, and open up localhost:8080 our output In the terminal should look something like:

{
  copyright: 'Göran Strand',
  date: '2022-03-22',
  explanation: "What's that in the sky? An aurora. A large coronal mass ejection occurred on our Sun earlier this month, throwing a cloud of fast-moving electrons, protons, and ions toward the Earth. Part of this cloud impacted our Earth's magnetosphere and, bolstered by a sudden gap, resulted in spectacular auroras being seen at some high northern latitudes. Featured here is a particularly photogenic auroral corona captured above a forest in Sweden from a scenic perch overlooking the city of Östersund. To some,  this shimmering green glow of recombining atmospheric oxygen might appear like a large whale, but feel free to share what it looks like to you.  The unusually quiet Sun of the past few years has now passed. As our Sun now approaches a solar maximum in its 11-year solar magnetic cycle, dramatic auroras like this are sure to continue.    Open Science: Browse 2,700+ codes in the Astrophysics Source Code Library",
  hdurl: 'https://apod.nasa.gov/apod/image/2203/WhaleAurora_Strand_1500.jpg',
  media_type: 'image',
  service_version: 'v1',
  title: 'A Whale of an Aurora over Swedish Forest',
  url: 'https://apod.nasa.gov/apod/image/2203/WhaleAurora_Strand_960.jpg'
}

Notice how the Image URL is in the hdurl and url parameters in the output? To grab only the hdurl we need to change console.log(data) to console.log(data.hdurl), this tells NodeJS to grab the hdurl parameter in the object.

Re-run the code and reload the website and you should see the output of only the hdurl.

https://apod.nasa.gov/apod/image/2203/WhaleAurora_Strand_1500.jpg

Using the Image URL to display the image on the website

Now that we have a source for the Image URL we need to serve the image onto the website.

To do this we can put the res.send function into the fetch function, and replace 'Hello World' with ''

Confused? This is what your code should look like:

const express = require('express')
const fetch = require('node-fetch')

let app = express()

app.get('/', (req, res) => {
    fetch('https://api.nasa.gov/planetary/apod?api_key=Uw5jRuEmRfVAFQkHjJJ63CjvZNOPNBm6GeNroXli')
    .then(res => res.json())
    .then(data => {
        res.send('<img src='+data.hdurl+'>')
        console.log(data.hdurl)
    })
})

app.listen(8080, () => {
    console.log('Server running at 8080')
})

Now, Re-run the script one last time and open up localhost:8080 and you should see the Apod image on the website, Cool.

Happy Coding!