JSON in APIs
REST APIs send and receive JSON. Use fetch() with response.json() to consume APIs, and set Content-Type: application/json when sending data.
REST APIs send and receive JSON. Use fetch() with response.json() to consume APIs, and set Content-Type: application/json when sending data.
// GET request — read JSON response
const res = await fetch("https://api.example.com/users/1");
const user = await res.json(); // Parses JSON automatically
// POST request — send JSON body
const res2 = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Bob", email: "bob@example.com" }),
});
const created = await res2.json();
Always check response.ok before calling response.json() — a 404 or 500 still returns a response, just with an error body.
More in JavaScript