CSE 154

Lecture 14: Public APIs

Agenda

Administrivia:

  • When submitting to gitgrade, you will now get e-mail turnin receipts. If you click the turn-in button and do not get one, you should let us know. It is your job to save this email as proof of turn-in.
  • CP3 due Thursday
  • HW3 out tomorrow

Review JSON/AJAX with JavaScript fetch

Practice using fetch with different public APIs!

JSON and AJAX so far

  • JSON introduced as object type to package/process structured data
  • AJAX introduced with fetch to fetch data from a server
  • Used the fetch(URL).then(...).then(...).catch(...) pipeline to handle requests
  • Practiced taking HTML/text data and converting it to JSON (Wednesday)

Check your understanding: Why (and when) is JSON preferred over HTML/text?

Learning Objectives

By the end of today, you should be able to:

  • Have a strategy for approaching documentation for different API's
  • Know what an API key is, and how to get one if needed
  • Make a fetch call to an API, and possibly different calls to the same API
  • Know how to see whether a response is succesfully returned using Network tab
  • Handle errors from API requests

Recall: Fetching data from a web service

To make a request to a web service (API), we need to know:

  1. Who to ask (the url)
  2. Do we have permission to ask (any API keys/tokens)
    • Not in recipe.php, but NASA/TMDB require them; add as additional query parameter
  3. What to ask (any query parameters)
    • Differ per API, some have specific order of parameter values, separated by /, others have explicit key/value pairs started with ? and combined with &
    • Example: Recipes API from last week's section might have
      recipe.php?recipe=cupcake&vegan=true
    • Example: Numbers API from last week's section: http://numbersapi.com/154/math)
  4. What format we get answers in (the response data format, preferrably txt or JSON)

Check your Understanding (Q1A)

Consider the following request we might make with fetch:

function makeRequest() {
  let requestString = "https://api.nasa.gov/planetary/apod?" +
                      "api_key=DEMO_KEY&date=2018-09-30";
  fetch(requestString, {mode : "cors"})
    .then(checkStatus)   // 1
    .then(JSON.parse)    // 2
    .then(processData)   // 3
    .catch(handleError); // 4
}

JS

  1. Who are we asking for data from (the base url)?
  2. What query parameters are we using? What are the values of the parameters?
  3. What is the purpose of each step (1 through 4)?

Review: Pre-Lecture Activity

Review 2 (or optionally all) of the following API docs:

For each you reviewed, you were asked to:

  1. Identify whether you need a key to use the API
  2. Identify the different types of responses (txt, JSON, HTML, etc.)
  3. Identify one question you can ask with data from the API.

Dicussion Questions

With your neighbor(s), take a few minutes to discuss:

  1. What API looked most interesting to you?
  2. Did you find anything confusing/frustrating about the API documentation?
  3. What is one question/use case you thought of given the API documentation/examples?

Pre-Lecture Survey Responses: Reddit API

  • What is the top trending post in r/funny?
  • Who is friends with a certain user?
  • What are the topics of the most frequently-asked questions?
  • What are the last 10 posts to Reddit?
  • "User info muahahaha"

Pre-Lecture Survey Responses: NASA API

  • Where was the picture of comet taken?
  • What is the latest NASA article?
  • Information about particular planets
  • Showcase of planet pictures on a website
  • Trivia game for displaying constellations and having users guess the name

Pre-Lecture Survey Responses: Datamuse Word API

  • What are the synonyms for a word ?
  • What is a word that rhymes with "Montana" and is often followed by the word "Phone"?
  • What word is close to what the user is typing and commonly follows the preceding word (for autocomplete/word suggestions in text boxes)?
  • What is the definition for all of the synonyms of a word ?

Pre-Lecture Survey Responses: Movie Database (TMDB) API

  • What were some of the reviews for "Bee Movie"
  • What movies do I like? (requires account on TMDB)
  • Who is the most popular person from movies in the year 2015?
  • What are the most popular TV shows this month?
  • What TV shows will air in the US on December 10th?

Note: Convenient In-browser JSON Formatter

We're about to dive into how to get started with a public API. The first thing you usually want to do is to find a url with query parameters you're interested in, and see if you can view it on your browser.

There is a great Chrome extension to format nested JSON returned by different API's!

Chrome Extension: JSON View

Demo: You Choose the API

Note: When reviewing at home, start with this api-tester.zip (starter HTML/CSS/JS) which has instructions to work through in api-tester.js for any API.

Use the information on one of the 4 slide columns (go down to navigate each API option) to fill in the JavaScript, and change the HTML/CSS to allow a user to choose different query parameters and display different types of results (e.g. a series of "cards" to add post data for a subreddit, or a multiple-choice game for NASA astronomy trivia).

You can use the steps outlined in the provided JS to start your CP3 as well, but your solutions should be substantially different than the starter files.

API 1: Reddit

  1. What kind of format is the response data? JSON
  2. Do you need an API key? Not always
    • Note: You need a key if you are wanting to access/update user-specific information on reddit (see documentation). To simply fetch JSON about subreddit posts though, you can just append /.json to the end of a subreddit url.
  3. What kind of query parameters can you pass?
    • limit=postcount (optional): limits the number of JSON objects returned in array of subreddit post data
    • q=query (optional): filters posts based on search query term

API 1: Reddit Example

https://www.reddit.com/r/subreddit/.json?limit=postcount

Template

https://www.reddit.com/r/subreddit/search/.json?limit=postcount&q=searchquery

Template

Examples:

API 1: Another Reddit Example

To get JSON response about best and trending posts on Reddit:

https://www.reddit.com/r/best/.json?limit=postcount
https://www.reddit.com/r/trending/.json?limit=postcount

Template

Examples:

More information about JSON data returned: Reddit Wiki

API 2: Datamuse API

  1. What kind of format is the response data? JSON
  2. Do you need an API key? No
  3. What is the base url? https://www.api.datamuse.com

API 2: Datamuse API

Examples:

API 3: NASA APOD (Astronomy Photo of the Day) API

  1. What kind of format is the response data? JSON
  2. Do you need an API key? Yes* *(but you can make 50 calls per day with "DEMO_KEY" as your api key parameter!
  3. What is the base url? https://api.nasa.gov/planetary/apod

API 3: NASA APOD (Astronomy Photo of the Day) API

Examples:

API 4: The Movie DB API

  1. What kind of format is the response data? JSON
  2. Do you need an API key? Yes
  3. What is the base url? https://api.themoviedb.org/3

API 4: The Movie DB API

Examples: (note: you need to add an api key parameter to get this data)

  • List the most popular movies right now:
https://api.themoviedb.org/3/discover/movie/?api_key=<yourkey>&sortby=popularity.desc

Template

  • A ton more examples using the /discover/movie/ endpoint here!
  • Return information about movies matching a search term:
https://api.themoviedb.org/3/search/movie/?api_key=<yourkey>&query=<searchterm>

Template

  • Play with different options here!