Backend

REST API Basics with JavaScript Fetch

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.

Leave a Reply

Your email address will not be published. Required fields are marked *