Introduction to APIs

Visual Diagram of APIs

Web APIs Overview

  • What is an API?
  • What APIs Can Access
  • REST APIs

API = Application Programming Interface

Have you ever wondered how Facebook is able to automatically display your Instagram photos?

Have you ever wondered how the Starbucks store locator gives you directions to the closest Starbucks? It asks Google Maps!

As a programmer, you don't want to install a database of all the world’s addresses and algorithms in order to search them on your server. (hint: just use Google's API)

Cartoon about computer magic

A helpful diagram

APIs like a card catalog at a library

You can’t use the card catalog yourself because you don’t have access and you don’t know how to use it.

Imagine your website is looking for a book...

Google Book Database API

Your website doesn’t know how to access or read the Google Books database, but it can use the Google Books API to request the book.

How is an API like a librarian?

Librarian API
Human Language (like English) HTTP protocol
Question containing details (title and author) Request containing parameters (title and author)
Answer JSON response including URL

Practice: Search for a Book

  • Open this URL in your browser: https://www.googleapis.com/books/v1/volumes?q=little+women+inauthor:alcott
  • Congratulations! You’ve successfully made an API request. The response has more information than we needed, but it does contain the download URL we were looking for.
  • Try replacing the parameters (the part after “q=”) to find another book. For example: https://www.googleapis.com/books/v1/volumes?q=very+hungry+caterpillar

Companies use APIs to boost traffic and business

  • In 2013, there were over 10,000 APIs published by companies for open consumption.
  • Companies like Google, Instagram, and Square publish APIs so that your website can access their information in a secure way. This boosts traffic and business for them.
  • You can learn about many different companies and their APIs here.

Web APIs Overview

  • What is an API?
  • What APIs Can Access
  • REST APIs

What APIs Can Access

  • 1. Functionality: We use APIs to outsource part of our application’s functionality to someone else, so we can focus on the unique bits.
    • Example: Starbucks asks Google Maps for directions to your closest location.

2. Public Data: There is a huge amount of data available, and APIs make that data available to use in a structured way.

  • Example: You can search for books through Google Books.

3. User Data: We also use APIs to access data from other products and integrate them with our own. Users use multiple products and expect for them to work together - synergy.

  • Example: You can sign into many websites using your Facebook account, which then automatically import your name, email address, etc.

The Diagram

This is all dynamic content.

APIs are so useful!

We need to understand:

  • HOW to best use APIs
  • WHAT APIs are out there
  • WHY you should use them

Web APIs Overview

  • What is an API?
  • What APIs Can Access
  • REST APIs

REST APIs

REST APIs conform to a set of constraints.
Read this article.

Then let's watch the first 6 minutes of
this video!

HTTP Requests

  • APIs are accessed using HTTP, which is the language of the Internet.
  • You make an HTTP request using your browser every time you visit a URL. Your browser is doing some of the work behind the scenes, though; there is more to an HTTP request than a URL. Learn all of the parts of an HTTP request here.

How do APIs Work?

How do APIs work?

  • An API is used to bring in information from another server, and there's only so many ways that you can do that in the client.
  • The API itself isn’t really a box floating in space, so much as a chunk of code that acts as a gatekeeper.
  • That code helps translate the third party’s data into something you can read, and it makes sure that only authorized users can access the data (a process called “authentication”).

Working with data on the web

  • JSON
  • Using Fetch to make requests
  • Async/Await

Sending/Receiving Data Across the Internet

JSON = JavaScript Object Notation

  • JSON is all about transmitting data objects
  • This is a way to store and send data!
  • JSON can be read by all sorts of backend platforms and databases.

How does JSON work?

  • Using Key/Value pairs
  • Keys must be stored with quotes (unlike JS Objects)
  • Value can be the following data types: Number, String, Boolean, Array, Object, null
  • Resembles objects in JS

Example


{
"firstName": "Gene", 
"lastName": "Smith", 
"address": { 
"streetAddress": "425 2nd Street", 
"city": "San Francisco", 
"state": "CA", 
"postalCode": 94107 
}, 
"phoneNumbers": [ 
"212 732-1234", 
"646 123-4567" ] 
} 
        

JSON Identification

Your product manager provided you the following UI design. How would you create a JSON from this page?

JSON Exercise

How is data sent over the internet?

GET and POST Requests

Get and Post Requests

Let's make a GET request for some JSON

Your browser will automatically make a GET request, and this particular response will be JSON. This is very common for when you are making API calls to get data.

Click here for an example.

