Async and fetch, continued
Topic Slides
Agenda Slides Open fullscreen β
Open slides ↗Post-Class Notes
TL;DR#
Today we read JSON from an API, waited for it with await, handled a request that fails, and sent data with POST to the message board. Then the room tested the course API, and a bug in its live board was found and fixed in class. The habit worth keeping: log what an API sends back before you render it, and find the field you need in the real response.
Before next class#
Checkpoint 5 is due Sunday 11/08.
- Mini Project 3 has new dates. Your repo URL is still due on Canvas Wednesday 11/04. The project is now due Sunday 11/08, deployed and working, and the showcase and Walkthrough 3 will be in class on Tuesday 11/10. Check your API in the Console as the spec describes before you build on it. If your API needs a key, we will build the function that holds it on Tuesday 11/03; the steps are also in Deploy on Vercel When Your API Needs a Key.
post-message.htmlandfetch-fun.htmlin youroim3690repo. Both are on Checkpoint 5. The steps are the two Your Turn slides at the end of JS Async + Fetch. Commit and push.logs/wk09.mdon GitHub by Sunday 11/01, with your three ideas for Mini Project 3.
On Tuesday 11/03 we will cover API keys and calling an LLM API. Browser APIs and extensions move to Thursday 11/05.
Reading JSON from an API#
An API endpoint sends back data, usually as JSON, where a web page would send HTML. Open the course API's Massachusetts towns and turn on pretty print: all 351 towns and cities, each with its county, population and the year it was founded, in a different order each time you reload.
- JSON arrives as text.
await response.json()turns it into a JavaScript object your code can read. - Read the structure before the field. In this response,
data.datais the array of towns anddata.data[0]is the first one. - Log it first.
console.log(data)before you render anything. An agent that has never seen an API guesses what its response looks like, so check its code against what the Console shows.
Waiting with await#
A request goes to someone else's server, and you cannot know how long it will take. await waits for it without freezing the page, and a function that uses await is marked async.
- Remove
asyncand the browser refuses to run the script:awaitis only allowed inside anasyncfunction. - Remove
awaitand you get response.json is not a function, becauseresponseis still a promise of a response.
When a request fails#
fetch throws an error only when no response arrives at all: you are offline, or the server cannot be reached. A 404 or a 500 is still a response, so check it yourself:
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();
// render data
} catch (error) {
// show a message on the page
}The message in catch is what the user sees when something goes wrong. Fetch Something Fun asks you to predict it, then check with Offline in the Network tab.
Sending data with POST#
GET reads data; POST sends it. The message board call sets method: "POST", a JSON body, and an X-Token header with your GitHub username.
- Replace the whole placeholder, angle brackets included.
"<your-github-username>"becomes your username with nothing around it. - Save the file before you reload. The browser runs the saved version.
The server sees every request: which tool sent it (a browser, curl, an agent's script) and roughly where it came from. APIs limit how many requests one address can send, and ask for a token so they know who is writing.
Treat what users send as text#
The course API's live board put each posted message into its HTML. The function that cleaned messages escaped < and > but not double quotes, so a message with a quote in it could break out of an HTML attribute and change the page. The fix builds each row from DOM elements and sets the message with textContent, which shows it as text whatever it contains.
The same applies to your projects. Anything a user types, and anything an API sends back, goes on the page through textContent. If your agent builds HTML strings from that data with innerHTML, ask it to switch.