Fetching Data from an API
Pull live data from the internet into your page — the exact skill that connects your React front-end to your Node back-end.
What you will learn
- Use fetch() to call an API
- Handle the JSON response with async/await
- Display live data on the page
fetch() gets data from a URL
The fetch() function requests data from a web address (an API). It returns a Promise, so we await it, then await turning the response into JSON.
<p id="joke">Loading a joke...</p>
<script>
async function getJoke() {
const response = await fetch("https://official-joke-api.appspot.com/random_joke");
const data = await response.json(); // parse JSON
document.getElementById("joke").textContent = data.setup + " ... " + data.punchline;
}
getJoke();
</script>await fetch(url) sends a request to that web address and waits for the server’s reply (the response). await response.json() then turns the reply’s JSON body into a real JavaScript object, data. The joke API gives back an object with setup and punchline fields, which we join and show on the page.
Note: Output: At first: Loading a joke... After the request: Why did the scarecrow win an award? ... Because he was outstanding in his field! (The joke changes each time — it is live data fetched from the internet.)
The standard pattern
const res = await fetch(url)— request the data.const data = await res.json()— parse the JSON.- Use
datato update the page.
Tip: This is the heart of full-stack development. In MERN, your React app will fetch from your own Node/Express API, which returns JSON from MongoDB. You are learning the exact connection now.
Note: Wrap fetch calls in try/catch to handle network errors gracefully — you will cover that in the Errors lesson.
Q. After const res = await fetch(url), how do you get the JSON data?
✍️ Practice
- Fetch a random joke (or any public API) and show it on the page.
- Fetch from
https://jsonplaceholder.typicode.com/usersand print the first user’s name.
🏠 Homework
- Fetch a list of posts from a public API and display their titles in a list.