Let's add a JSON Formatter

The GET request on the prior slide yields JSON in raw form.

To make the JSON more readable, we will need to parse it.

Click here to add JSON Formatter,
an extension from the Chrome Web Store.

Then click between Raw and Parsed. Notice what happens!

When do we make GET and POST requests?

  • When we go to a website (GET)
  • When we login or sign up for a web app (POST)
  • When we search for items in an online store (GET)
  • When we submit a post to a social media site (POST)
  • When we submit a form (POST)

Web Apps

Web apps can be set up to make many, many GET and POST requests for almost any user action.

Frontend developers send those requests and receive the responses.

Frontend developers also determine WHEN a request is sent and how it is handled by the UI.

What does asynchronous mean?

Asynchronous technologies enable users to access information or communicate at different points of time, usually at the time of choice of the user.

Web Apps - The Old Way

A traditional data-driven web application is written so that it:

  1. Displays a webpage
  2. Waits for user interaction
  3. Asks the server for data
  4. Reloads the webpage

This process has a negative effect....

Sad Users

As a result, the user has "down time" - a period of time where the users can't interact with the webpage at all.

Importance of Async for Web 2.0 Programming

  • No down time!
  • The user can still interact with other parts of the page while one part is loading.
  • The user can selectively load the content they're interested in.
  • This is arguably the most important part of Web 2.0 programming!

Requests and Responses

Requests and Responses

  • Front-End: Hey, Back-End! Here are my credentials. Can I get some data? How about books on APIs?
  • Back-End thinks about it, decides how to handle request...looks in database, searches...
  • Back-End: 200 OK, here are some books on APIs!
  • Front-End: Thanks! I'm going to make an online bookshelf with the data!

How does this communication take place?

There are different methods for making async requests, and new ones are being added all the time.

We will talk about a tool that is built into JavaScript, called Fetch.

Fetch

  • Fetch allows for asynchronous data transfer between a webpage and a web server/API.
  • JavaScript tells the browser to retrieve or send data from a particular URL and send the response back to the webpage.

Let's talk about this diagram

Diagram of Client and Backend Communication

Server Status Responses

Server Status Codes

Fetch

The Fetch API allows JS to access and manipulate the HTTP pipeline, such as requests and responses, using fetch().

Let's take a look at "GET" and "POST"


//GET
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

//POST
let data = { name: "lhack"}
fetch('http://example.com/movies.json', {
  method: 'POST', 
  body: JSON.stringify(data) 
})
.then(response => response.json())
.then(data => console.log(data));
        

Fetch for GET and POST Requests


//GET
fetch('http://example.com/movies.json')

//POST
let data = { name: "lhack"}
fetch('http://example.com/movies.json', {
  method: 'POST', 
  body: JSON.stringify(data) 
})

Notice that both requests have a url string as a parameter.

The POST request has an additional parameter: an object.
The object in the POST request has 2 properties:

  • method, which must have a value of 'POST'
  • body, which must utilize the JSON.stringify() method.

Fetch first, then what?

When using fetch(), expect a response and data.
Let's look at "GET" and "POST" again.


//GET
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

//POST
let data = { name: "lhack"}
fetch('http://example.com/movies.json', {
  method: 'POST', 
  body: JSON.stringify(data) 
})
.then(response => response.json())
.then(data => console.log(data));
        

Notice we can use method chaining and apply .then() right after we use the fetch() method.

More Fetch Examples

Let's walk through this example

Exercise using an API

We will check out this example using the Cat Facts API
Click here

Let's display the data!


document.addEventListener("click", function() {

  let text = document.getElementById("paragraph-text")
  text.textContent = 'loading . . .'
  
  fetch('https://cat-fact.herokuapp.com/facts')
  .then(response => response.json())
  .then(data =>   
    for (let i = 0; i < data.length; i++) { 
      text.textContent += data[i].text
    }
  );
});
        

Another Fetch GET exercise

Hint: Take a look at the structure of the JSON data to complete the exercise.

Click here

How JS Works!

The Event Loop

Great Resources

Callbacks and Async - Oh My!

Web Fundamentals

Marvel API Key Exercise

Ask a user for a character name, then make an API call to fetch and then display the character's thumbnail, name, and description to the user.

Click here for the instructions and links to resources to help you sign up for an API key, use fetch().

More on Web APIs

Watch these Web API videos.

Web APIs Overview

  • What is an API?
  • What APIs Can Access
  • REST APIs

THE END

Thank you for your attention!