Discover how to use JavaScript's fetch method to effortlessly retrieve and display data from APIs. Learn to integrate interactive buttons and dynamically update web content with JSON responses.
Key Insights
- Learned how the JavaScript
fetch
method sends HTTP GET requests to APIs, demonstrated by requesting random facts from the CatFact API and displaying them dynamically on a webpage. - Explored the concept of JSON (JavaScript Object Notation), including parsing JSON responses into usable JavaScript objects, specifically extracting the
fact
property for webpage output. - Introduced user interactivity by incorporating button-triggered API requests, enhancing user experience with dynamic, on-demand data retrieval.
Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.
This is a lesson preview only. For the full lesson, purchase the course here.
Hi, welcome back to Python AI apps. My name is Brian McLean. We're on to lesson seven.
In this lesson, we're going to introduce JavaScript and the `fetch` method for making server requests. So in the last lesson, we coded up that little chat assistant window, but only got so far as you can type a message and hit send, and all it does is appear in the window. The message does not get sent anywhere.
So ultimately, we're going to be sending our message to a Flask server for forwarding to the OpenAI API to get back the AI's answer, which comes back to JavaScript for output to the chat assistant window to actually have the chat showing up. You type AI answers right there in the window, but that's several lessons worth. So for this lesson, as a stepping stone, we're just going to focus—no Flask server, no OpenAI API.
We're going to focus on the JavaScript `fetch` method to make a request to a server, and the server we're going to request is not our own Flask server at all. We're going to make a request to an API—an application programming interface—some third-party website that supplies data. There are many kinds of APIs: cocktails, Bitcoin prices, weather data.
We're going to hit up the Cat Fact API. We're going to request a random Cat Fact, and actually there are a lot of whimsical APIs—Chuck Norris jokes and so on. We're going to use the `fetch` method to make a request for an API.
That's going to give us back JSON—which we're going to parse into a usable object. And then from that object, we're going to go get output. What is the `fact` property? The `fact` property of that object.
You'll see as we go, it'll all make sense, even if you don't know JavaScript. Now, if you don't know JavaScript, it's a little bit harder to follow, but there are a lot of notes on the JS in the book, and as it is not a JS course, we can't really spend too much time on the JavaScript, but I do have a lot of notes in here. We will use `fetch` to request that the Cat Fact API send us a random Cat Fact.
But first, let's go over a few key terms. API: application programming interface, which is an app involving a client requesting data from an endpoint URL on a server, and handling a response. JSON: JavaScript Object Notation—that is a string version of a JavaScript object.
If you're a Python person, you'd know that better as a Python dictionary. It gets stringified for transmission—or serialized, as they say—for transmission across a network. And then when the JSON lands at its destination, it has to get parsed or broken back into a usable object.
So the `fetch` method of JavaScript will be for sending the request to a server. It's like calling Domino's for pizza and saying, “Hey, send me a Cat Fact.” And it'll give us a JSON response.
It'll look basically like so: some random fact with two properties, `fact` and `length`. We don't care about the `length`, just the `fact`. We'll parse that JSON and then get the `object.fact` property, which will give us the value of the fact—the fact text—which we'll then output to a webpage.
So it's a three-method process: `fetch` to send the request, `then` to parse the incoming JSON response, and the second `then` will be to handle the JS object. And in our case, again, all we want to do is output the fact to the webpage.
So let's see how this works. Let's go visit the API. Just take this URL, go to the browser, paste it, and you get a random Cat Fact. And if you refresh, you get another one.
Two properties: `fact` and `length`. Now, what we're going to do instead—you don't want to go here. You just want to order the Cat Fact from here, right? It's like Domino's.
You don't want to go to Domino's. You want to call them and have them deliver to you. We just want to call this page and have it deliver.
This is called an endpoint, by the way, of the API. We want to call that endpoint—request of that endpoint—for a Cat Fact to be delivered to us like a pizza. We're going to go to—we just need a very simple page.
We're going to back up to lesson one. We're going to take index one, which is just an H1 and an H2, and File > Save As. Call it 7, index-07.
Change that to Cat Fact API. We're going to be using JS `fetch` Cat Fact API. And then here in the H1, we'll match the title.
We don't need two H2s. We'll just say Cat Fact here, right? The Cat Fact is going to appear there. So that's what we have.
We got a little bit of CSS to just make the H1 and H2 look better. We can just copy that real quick. Let's go up to the—we have a little CSS already.
Just paste that. That's not really necessary. It'll just make it look a little nicer.
We have to import a JS file. This is the syntax—a JS file into our HTML file. We saw this last lesson.
We're going to say <script src="./static/js/script-07.js"></script>
. In the JS folder, let's make a new file called script-07.js, right? We're importing it, but we haven't made it yet. So in your JS, brand new file: script-07.js.
Now into this file, what we're going to do is we're going to grab the H2, which is where we're going to output the fact, right? It says so, you know? Cat Fact here—that's the H2 we want to grab. It's the only one. We'll just say const h2 = document.querySelector("h2")
.
And we looked at this syntax in the previous lesson. So go to the document, find the first H2—there's only one anyway—and bring it into JavaScript as an object.
The next move we're going to do is called a `fetch` method, which is a global JavaScript method. You could say window.fetch
, in fact, because it's one of those functions that lives at the window level. If you don’t know any JavaScript, that might not make any sense—just disregard.
Anyway, `fetch` is a function or method that's going to be called, and it's going to take as its argument—the input—the URL, the destination that you're hitting up. We're going to say `fetch`. Well, that is not what we want to fetch.
We want to—let's just go get the URL. That’s what we want. `fetch` takes as its argument the URL that you’re fetching from.
Send a fetch request to the Cat Fact API. Pass in another required argument: the method by which the request will be sent. `GET` is a default specification for HTTP requests.
In fact, you can actually leave it out because it is the default argument. It'll use that if you don't say anything, but it's best practice to specify. We're going to say method: "GET"
.
`GET` is, again, a little bit outside the scope of what we're doing here. It refers to the method by which the data is being transmitted across the web, the internet, the network. Step two: for handling the API response JSON, we're going to call the `then` method, chained onto `fetch`.
It'll run after `fetch` is done. It'll take the incoming JSON data as its argument, assuming we get a valid response from the API. And it's going to be coming in as JSON.
We're going to then call the `.json()` method on that, which belongs to the response object. And that will return a usable JSON object. This is all going to be handled as a callback function—so-called.
So the `then` method takes a callback—a function passed to it—where the input of the function is the JSON coming back and the output of the function is the parsed JSON object. It's kind of like input → crunch, crunch, do stuff → output. That’s what the arrow function syntax is showing—the flow of input, process, output.
We're going to say `.then`, because we're chaining. We're going to say the response JSON object—that's what we're going to call the incoming response from the Cat Fact API. And we're going to parse it into a usable object.
Parse the incoming JSON result into a usable object. Then after that, we want to output that. We want to output the cat fact—the `fact` property.
Call the `then` method again, chained onto the first `then`. It takes the incoming JS object as its argument—its callback does. The callback being the function inside the function.
We're going to log the object to the console just so we see if it worked. We're going to say—I'm just going to copy all this. Log the parsed JS object to the console—you'll see what that is in a moment.
So that is going to be: the object is coming in and we're logging it out. console.log()
—that ought to do it. There's no button or anything.
It just runs, right? When you refresh the page. So let's go over to index-07 and we should get a cat fact straight away to show up without clicking or doing anything. Oh—we haven’t outputted it to the website.
Oh, we got the object though. I mean, that’s all we got. Yeah, that’s all we’re asking for so far.
Good. Oh, we got it. We didn’t output it yet.
Refresh the browser. The `fetch` method should be called automatically, resulting in the random cat fact object outputting to the console. That’s exactly what we have.
There’s your `fact`, and there it is, right? There’s your `fact` and your `length`. That’s your object. So what we need to do is also output it to the webpage.
We’re going to output the `fact` property—the actual cat fact—to the webpage, to the H2. So with two lines of code now to run—one for the log and one to the output—we need to open up the function with curly braces. We’re going to have to say curly braces.
And then there’s one line. And the next line is h2.textContent = responseObject.fact
, right? We don’t want the whole object. We just want the fact.
Output the cat fact text to the H2, right? Just the text. Now, when you refresh, you automatically get a cat fact. Every time you refresh the page, you get a cat fact.
There’s no user interactivity—no buttons to click. It’s just running on page load. Here’s an explanation of the JS.
I encourage you to go look through all that. Now what we’re going to do is up it a notch. We’re going to have the cat fact appear only when the user clicks a button, right? So not automatically—introduce some interactivity, right? Better user experience if the user gets to decide when that cat fact shows up.
So below the H1, we’re going to make a button. We’ll say <button>Fetch Cat Fact</button>
. You refresh the HTML page.
There’s a button. It’s still loading the cat fact automatically. It’d be nice to have the CSS though.
Let’s see. Let’s get the CSS for the button. You don’t have to do this.
This isn’t in the book, but I would like to see it. Here—you can come over here to the Greenleaf and grab the button. There you go.
Nicer button. That’s a button. All right.
So what we’re going to do—we have a button now. Now we’re going to go into the JavaScript, grab the button with querySelector("button")
, like we did in the last lesson with the chat assistant at Greenleaf website. And we’re going to tell the button when it’s clicked to call a function, which we will call `fetchCatFact`.
And we’ll just put all the `fetch` data—the `fetch`–`.then`–`.then` chain—into that function. We’ll say get button and have it call function. We’ll say const button = document.querySelector("button")
, button.addEventListener("click", fetchCatFact)
.
To call a function, `fetchCatFact` is what we shall call our function. And all this stuff—`fetch`–`.then`–`.then` code—becomes the code that runs when the function is called. So put all that triple-chained `fetch`–`.then`–`.then` code in the function.
On the function that runs on button click. Yep. There it is.
Step four: find the function that runs on button click. Refresh the browser and click the button. Now the cat fact will not appear automatically—it’ll appear at the click first. Here’s a little another mention about `then`—some description of what’s going on.
Refresh. We do not get a cat fact until we click the button. There it is. Get another one if you click it again.
And that concludes the lesson. So that’s it for lesson seven. There’s your HTML and JS.
Excuse me—HTML and JS—real short. Very cool. Does a really cool thing without much code at all.
CSS omitted here, but that’s all the HTML. All right. Good job, everybody.
Let’s keep it rolling. We’re gonna go right into lesson eight or whenever you can. That lesson will be waiting for you.
In the next lesson, we’re going to use the `fetch` method to request our own Flask route—that’s going to serve as our API.
We’re gonna send the message that the user typed in the chat box over at the Greenleaf site to Flask. All right, but that’s it for lesson seven. See you in lesson eight.