Fetching Data from APIs

Site Admin · 11 Sep 2026 · 8 views

Fetching Data from APIs

The fetch API is the modern way to make HTTP requests in JavaScript. It builds on promises, so it pairs perfectly with async/await. This post shows the essential patterns.

The fetch Function

fetch returns a promise that resolves to a Response object. The response body is not parsed automatically - you parse it with a method like json() or text().

const response = await fetch("https://api.example.com/posts");
const posts = await response.json();
console.log(posts);

GET Requests

async function getPosts() {
    const response = await fetch("https://api.example.com/posts");
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
}

// With headers
async function getUser() {
    const response = await fetch("/api/users/me", {
        headers: {
            "Authorization": `Bearer ${token}`,
            "Accept": "application/json"
        }
    });
    return response.json();
}

POST Requests

async function createPost(postData) {
    const response = await fetch("https://api.example.com/posts", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(postData)
    });

    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message);
    }

    return response.json();
}

await createPost({title: "My Post", content: "Hello!"});

HTTP Methods and Error Handling

// PUT updates; DELETE removes
await fetch("/api/posts/42", {
    method: "PUT",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify(updatedPost)
});

await fetch("/api/posts/42", {method: "DELETE"});

// Always handle errors
async function safeFetch(url, options = {}) {
    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            throw new Error(`${response.status}: ${response.statusText}`);
        }
        const data = await response.json();
        return {success: true, data};
    } catch (error) {
        return {success: false, error: error.message};
    }
}

Loading State Pattern

Every data fetch needs UI states. A minimal renderer pattern:

const container = document.querySelector("#posts");
container.innerHTML = "<p>Loading...</p>";

try {
    const posts = await getPosts();
    container.innerHTML = posts
        .map(p => `<article><h2>${p.title}</h2><p>${p.body}</p></article>`)
        .join("");
} catch (error) {
    container.innerHTML = `<p>Failed to load: ${error.message}</p>`;
}

Key Points

  • The fetch function returns a promise; parse the body with json().
  • Always check response.ok before using the data.
  • Use method: "POST" and body: JSON.stringify(...) to send data.
  • Set headers like Content-Type and Authorization as needed.
  • Show loading, success, and error states in your UI.
Share this post:

Comments (0)

Please login or register to comment.