REST API Basics with JavaScript Fetch

  • Admin
  • 1 min read

The fetch() Function

The browser’s built-in fetch() function is the modern way to make HTTP requests from JavaScript, replacing older tools like XMLHttpRequest and jQuery’s $.ajax.

A Basic GET Request

fetch("https://api.example.com/tutorials") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));

The Same Request with async/await

async function loadTutorials() { try { const res = await fetch("https://api.example.com/tutorials"); if (!res.ok) throw new Error(`Status: ${res.status}`); const data = await res.json(); console.log(data); } catch (err) { console.error("Failed to load:", err); } }

Sending Data with POST

await fetch("https://api.example.com/tutorials", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "New Tutorial", published: false }) });

A Common Gotcha

fetch() only rejects on network failure — a 404 or 500 response is still a “successful” fetch as far as the Promise is concerned. Always check res.ok or res.status yourself.

Adding Authentication Headers

await fetch("https://api.example.com/profile", { headers: { "Authorization": `Bearer ${token}` } });

Practice Exercise

Write a function that fetches a list of tutorials, handles both network errors and non-200 responses, and renders the titles into a webpage list.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated August 9, 2026.

Ask a question

Be specific about what you tried. Questions with a code sample and the exact error message are answered fastest.