Calling Web APIs with fetch

Get live data from the internet. Learn what a web API is, load data with fetch, find out when a request has failed, show loading, empty and error states, and send data back to a server.

Updated

Web APIs

  1. What a Web API Is (Apprentice): A web API is a server that answers requests sent to its addresses, and every request and answer has the same parts: a URL with a path and query string, a method, a status code and, usually, JSON.

fetch in JavaScript

  1. Getting Data with fetch (Apprentice): fetch sends a request to a web API and gives back a promise of the response; await it, then await response.json() to turn the JSON answer into a JavaScript value your page can use.
  2. When fetch Fails (Journeyman): fetch rejects only when no answer arrives at all, so check response.ok for answers like 404 and 500, catch network errors and timeouts (AbortSignal.timeout) with try/catch, and turn each one into a message a person understands.
  3. Loading, Empty and Error States (Journeyman): A page that loads data has four states, loading, success, empty and error, and it should say which one it's in, so people never stare at a blank screen or a page that quietly broke.
  4. Sending Data with fetch (Journeyman): To send data to an API, give fetch a second argument with method POST, a Content-Type header that says the body is JSON, and a body made with JSON.stringify; and know that CORS, the API's rule about which sites may call it, decides whether a page can call it at all.

Exercise: Dog Breed Explorer

  1. Exercise: Dog Breed Explorer (Journeyman): Finish an animal shelter's dog breed explorer, writing the functions that read the Dog CEO API's breed list, build a photo's address and load a photo with friendly errors, with offline tests for the functions and a checklist for the page's loading, empty and error states.

Up Next: Working Like a Professional

  1. Up Next: Working Like a Professional (Journeyman): See what your code can wait for after Module 5, meet the Trivia Night project where you'll build a timed game with live questions, and get a first look at Module 6, starting with a test that catches a bug before a player does.