Tutorials - JavaScript Fetch


Written by M.A.Corr

Published on: Sun Jun 02


Tags


Back to Blog

So as a fun way to come up with more blog posts(or filler if your a pessimist) I thought trying to write a few basic tutorials might work. So for this exciting first episode I’ll be covering how to make an API request, I’ll be using the NASA Photo of the Day as the example since I think they won’t complain.

So to begin with go to the NASA site here here and have a look around. Also get yourself an API key rather then using mine. The query we’ll be using is this https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY where DEMO_KEY will be our own API key’s respectively. We’ll be using Fetch to make the request.

This is a rewritten version of the tutorial since when I first wrote it the site was made using Next JS but now uses Astro. This has made some things easier since the .astro are closer to normal HTML and reduces the concepts needed to be explained.

Basic Version

To see the code in action or just the photo itself go here. To begin with we need to get the full response from the API itself. If your not using Astro and just a normal <script></script> file the JavaScript is essentially the same. Let’s add the following:

const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=${import.meta.env.NASA_API}`)

We’re using const since we not doing anything to the object beyond reading it’s fields so no need to use var or let. Since we want the request to be comepleted before continuing we add the await keyword to make it synchronus. Finally the meta.env.NASA_API is so I can get the API Key from a the .env file without having to have it in the code since it’s not included in source control. Let’s add another line to the code to get the needed data.

const photo = await response.json()

This gives us an object of photo from the following JSON.

{
  "copyright": "Dan Bartlett",
  "date": "2024-06-28",
  "explanation": "Not a paradox, Comet 13P/Olbers is returning to the inner Solar System after 68 years. The periodic, Halley-type comet will reach its next perihelion or closest approach to the Sun on June 30 and has become a target for binocular viewing low in planet Earth's northern hemisphere night skies. But this sharp telescopic image of 13P is composed of stacked exposures made on the night of June 25. It easily reveals shifting details in the bright comet's torn and tattered ion tail buffeted by the wind from an active Sun, along with a broad, fanned-out dust tail and slightly greenish coma. The frame spans over two degrees across a background of faint stars toward the constellation Lynx.",
  "hdurl": "https://apod.nasa.gov/apod/image/2406/13P_Olbers_2024_06_24_215434PDT_DEBartlett.jpg",
  "media_type": "image",
  "service_version": "v1",
  "title": "Comet 13P/Olbers",
  "url": "https://apod.nasa.gov/apod/image/2406/13P_Olbers_2024_06_24_215434PDT_DEBartlett1024.jpg"
}

If we were using TypeScript it would be a good idea to build a definition to make using it’s properties easier in the editor. However for this instance we only need to consider these parts of it:

For the Astro page it is being used in it looks like this:

    <p class="text-3xl text-center" style={{ marginBottom: '2.5rem' }}>
        {photo.title}
      </p>
      <p>Copyright: {photo.copyright}</p>
    <img src={photo.hdurl}/>
    <p>{photo.explanation}</p>

Lesson Over

Hopefully this has been useful or at least not made understanding how to use Fetch more difficult. This of course only looked at GET there are other methods an API call can use, a main one being POST to send something to the server. That might be the topic of another tutorial.