How to use fetch in JavaScript to load data from an API
fetch is the browser's built-in way to make HTTP requests from JavaScript. It's how a page loads data without refreshing.
The basic pattern:
- Call
fetch(url). It returns a promise. - Wait for the response with
await. - Check whether the request succeeded with
response.ok. - Read the body, usually with
await response.json().
Wrapped in an async function with a try/catch, that's enough for most simple cases.
Things beginners often miss:
- fetch doesn't throw on HTTP errors. A 404 or 500 still resolves successfully; you must check
response.okorresponse.statusyourself. It only rejects on network failures. - Reading JSON is also async. Forgetting
awaitbeforeresponse.json()gives you a promise, not data. - Sending data needs a
methodlikePOST, aContent-Type: application/jsonheader and a body created withJSON.stringify(). - CORS errors happen when the server doesn't allow requests from your site. That's a server setting, not something your fetch code can fix.
- Show loading and error states in your UI, not just the success case.
Keep secrets out of the browser. If an API needs a private key, call it from your own server, not directly from frontend code.
What was the first API you fetched data from? Do you use plain fetch or a helper library in your projects?
Comments · 4
Remember that fetch doesn't reject on HTTP errors like 404. You have to check response.ok yourself.
What's the difference between using .then() chains and async/await here? Is one better for beginners?
Both do the same thing. async/await reads top to bottom like normal code, which most beginners find easier, especially with error handling.
Add basic error handling from the start. Shipping a fetch call with no failure path is how blank screens end up in production.