Connecting to APIs and Loops¶
Before we talk about loops, we need to have some data to loop over, so let’s get our data from Google Sheets using their Application Programming Interface (API).
What’s an API?¶
An API can be really thought of as an external appliance we are borrowing. In that sense, we are just plugging into it so we can access the data it provides.
Basically, an API allows different websites, computer devices, and data talk to each other.
Boo!!! Google’s API Depreciation!¶
Unforunately, in 2021 Google Depreciated the API for connecting to their files directly.
So we will have to do a work around, which means we won’t be using the built-in JavaScript fetch API
.
Instead we will use an open-source library called…
Sweet, (beard) papa-parse
!¶
Adding papa parse
to our html¶
We want to bring the library of sweet pastries into our site, so let’s bring in papa parse
directly online like we did with Leaflet.js.
Copy the following code and paste it into your <head>
tag in your index.html
file:
Your index.html
should look like this:
With papa parse
added to our site, we can now use it to connect to our Google Sheet.
Connecting to our Google Sheet with papa parse
¶
Go into our init.js
and change out the fetch
in the loadData()
function to the following:
function loadData(url){
Papa.parse(dataUrl, {
header: true,
download: true,
complete: function(results) {
console.log(results)
}
})
}
Let’s open up our console and see if our data is loaded!
If you see this:
Then you are in good shape for the next part of the lab!
⚽ Warm-up: Arrow Functions!¶
Can you convert the function?
Arrow functions help to cut down our code and make it easier to read. Are you able to convert the function below to an arrow =>
function?
function loadData(url){
Papa.parse(dataUrl, {
header: true,
download: true,
complete: function(results) {
console.log(results)
}
})
}
Answer
Since our data is showing up in our console, we can now start our loopy lab!
🏁Checkpoint¶
Check to see if your code is like the following before moving on: