fetch() Basics

What is an API?

A web API is a URL that returns data (usually JSON) instead of a web page. The fetch() function sends an HTTP request and returns a promise of the Response.

const response = await fetch("https://api.example.com/users/1");
const user = await response.json();   // parse the JSON body

Example

Example

This page loads a user from a free test API:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<button id="load">Load user</button>
<pre id="out">Click the button</pre>
<script>
  document.getElementById("load").addEventListener("click", async () => {
    const out = document.getElementById("out");
    out.textContent = "Loading...";
    const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const user = await res.json();
    out.textContent = user.name + "\n" + user.email + "\n" + user.address.city;
  });
</script>

</body>
</html>

Result