Working with JSON APIs
Most modern web APIs communicate using JSON — sending it in request bodies and returning it in responses — making the fetch API and JSON parsing a core combination in web development.
Fetching JSON Data
The fetch() function requests data from a URL, and its response provides a .json() method that parses the body as JSON automatically, returning a promise that resolves to the parsed data.
fetch("https://api.example.com/products")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error("Fetch failed:", error));
Sending JSON in a Request
When sending data to an API, the body must be stringified, and the Content-Type header should announce that it's JSON so the server parses it correctly.
fetch("https://api.example.com/products", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Notebook", price: 45.99 })
});
Common Mistakes
- Forgetting to call .json() on a fetch response, ending up with a raw Response object instead of usable data.
- Forgetting to stringify the request body with JSON.stringify() before sending it.
- Omitting the Content-Type: application/json header, which can cause the server to misinterpret the request body.
- Not handling network failures or non-OK HTTP responses, silently treating error responses as successful data.
Professional Tip
Check response.ok before calling .json() on a fetch response. A 404 or 500 response is still a "successful" fetch from JavaScript's perspective — you need to check the HTTP status explicitly to detect API errors.
Your Turn
Write a fetch request to a public JSON API (like a placeholder API) that retrieves a list of items and logs each item's name to the console.
Mini Quiz
What method on a fetch Response object parses its body as JSON?
.json() on a fetch Response reads the body stream and parses it as JSON, returning a promise that resolves to the parsed JavaScript value.