DrSchool Learn coding, fast.
EN AR BN CS DE EL Search

JS: Fetch API

Learn Fetch API in JS with practical examples.

Read time: 1 min Words: 40
Open Playground → HTML My Progress

JS — Fetch API

Overview

Fetch lets you request data from APIs (JSON/text) using Promises.

What you'll learn

  • Basic fetch
  • Parsing JSON
  • Error handling
  • async/await

Syntax

const res = await fetch(url);

Example

async function load(){
  try{
    const res = await fetch("https://api.github.com/zen");
    if(!res.ok) throw new Error("HTTP " + res.status);
    const text = await res.text();
    console.log(text);
  }catch(err){
    console.error(err);
  }
}
load();

Notes

  • Always check res.ok.
  • Use try/catch with async/await.

    Try: Open the Playground: /en/playground/html