Skip to main content
Albero Academy

JSON, Storage & APIs

Serialize data with JSON, persist it in the browser with localStorage, and talk to REST APIs with fetch, headers and methods.

Chapter 15JavaScript16 min readBeginner friendly
  • #JavaScript
  • #JSON
  • #APIs

Apps constantly move data around — saving to storage, sending it to servers, receiving it back. The lingua franca is JSON. This chapter ties together JSON, browser storage and talking to REST APIs — the practical plumbing behind almost every web feature.

JSON

JSON (JavaScript Object Notation) is a text format for data. Convert between JS values and JSON text with two functions:

stringify & parse
const student = { name: "Aanya", tools: ["SQL", "Python"] };
const text = JSON.stringify(student); // object → string (to send/store)
// '{"name":"Aanya","tools":["SQL","Python"]}'
JSON.stringify(student, null, 2); // pretty-printed
const back = JSON.parse(text); // string → object (when receiving)

Browser storage

localStorage persists small key/value string data in the browser across sessions (sessionStorage clears on tab close). Since it only stores strings, pair it with JSON:

persisting data
// Save
localStorage.setItem("prefs", JSON.stringify({ theme: "dark" }));
// Load (with a fallback)
const prefs = JSON.parse(localStorage.getItem("prefs") || "{}");
localStorage.removeItem("prefs");
localStorage.clear();

REST APIs with fetch

the four verbs
// GET
const res = await fetch("/api/students");
const students = await res.json();
// POST — create
await fetch("/api/students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Rohan" }),
});
// PATCH updates, DELETE removes — same shape, different method
await fetch("/api/students/42", { method: "DELETE" });

Headers & auth

Headers carry metadata: the content type, and authentication. A common pattern is a bearer token:

authenticated requests
const res = await fetch("/api/me", {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
},
});
if (!res.ok) throw new Error(`HTTP ${res.status}`); // always check

Practice

Build a tiny preferences feature: read settings from localStorage (JSON), let the user change one, and save it back. Then write an async function that POSTs a new record to an API with the right headers and handles a non-OK response.

Key takeaways

  1. 01JSON.stringify serialises JS → text; JSON.parse deserialises text → JS (wrap parse in try/catch).
  2. 02localStorage persists string key/values across sessions; pair it with JSON.
  3. 03Never keep secrets/tokens in localStorage — it's readable by any script (XSS).
  4. 04fetch talks to REST APIs: GET/POST/PATCH/DELETE, JSON body, and always check response.ok.
  5. 05Headers carry Content-Type and auth (e.g. Authorization: Bearer <token>).