How to fetch data from an API
Fetch JSON data
Modern browsers and Node.js 18+ provide fetch. Reading the response body is asynchronous too.
async function loadPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await response.json();
console.log(post.title);
}
loadPost();
Check the HTTP status
fetch rejects for network failures, but HTTP 404 or 500 responses still fulfill. Check ok before parsing.
async function getJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
Send JSON
Set the content type and serialize the body. The exact URL, method, headers, and authentication depend on the API.
async function createPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "First post", userId: 1 })
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.json());
}
createPost();
Build resilient requests
- Use
try/catcharound awaited requests - Show loading, success, empty, and error states in interfaces
- Never place private API secrets in browser JavaScript
- Respect API limits and validate response data before trusting it