fetch requests JSON from an API endpoint, decodes the response body, and renders the profile data.

Program

The Fetch API is the standard browser interface for HTTP requests. Most client code fetches JSON, turns it into objects, and then renders state.

The UI updates only after the request and JSON parse both finish.Fetch LifecyclePromise states before the visible cardNetwork, parsing, and rendering are separate waits.clickrequestresponsejson()staterenderThe UI updates only after the request and JSON parse both finish.
Figure: Fetch resolves in separate request, parse, and render steps. Model source: books/javascript-client/04network_requests/fetch_json_render/diagrams/fetch_lifecycle.semantic.json.
fetch_json_render.html
<section id="profile">Loading...</section>
<script>
  const profileEl = document.querySelector("#profile");
  fetch("/api/profile.json")
    .then(response => response.json())
    .then(profile => {
      profileEl.textContent = profile.name + " - " + profile.role;
    });
</script>
fetch fetch starts an HTTP request and returns a Promise for the response.
response.json response.json reads and parses a JSON response body.