• NICK LUSK
  • NICK LUSK
  • NICK LUSK
  • NICK LUSK
  • NICK LUSK
  • NICK LUSK
  • NICK LUSK

Several Ways JavaScript Can Get Data From An API

In simpler times the pages of a website were static files that just sat there, like pages in a book waiting to be turned. Wipe the mist out of your eyes because those days are gone. Either you are hitting a database or pulling various parts of a page from a file system or you are doing it the way it should be done by making an API call and building a page with the response.

Making an API call is a lot like skinning a cat, there is more than one way to do it. I am going to try and give examples both plentiful and diverse. I am not sure anyone could make a comprehensive list of methods, which is a testament to the unreasonably large number of front-end technologies that objectively do the same thing.

JSONPlaceholder is a free online REST API that is so good at its job I would be out of my gourd not to use it. Specifically, I’m going to use https://jsonplaceholder.typicode.com/todos.

I have included just enough HTML around the JavaScript in each example for you to be able to copy and paste into your IDE and see results without having to figure anything out.

Make an API call, retrieve a value, write value to page. Several different ways. Starting now.

XMLHttpRequest

See the Pen XMLHttpRequest API Call - JSON to <table> by Nick Lusk (@fearofmusic) on CodePen.

View on Codepen.io

Fetch API

Fetch really comes into town ready to do business with any method or API you can fling at it. Fling being a distant cousin of fetch, of course. Let's take a look at the full list of all possible fetch options

let promise = fetch(url, {
method: "GET", // POST, PUT, DELETE, etc.
headers: {
// the content type header value is usually auto-set
// depending on the request body
"Content-Type": "text/plain;charset=UTF-8"
},
body: undefined // string, FormData, Blob, BufferSource, or URLSearchParams
referrer: "about:client", // or "" to send no Referer header, // or an url from the current origin
referrerPolicy: "no-referrer-when-downgrade", // no-referrer, origin, same-origin...
mode: "cors", // same-origin, no-cors
credentials: "same-origin", // omit, include
cache: "default", // no-store, reload, no-cache, force-cache, or only-if-cached
redirect: "follow", // manual, error
integrity: "", // a hash, like "sha256-abcdef1234567890"
keepalive: false, // true
signal: undefined, // AbortController to abort request
window: window // null
});

So let's get started with the first fetch example.

See the Pen Fetch API Call - JSON to <table> by Nick Lusk (@fearofmusic) on CodePen.

View on Codepen.io

Fetch with Async and Await

I know, the previous example actually has async and await in it. Well here's another one, await for it.

See the Pen Fetch with Async and Await - JSON to <table> - by Nick Lusk by Nick Lusk (@fearofmusic) on CodePen.

View on Codepen.io

jQuery ajax method

jQuery has a specific method called getJson() which is shorthand for an .ajax() call that has the dataType json. So use that, maybe. Maybe one of them has better performance, I don't know.

See the Pen jQuery ajax API call - JSON to <table> by Nick Lusk (@fearofmusic) on CodePen.

View on Codepen.io

Axios

Axios is a library for making HTTP requests. Specifically, it makes promise based requests. It also works in both original JavaScript and most of your fancy ones like React. It might work in all of them, I'm honestly not sure. We are going to employ it wrapped in the warm arms of plain JavaScript.

Doing it the quaint way means we have to include it in the HTML. Like you would with jQuery. Use the CDN.

<script src='https://unpkg.com/axios/dist/axios.min.js'></script>

Go buy yourself a hat...and get ready to hold on to it because we are changing things up this round. Instead of todo items, this time we're grabbing users. Not only that, we're only displaying a couple of items per user and combining them in a novel way. We get the name, their hometown, and their catch phrase. Neat. Added some sophistication to the style, too.

See the Pen Axios API Call - JSON to <ol> by Nick Lusk (@fearofmusic) on CodePen.

View on Codepen.io