CSE 154

Week 6 Section: Using JSON with JavaScript and AJAX

Today's Agenda

Review AJAX with fetch and JSON

Practice using JSON as a data format to process with JS

Recall: JavaScript Objects and JSON

JSON is a way of saving or storing javascript objects (the technical term is "serializing" which is just a fancy word for turning an object into a savable string of characters)

Browser JSON methods:

Demo: You Choose the API

api-tester.zip (starter HTML/CSS/JS)

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!