Skip to content

JavaScript Tutorial The Fetch API

Making a GET Request with fetch()

Lesson 151 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

A GET request asks for data. It is the default for fetch, so you only need the URL.

script.js
JS
const response = await fetch("https://api.example.com/products");
const products = await response.json();

Query parameters

Filters, search terms and page numbers go in the URL after a ?. Build them with URLSearchParams so special characters are encoded correctly.

script.js
JS
const params = new URLSearchParams({ q: "blue shoes", page: 2, sort: "price" });

console.log(params.toString());  // → q=blue+shoes&page=2&sort=price

const url = "https://api.example.com/search?" + params;
console.log(url);                // → https://api.example.com/search?q=blue+shoes&page=2&sort=price

You can also use the URL object, see URL and URLSearchParams.

A complete example: a product list

index.html
HTML
<input id="filter" placeholder="Filter products">
<ul id="products"></ul>
<p id="status" role="status"></p>
<script>
  // A data: URL stands in for the server
  const api = "data:application/json," + encodeURIComponent(JSON.stringify([
    { id: 1, name: "Notebook", price: 4 },
    { id: 2, name: "Backpack", price: 35 },
    { id: 3, name: "Pen set", price: 6 }
  ]));

  const list = document.querySelector("#products");
  const status = document.querySelector("#status");
  let products = [];

  function render(items) {
    list.replaceChildren(...items.map(p => {
      const li = document.createElement("li");
      li.textContent = `${p.name} - $${p.price}`;
      return li;
    }));
    status.textContent = items.length + " products";
  }

  async function load() {
    status.textContent = "Loading…";
    const response = await fetch(api);
    products = await response.json();
    render(products);
  }

  document.querySelector("#filter").addEventListener("input", event => {
    const term = event.target.value.toLowerCase();
    render(products.filter(p => p.name.toLowerCase().includes(term)));
  });

  load();
</script>

Load once, keep the data in a variable, and filter it in the browser. For big data sets, filter on the server instead and send a new request.

Reading other response types

script.js
JS
const text = await response.text();      // plain text or HTML
const blob = await response.blob();      // images, files
const data = await response.json();      // JSON

You can only read the body once. Pick one.

Checking the status

A 404 or 500 is not an exception for fetch. Always check response.ok, as shown in HTTP Errors.

Caching

Browsers may cache GET responses. To control this, set headers on the server, or use the cache option (fetch(url, { cache: "no-store" })).

lightbulb
Same-origin vs cross-origin
Requesting your own site is simple. Requesting another site only works if that server allows it with CORS headers. See Request Headers and CORS.