Modern JS & AsyncCore· 45 min read

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.

Real live data from a public API
<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>
Live preview

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

  1. const res = await fetch(url) — request the data.
  2. const data = await res.json() — parse the JSON.
  3. Use data to 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?

Answer: await res.json() parses the response body into a JavaScript object/array you can use.

✍️ Practice

  1. Fetch a random joke (or any public API) and show it on the page.
  2. Fetch from https://jsonplaceholder.typicode.com/users and print the first user’s name.

🏠 Homework

  1. Fetch a list of posts from a public API and display their titles in a list.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →