💻 Programming

Web API

Web API

JavaScript interfaces provided by the browser. Provides features essential for web application development, such as the DOM, Fetch, Canvas, and Web Storage APIs.

📖 Detailed Explanation

Web API is a set of built-in interfaces that a web browser provides to JavaScript. It offers a variety of features needed for web application development, such as manipulating HTML documents, making network requests, rendering graphics, and accessing local storage. Separately from ECMAScript (the JavaScript language specification), the W3C and WHATWG are responsible for its standardization.

Representative Web APIs include the DOM API (Document Object Model manipulation), the Fetch API (HTTP requests), the Canvas API (2D/WebGL graphics), the Web Storage API (localStorage/sessionStorage), the Geolocation API (location information), the Web Audio API (audio processing), and the Intersection Observer API (detecting element visibility). As of 2025, more than 100 Web APIs have been standardized.

Distinguishing between Web API and REST API is important. A Web API is a client-side interface provided by the browser, while a REST API is a server-client communication convention based on the HTTP protocol. In interviews, asking about "Web API" usually means browser APIs, but depending on the context it may also mean "web service API (REST/GraphQL)", so you need to confirm.

Practical use: Saving user settings with localStorage, communicating with the backend via the Fetch API, implementing infinite scroll/lazy loading with Intersection Observer, push notifications with the Notification API, and copy/paste with the Clipboard API are used on a daily basis. Frameworks such as React and Vue also use Web APIs internally.

💻 Code Example

// Fetch API - HTTP 요청을 위한 모던 인터페이스
// XMLHttpRequest를 대체, Promise 기반

// 1. GET 요청 (데이터 조회)
async function fetchUsers() {
  try {
    const response = await fetch('https://api.example.com/users', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-token'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const users = await response.json();
    console.log(users);
    return users;
  } catch (error) {
    console.error('Fetch 실패:', error);
  }
}

// 2. POST 요청 (데이터 생성)
async function createUser(userData) {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
  });

  return response.json();
}

// 3. AbortController로 요청 취소 (타임아웃 구현)
async function fetchWithTimeout(url, timeout = 5000) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);

  try {
    const response = await fetch(url, {
      signal: controller.signal
    });
    clearTimeout(timeoutId);
    return response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('요청 시간 초과');
    }
    throw error;
  }
}
// Web Storage API - 브라우저에 데이터 저장
// localStorage: 영구 저장 (브라우저 종료해도 유지)
// sessionStorage: 세션 동안만 유지

// 1. 기본 사용법
localStorage.setItem('username', 'kaitrust');
const username = localStorage.getItem('username'); // 'kaitrust'
localStorage.removeItem('username');
localStorage.clear(); // 전체 삭제

// 2. 객체 저장 (JSON 변환 필수)
const userSettings = {
  theme: 'dark',
  language: 'ko',
  notifications: true
};

// 저장
localStorage.setItem('settings', JSON.stringify(userSettings));

// 불러오기
const savedSettings = JSON.parse(localStorage.getItem('settings'));
console.log(savedSettings.theme); // 'dark'

// 3. 실무 패턴: 유틸리티 함수
const storage = {
  set(key, value, expiresInDays = null) {
    const item = {
      value,
      timestamp: Date.now(),
      expires: expiresInDays
        ? Date.now() + (expiresInDays * 24 * 60 * 60 * 1000)
        : null
    };
    localStorage.setItem(key, JSON.stringify(item));
  },

  get(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) return null;

    const item = JSON.parse(itemStr);

    // 만료 확인
    if (item.expires && Date.now() > item.expires) {
      localStorage.removeItem(key);
      return null;
    }

    return item.value;
  }
};

// 사용 예: 7일 후 만료되는 토큰 저장
storage.set('authToken', 'abc123', 7);
const token = storage.get('authToken');
// Intersection Observer API - 요소 가시성 감지
// 무한 스크롤, 레이지 로딩, 애니메이션 트리거에 활용

// 1. 무한 스크롤 구현
const infiniteScrollObserver = new IntersectionObserver(
  (entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 마지막 요소가 보이면 다음 데이터 로드
        loadMoreData();
      }
    });
  },
  {
    root: null, // viewport 기준
    rootMargin: '100px', // 100px 전에 미리 로드
    threshold: 0 // 조금이라도 보이면 트리거
  }
);

// 마지막 아이템 관찰
const sentinel = document.querySelector('#load-more-trigger');
infiniteScrollObserver.observe(sentinel);

// 2. 이미지 레이지 로딩
const lazyImageObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // data-src -> src
      img.classList.add('loaded');
      lazyImageObserver.unobserve(img); // 로드 후 관찰 중지
    }
  });
});

// 모든 lazy 이미지에 적용
document.querySelectorAll('img[data-src]').forEach(img => {
  lazyImageObserver.observe(img);
});

// 3. 스크롤 애니메이션 (요소가 보일 때 페이드인)
const fadeInObserver = new IntersectionObserver(
  (entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
      }
    });
  },
  { threshold: 0.1 } // 10% 보이면 트리거
);

document.querySelectorAll('.fade-in-element').forEach(el => {
  fadeInObserver.observe(el);
});

🗣️ Say It Like This in Practice

💬 In a Meeting - Discussing How to Implement a Feature
"I think we should implement infinite scroll with the Intersection Observer API instead of the scroll event. Scroll events have performance issues, and the browser optimizes how Intersection Observer is handled. If we also apply lazy loading to images, we can reduce the initial loading time by more than 50%."
💬 In an Interview - Web API vs REST API Question
"Web API and REST API are different concepts. A Web API is a JavaScript interface provided by the browser, such as the DOM API or the Fetch API. A REST API is an HTTP-based server communication convention. In practice, we use both together, for example by using the Fetch API (a Web API) to communicate with a REST API server."
💬 In a code review
"If you store sensitive information in localStorage, it is vulnerable to XSS attacks. Store tokens in httpOnly cookies, and only put data in localStorage that is fine to expose, such as theme settings or a shopping cart. Also, wrap JSON.parse in a try-catch."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions & Common Mistakes

🌐
Browser compatibility check is required

Not every Web API is supported in every browser. Check on Can I Use (caniuse.com), and apply a polyfill if necessary. In particular, Safari/iOS is often slow to add support.

🔐
Permission request APIs require a user gesture

Permission requests for Geolocation, Notification, Clipboard API, and others can only be made within a user click/touch event. If requested automatically on page load, they will be blocked. First guide the user with the UI, then make the request when a button is clicked.

📦
Watch the polyfill bundle size

Importing all of core-js causes the bundle size to surge. Include only the necessary polyfills with the useBuiltIns: 'usage' option of @babel/preset-env. Alternatively, if you support only modern browsers, proceed without polyfills.

✅
The right approach

Use the feature detection pattern: if ('IntersectionObserver' in window) { ... }. Provide an alternative implementation (fallback) for browsers that do not support it. Be sure to check the browser compatibility table in the MDN documentation.

🔗 Related Terms

📚 Learn More