Nona Blog

How to be h-API

When I first started out programming (which is basically yesterday lol) , the word API was spoken so matter of factly that I felt stupid for not understanding what it is and how it works.

“Bro, can you link up to the API and get the data? Dude, all you need to do is access the API. Homie, talk to the API etc…” This solidified my feeling of being a dumbass noob. Therefore the pursuit of being less of a dumbass is what inspired this post.

The goals of this post will be to:

  1. Define in an easy-to-understand way what an API is
  2. To create a NASA open API account
  3. Explore the NASA API and get comfortable with the documentation
  4. Create a react app using the API
  5. Be less of a dumbass
Why Backstreet Boys? Because space :P!

1. WHAT THE FRACK IS AN API?

API is an acronym for Application Programming Interface (yeah totally explains it … NAAAAAT). Essentially an API is a gateway that you can use to access information from a data source.

A simple example would be if you wanted a glass of whiskey, let’s use my favorite type of whiskey the Lagavulin 16 YO (think of this as being the data you want). You would go to a bar (the database). However, you would need some way to get the whiskey from the bar to your cup. This is where the bartender (API) comes in. You tell her (yeah I’m progressive) that you want a double Lagavulin on the rocks (API call or query). She first asks for your ID (API key) to make sure you’re legit. After verifying that you’re old enough to drink the juice of the gods, she finds the bottle of Lagavulin 16 YO and pours you a cup of the sumptuous whiskey (my mouth is literally watering) and serves it to you (API return).

My epic drawing skills, trying to explain with a picture what the words are saying

You’re really happy because you didn’t need to rummage through the entire bar to find the bottle and pour your own damn whiskey, and now you can simply enjoy it’s goodness without much work. The bar is also happy because the bartender made sure you got exactly what you wanted while making sure you were of the correct drinking age and that you weren’t able to fool around with the actual bar itself.

This is why an API is useful, it lets you access only the data you want from massive data sources like YouTube, Banks etc… very quickly without needing to search through the entire database every time.

2. TO INFINITY AND BEYOND!

I won’t comment on what is happening in this picture. #DisneyDoggyStyle

Now that we’ve got a basic idea of what an API is, let’s shuttle off an example. We will be using the NASA open API for this one and you can find the website here.

We first need to start off by getting an API key so that NASA will give us top-secret access to all of its data (sadly this is just a joke 🙁 ). To do this click on the API Key Sign Up button.

Sign up and you will then be shown your API key. They will also email it to you so don’t worry too much about storing it.

Now that we have the API key we can start harvesting NASA’s data. One small step for APINoob, one giant leap for APINoobsEverywhere.

3. APOLLO API

Now that we have the API key and are ready for lift off, we need a few things to get our app flight-ready.

  1. We need to create-react-app
  2. We need to install axios

I’m going to assume you know how to set up and use create-react-app, if you don’t here’s a quick vid to get you up to speed. I called my app Nasa.

// Use the following line in your CLI to initilize
// a React app called Nasa
create-react-app Nasa

After creating your react app we need to install axios. Axios is a really great library that will help us make API calls very easily.

// Use the following line in your CLI
// Make sure you're in your app directory
// That would be Nasa for me
npm install axios

Okay great now that we’re all fueled up its about damn time I told you what our App is going to do (yep I’m flirt but I promise I put out (◡ ‿ ◡ ✿)).

We are going to take NASA’s APOD (Astronomy Picture of the Day) using the NASA API and display it in our browser. Very simple (or is it heheh — no really it’s pretty chilled).

The first point of call is then to look at the NASA APOD API documentation (essentially instructions on how to use the NASA API).

DO NOT be afraid (˼●̙̂ ̟ ̟̎ ̟ ̘●̂˻). The word documentation used to give me crazy anxiety but once you sit down for a few seconds and actually look at it you get this epiphany╭(◔ ◡ ◔)/ and wonder why you were being such a scaredy cat.

This is the APOD (Astronomy Picture of the Day) documentation

This is the first line:

GET https://api.nasa.gov/planetary/apod 

There are two parts to this:

GET is essentially a function that says to the NASA API that we want get some of their star-tastic data

https://api.nasa.gov/planetary/apodis the url we should use to access the data we want (essentially the directions to the bar and the bottle of Lagavulin from our example). Since we want APOD data, it makes sense that the link would contain ‘apod’ in it

Accessing data is most commonly referred to as a performing a query. Hence the next line — Query Parameters. These parameters are the different options we can use to specify the data we want.

date allows us to choose a particular APOD Image based on the date. So we could chose the 2nd of March 1993 (my birthday- yes I do accept gifts) and we could get the APOD for that day (although I’m not sure if they were taking pictures all the way back then…)

hd is a boolean (i.e. true or false) value we can use if we want the image to be hd (true) or if we would prefer simply a standard image (false)

api_key is the key we got right in the beginning which allowed us access to NASA’s data

Putting this all together, an example request url would look something like this:

https://api.nasa.gov/planetary/apod
?date=1993-03-02
&hd=true
&api_key=o6JapvYNSOFqep27eXiK09IZNmYNqzpZx0dBe1JI

