Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Fetch Fundamentals

Your First fetch() Request

Make your first fetch() request: understand the promise and the Response, read JSON and text, compare .then with await, and practice with data URLs and a mock fetch.

fetch() is the built-in browser function for making HTTP requests from JavaScript. You give it a URL; it gives you back a promise that eventually resolves to a Response object. From that response you read the body as text, JSON, a blob or raw bytes. That is the whole idea, and everything else in this chapter (errors, POST, headers) builds on it.

If promises are new to you, a quick look at Promises and async/await first will make this lesson much easier. For the full API surface see the fetch reference.

The shape of a request

The simplest possible call has one argument, the URL, and defaults to a GET request.

JavaScript
const promise = fetch('https://api.example.com/users/1');
sequenceDiagram
  participant Code as Your code
  participant Browser
  participant Server
  Code->>Browser: fetch(url)
  Browser-->>Code: Promise (pending)
  Browser->>Server: GET /users/1
  Server-->>Browser: Status and headers
  Browser-->>Code: Promise resolves with Response
  Code->>Browser: response.json()
  Browser-->>Code: Promise resolves with parsed data

Two promises: the first resolves when headers arrive, the second when the body has been read and parsed.

Notice there are two waiting steps. The first promise resolves as soon as the server's status line and headers arrive. The body may still be downloading. Reading it with response.json() or response.text() returns a second promise.

A request you can run right now

The editor on this site runs in a sandbox, so we cannot call arbitrary servers. A data: URL is a way to embed a tiny "document" directly in the address, so fetch can load it without any network. It is perfect for practice, because the shape of everything else is identical to a real request.

JS fetch with a data: URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

encodeURIComponent makes the JSON safe to put inside a URL. The module="true" setting on the editor lets us use await at the top level. In your own pages, put await inside an async function, or inside a <script type="module">.

Reading the body: json() vs text()

The Response has several body readers. Each returns a promise, and each consumes the body (you can read it only once; see The Response Object).

Method Resolves to Use for
response.json() Parsed JavaScript value JSON APIs
response.text() A string HTML, CSV, plain text, or debugging
response.blob() A Blob Images, files
response.arrayBuffer() Raw bytes Binary data
response.formData() A FormData Form-encoded bodies
JS text() versus json()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A handy debugging trick: when json() fails and you do not know why, call text() instead and look at the raw string. You will often discover the server sent an HTML error page.

.then() chains versus async/await

Both styles do exactly the same thing. The older .then() style chains callbacks; async/await reads top to bottom like ordinary code.

JavaScript
// Promise chain
fetch(url)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

// async/await
async function load() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

The second form is easier to extend with loops, conditions and early returns, so this tutorial uses async/await from here on. Remember the rule that trips up beginners: await only works inside an async function or a module.

Practicing with a mock fetch

Data URLs are fine for a single fixed response, but real APIs have many endpoints. A mock fetch is a small function with the same signature as fetch that returns a Response built in memory. Your application code does not care which one it gets, so the same code works against the mock in the editor and the real thing in production.

JS A tiny mock fetch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Response.json() is a static helper that builds a response with a JSON body and the right Content-Type. We use this mock again in the lessons that follow whenever we need a fake server.

Passing fetchFn as a parameter is a simple form of dependency injection. In real code you would write showUsers(fetch). The mock version makes tests fast, offline and deterministic.

What the sandbox cannot do

Runnable examples on this site cannot reach real servers, so calls such as the following are shown read-only:

JavaScript
const response = await fetch('https://api.example.com/users/1');
const user = await response.json();

If you try them in your own page you will also meet the browser's same-origin policy: a page may only read responses from another origin if that server allows it with CORS headers (see Headers, Auth and CORS Basics). Opening your page from file:// also restricts what fetch may do, so use a small local server during development.

A resolved fetch promise does not mean the request succeeded. A 404 or 500 response still resolves normally. Only network-level failures reject the promise. We cover this properly in Handling Errors in fetch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does fetch(url) return?

    fetch returns a promise for a Response. You then call a body reader such as json() or text(), which returns another promise.
  2. 2. Why are there two awaits in const data = await (await fetch(url)).json()?

    fetch resolves when the headers arrive. Reading the body is a separate asynchronous step with its own promise.
  3. 3. What is a good way to see why response.json() fails?

    text() shows exactly what the server sent, which often reveals an HTML error page or an empty body instead of JSON.
  4. 4. Why pass the fetch function into your own function in these lessons?

    Any function with the same signature works, so the same application code can run against a mock in tests and the real fetch in production.

Summary

  • fetch(url) returns a promise for a Response; the default method is GET.
  • The first promise resolves when headers arrive; body readers like json() and text() return a second promise.
  • await needs an async function or a module; .then() chains do the same job.
  • text() is the best debugging tool when json() fails.
  • data: URLs and a small mock fetch let you practice offline, and injecting fetch keeps code testable.
  • A resolved promise does not mean success; HTTP errors still resolve.

Next: The Response Object.