JS 012 — Communicating With External APIs

Greem
5 min readNov 19, 2023

Define API.

Give a few examples of APIs we’ve used.

What can generally be found in API documentation?

What is an API key?

Where can we find instructions for getting and using an API key?

Give an example of how an API key can be used.

We are in our final lecture of the first phase of the software engineering course. We are going to be tying together, especially with the fetch request. A lot of the fetch request that we’ve been making so far, have been completely local. We’ve been making these requests to endpoints that we’ve defined using JSON server.

Today we are going to be interacting with the external API. We are going to integrate into the application and a few others, some third party API, that don’t require API keys.

What is API?

Application Programming Interface

  • API is like a menu at a restaurant that lists all available dishes with a description.
  • A request is made for an option and the kitchen prepares and delivers the final product.
  • Simply put: an API is a software with protocols and procedures to send data back and forth between two separate computer i.e a web page or app and a user.
  • There are many third party API’s available that developers can use or you can build your own!

When you are building your project, you can utilize this API list.

go to : https://pokeapi.co/

add this in postman https://pokeapi.co/api/v2/pokemon/ditto

Retrieve pokemon information using GET request. With public API, we can’t edit or create a new object so we can’t send a POST request.

fetch('https://pokeapi.co/api/v2/pokemon/mewtwo/')
.then(res => res.json())
.then(data => {
//debugger
console.log(data)
})
goal of the day

Goal: when we search, books that match with the search word get displayed

We will use GOOGLE BOOK API

Google

API & Services

get API key

Get the API key, copy and past it on keys file.

Search for the BooksAPI and enable it

How to use keys.js

//index.html   
<head>
<meta charset="utf-8" />
<title>Flatburger</title>
<link rel="icon" href="./assets/hamburger-icon.png">
<link rel="stylesheet" type="text/css" href="styles.css" />
        <!-- file not pushed up to github to protect keys -->
<script src="src/keys.js"></script>
<!-- /////////////////////////////// -->
<script defer type="text/javascript" src="./src/index.js"></script>
</head>
keys.js to protect our key
.gitignore

We’ve got our own API key on google book api service. We tent to avoid including this in our Version Control (GIT) because we don’t want it to be public facing.

We want to protect our API keys.

So we store the apiKEY in the keys.js file and use .gitignore to ignore to upstream keys.js file

Notice these new code

function handleRenderSearch(){
console.log("hello")

const sectionElement = document.createElement('section')

sectionElement.innerHTML = `
<form id = "api-search">
<label> API Search <label>
<input type="text" name="search"></input>
<input type="submit"></input>
</form>`

document.querySelector("body").appendChild(sectionElement)
document.querySelector("#api-search").addEventListener("submit", handleAPIQuery)
}

handleRenderSearch()

Let’s write function that handles Google Books API search

  1. visit: https://developers.google.com/books/docs/v1/using

2. search for yourAPIkey to look for the REQUEST URL

This is one type of endpoint that we can send a GET request and retrieve information.

“flowers” is the search value that we want to derive from the UI. When users submit their form, we want to store that input value and search for the term.

3. Write GET request using the Fetch API

        //Handles Google Books API search
function handleAPIQuery(e){
e.preventDefault()
console.log(e.target.search.value)
//const search = document.querySelector('#search').value
const search = e.target.search.value
console.log(search)

fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}&maxResults=20&key=${apiKEY}`)
}

4. We get this endpoint, request URL by looking at the googleAPI doc.

fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}&maxResults=20&key=${apiKEY}`)

When it comes with working with 3rd party APIs, there’s a lot of digging in the documentation.

5. Write the first .then to get the promise with result response

 fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}+inauthor:keyes&key=${apiKEY}`)
.then(response => console.log(response.json()))

6. Take a look at the second .then method to look at the js obj.

            fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}&maxResults=20&key=${apiKEY}`)
.then(response => response.json())
.then(data => console.log(data.items))
.catch(console.error)

7. What is the data type? array. Let’s iterate it

fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}&maxResults=20&key=${apiKEY}`)
.then(response => response.json())
.then(data => data.items.map(item=> console.log(item.volumeInfo.title)))
.catch(console.error)

8. What do we want to do with this data? We want to render it and display it on the DOM

9. This is very similar to the functions that we previously wrote, utilizing the local GET request

10. Create a new function called, renderResultCard and invoke it

fetch(`https://www.googleapis.com/books/v1/volumes?q=${search}&maxResults=20&key=${apiKEY}`)
.then(response => response.json())
.then(data => data.items.map(item=> {
renderResultCard(item.volumeInfo)
}))
.catch(console.error)
}


function renderResultCard(itemInfo){
console.log("focused!", itemInfo)
}

11.

       function renderResultCard(itemInfo){
console.log("focused!", itemInfo)

// article as a parent container

// h2, two p elements, img

// add content using textContent

// wrap elements together into `article` element before appending it to <section>
}

12. code

        function renderResultCard(itemInfo){
console.log("focused!", itemInfo.authors)

// article as a parent container
const bookCard = document.createElement("article")


// h2, two p elements, img
const bookTitle = document.createElement("h2")
const bookAuthor = document.createElement("p")
const bookDescription = document.createElement("p")
const bookImage = document.createElement("img")


// add content using textContent
bookTitle.textContent = itemInfo.title
// if(itemInfo.authors) bookAuthor.textContent = itemInfo.authors.join(' and ')
itemInfo.authors? bookAuthor.textContent = itemInfo.authors.join(' and ') : null

bookDescription.textContent = itemInfo.description
itemInfo.imageLinks? bookImage.src = itemInfo.imageLinks.smallThumbnail : null

//add classname for styling
bookCard.className = "search-list"

// wrap elements together into `article` element before appending it to <section>
bookCard.append(bookTitle, bookAuthor, bookDescription, bookImage)

document.querySelector('section').append(bookCard)

}

--

--