This should send us info about the hd APOD for the 2 March 1993, and I’ll be allowed access because of my API key.

Okay now I know you’re board of this damn reading SO LETS LIFTOFF AND GET THIS APP ROCKET ROLLIN!

4. DEATHSTAR

Let’s get onto the same page! Follow the following instructions:

  1. Delete all the files in the src folder
  2. Create an index.js file in src
  3. Copy the code below to initialize the app
// Importing React libraries
import React from 'react'
import ReactDOM from 'react-dom'

// Might as well import axios in the mean time
import axios from 'axios'

// Create an App class
class App extends React.Component {
// Initialize state (we will need this later)
    state = { picture:null }

    render(){
        return <div>Han Solo or Captain Kirk?</div>
    }
}

// Render the App to the DOM
ReactDOM.render(
    <App />,
    document.querySelector('#root')
)

Obviously Captain Kirk…

If you’ve done everything correctly run npm start in your console you should see the question “Han Solo or Captain Kirk?” appear in your browser.

Next we’re gonna set up what we need to begin our API adventure (insert this between your axios import and the App class):

import axios from 'axios'

// Create a KEY variable for the NASA API key you received earlier
// Make sure it's in quotations
const KEY = 'YOUR KEY'

// Create a nasa variable that we will use to perform our API request
// Axios is going to create a url for us that conforms to NASA's
// specifications
let nasa = axios.create({
  
// baseURL is the url we saw ealier to access the APOD data
    baseURL: 'https://api.nasa.gov/planetary/apod',
  
// params are the query parameters we can set
// I am chosing the date of 10 February 2019 (when I wrote this blog)
// I chose HD to be true (cause why not :)?)
// Finally the api_key is simply the key we got from NASA
    params: {
        date: '2019-02-10', // Don't forget the quotations
        hd: true,
        api_key: KEY
    }
  
 // Essentially this will create a url that looks like this
 // https://api.nasa.gov/planetary/apod?date=2019-02-10&hd=true&api_key=KEY
})

class App extends React.Component {

Okay great, now we can query the NASA database and give it the correct url to retrieve the data we want. If you go to the url that is generated (https://api.nasa.gov/planetary/apod?hd=true&api_key=YOURKEY) we get back a JSON file that looks like the following:

{
"date": "2019-02-10",
"explanation": "What does Venus look like beneath its thick clouds?  These clouds keep the planet's surface hidden from even the powerful telescopic eyes of Earth-bound astronomers.  In the early 1990s, though, using imaging radar, NASA's Venus-orbiting Magellan spacecraft was able to lift the veil from the face of Venus and produced spectacular high resolution images of the planet's surface.  Colors used in this computer generated picture of Magellan radar data are based on color images from the surface of Venus transmitted by the Soviet Venera 13 and 14 landers.  The bright area running roughly across the middle represents the largest highland region of Venus known as Aphrodite Terra. Venus, on the left, is about the same size as our Earth, shown to the right for comparison.",
"hdurl": "https://apod.nasa.gov/apod/image/1902/VenusEarth_MagellanApollo17_3000.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Venus Unveiled",
"url": "https://apod.nasa.gov/apod/image/1902/VenusEarth_MagellanApollo17_1080.jpg"
}

From this we can see that we will only really need the hdurl part to get the picture we want — put this in the memory bank for now.

We need to now actually talk to the NASA API and say “Howdy, gimme some of that sweet APOD data you have there” — all we’ve done until now is figure out what we want to drink but we haven’t told the bartender to get it for us. We will need two functions for this to work. First we create a function to handle querying the NASA database for the APOD we want and then adjust our state so that it displays the APOD picture:

// We're creating a function to handle retrieving
// the image from the NASA API

// Function is asynchronous because talking to the API
// isn't instantaneous (your bartender can't instantly
// give you your drink when you ask him for it)
handlePic = async () => {
// Create a response variable that retrieves the data
    const response = await nasa.get()
// Change the state of picture to be the hdurl
    this.setState({
        picture: response.data.hdurl
    })
};

SideNote: So you might be wondering how I knew to use response.data.hdurl to get the picture. The way I figured this out was by console logging the response variable to see that what we want can be found in data and remembering from the JSON earlier that what we want is hdurl.

We then need to use the componentDidMount function , so that the picture will actually be displayed on the page:

// Use the componentDidMount function to use the 
// handlepic function we just created and therefore
// render the picture to the screen
componentDidMount() {
    this.handlepic()
}

And that’s it. If you run the app you should get this APOD on your screen (although the picture is massive so you may want to reduce its size in CSS):

WE ARE OFFICIALLY API BۜROS :)!

Let’s summarize what we learned:

  1. Using a bar and bartender as a metaphor for an API helps with understanding what the hell it actually is.
  2. How to read API documentation
  3. Axios is a great library to use when dealing with an API
  4. How to implement a working application to actually make API calls and render stuff to the browser
  5. “To Boldly Go Where No Man Has Gone Before…” #APINoobNoMore

Two things are infinite: the universe and human stupidity; and I’m not sure about the universe.”

Add comment