Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Standard Web APIs You Should Know

· 7 min read · Home Tech

In this article
  1. Background: What Are Web APIs?
  2. Core APIs for Everyday Development
  3. APIs for Rich Media and User Experience
  4. How to Choose the Right API
  5. Common Problems and Misconceptions
  6. Comparisons: Web APIs vs. Libraries
  7. Safety and Privacy Considerations
  8. Frequently Asked Questions

The standard web APIs you should know are the built-in browser interfaces that let JavaScript interact with the page, the browser, and the user's device. These include the DOM, Fetch, Storage, Geolocation, Canvas, and Web Audio APIs, among others. Understanding them lets you build richer, more responsive web applications without relying on third-party libraries.

Background: What Are Web APIs?

Web APIs are predefined sets of JavaScript objects, methods, and properties that browsers expose to developers. They form the backbone of modern web development, allowing you to manipulate HTML documents, handle user input, make network requests, and even access hardware like cameras or GPS. The term "standard" refers to APIs that are specified by organizations like the World Wide Web Consortium (W3C) or the WHATWG, and are implemented consistently across major browsers. This consistency is crucial because it means code written against these standards will work in Chrome, Firefox, Safari, and Edge with minimal differences.

Core APIs for Everyday Development

These are the APIs you will use in almost every project:

  • DOM (Document Object Model): The DOM represents the page structure as a tree of objects. You use methods like document.getElementById() or querySelector() to find elements, and properties like textContent or innerHTML to change them. It is the foundation of any interactive page.
  • Fetch API: This is the modern way to make HTTP requests. It returns a Promise that resolves to the response object. For example, fetch('/api/users').then(res => res.json()).then(data => console.log(data)) retrieves JSON data from a server. It replaces the older XMLHttpRequest (XHR) with a cleaner, promise-based syntax.
  • Storage API: localStorage and sessionStorage let you store key-value pairs in the browser. localStorage persists across browser sessions, while sessionStorage clears when the tab closes. They are useful for saving user preferences, form drafts, or small amounts of data that don't need a server.
  • JSON API: Though technically a language feature, the JSON.parse() and JSON.stringify() methods are essential for working with data. They convert between JavaScript objects and JSON strings, which is the standard format for API responses.

APIs for Rich Media and User Experience

These APIs add multimedia and interactive capabilities:

  • Canvas API: The <canvas> element provides a bitmap drawing surface. You can draw shapes, text, images, and animations using JavaScript. It is used for games, data visualizations, and image manipulation. For example, ctx.fillRect(10, 10, 50, 50) draws a rectangle.
  • Web Audio API: This API processes and synthesizes audio in the browser. You can create oscillators, apply filters, and visualize sound. It is more powerful than the simple <audio> element, enabling real-time effects and generative music.
  • Geolocation API: It allows your site to request the user's physical location. You get latitude and longitude, which you can use for maps or location-based services. The user must grant permission, and the API is HTTPS-only for security.
  • Drag and Drop API: This lets you make elements draggable and drop them into designated zones. It is useful for file uploads, sortable lists, or any interface that needs direct manipulation.

How to Choose the Right API

Choosing the right API depends on what you need to accomplish. Start by asking what the core task is:

  1. Manipulate the page? Use the DOM. It is the only way to change what the user sees.
  2. Send or receive data? Use Fetch. It handles all HTTP methods and supports promises.
  3. Store data locally? Use localStorage or sessionStorage. For larger structured data, consider IndexedDB (a more complex but powerful API).
  4. Draw or animate? Use Canvas for pixel-level control, or the CSS Animations API for simpler transitions.
  5. Play or generate sound? Use Web Audio API for complex effects, or the <audio> element for simple playback.

If you are unsure, check browser support on sites like Can I Use. Most standard APIs are well-supported, but some newer ones like the Web Share API or the File System Access API may have limited support.

Common Problems and Misconceptions

One common misconception is that the DOM is slow. In reality, it is fast for most operations, but frequent reflows and repaints can cause jank. The fix is to batch DOM changes and use requestAnimationFrame for animations. Another issue is that localStorage is synchronous and blocks the main thread, so it should not be used for large amounts of data. For that, use IndexedDB, which is asynchronous. A frequent Fetch mistake is forgetting to check res.ok before parsing JSON. A failed request (404 or 500) will still resolve the promise, so you must handle it explicitly. Also, remember that the Geolocation API only works over HTTPS, and it will prompt the user for permission, which they can deny.

Comparisons: Web APIs vs. Libraries

Many developers reach for libraries like jQuery or Axios before considering native APIs. However, modern standard APIs have largely replaced the need for these. jQuery was created to smooth over browser inconsistencies, but today's browsers are much more uniform. The Fetch API is a direct replacement for Axios in most cases, though Axios adds features like automatic JSON transformation and request cancellation. Similarly, the DOM API is now powerful enough that you rarely need a virtual DOM library unless you are building a large, state-heavy application like React or Vue. The main advantage of libraries is convenience and cross-browser consistency for older browsers, but for modern projects, standard APIs are often faster and reduce bundle size.

Safety and Privacy Considerations

Several web APIs have security implications. The Geolocation API requires explicit user consent, and you should never store location data without informing the user. The Storage API is sandboxed to the origin, meaning one site cannot read another's data, but be careful not to store sensitive information like passwords or tokens in localStorage, as it is accessible to any script running on the page. The Fetch API is subject to the same-origin policy, which prevents a site from reading responses from a different origin unless the server allows it via CORS headers. When using the Canvas API, be aware that reading pixel data from a canvas that has been drawn with cross-origin images can "taint" the canvas, preventing you from calling toDataURL() for security reasons. Always use HTTPS for any API that involves user data.

Frequently Asked Questions

What is the difference between localStorage and sessionStorage?

Both store data as key-value pairs in the browser. The main difference is lifetime: localStorage persists until you explicitly clear it, even after the browser is closed. sessionStorage is cleared when the tab or window is closed. They share the same API, so you can use setItem(), getItem(), and removeItem() on both.

Is the Fetch API better than XMLHttpRequest?

Yes, for most uses. Fetch is promise-based, which makes it easier to chain and handle errors with async/await. It is also more flexible with the Request and Response objects. However, XHR has some features that Fetch still lacks, like progress tracking for uploads. For basic requests, Fetch is the recommended choice.

Do I need to worry about browser compatibility for web APIs?

Yes, but less than in the past. Most core APIs like DOM, Fetch, and Storage are supported in all current browsers. Newer APIs like the Web Share API or the Clipboard API may have partial support. You can check compatibility on MDN or Can I Use, and use feature detection like if ('geolocation' in navigator) to provide fallbacks.

How do I make a GET request with the Fetch API?

Simply call fetch('url'). By default, it makes a GET request. To handle the response, you can do: fetch('url').then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error)). Remember to check response.ok to ensure the request was successful.

Can I use the Canvas API to create animations?

Yes, you can. The typical pattern is to use requestAnimationFrame to call a drawing function repeatedly. Each frame you clear the canvas and redraw the scene. This gives you smooth, 60fps animations. For simpler animations, CSS transitions or the Web Animations API might be easier, but Canvas gives you full control.

What is CORS and why does it matter?

CORS (Cross-Origin Resource Sharing) is a security mechanism that controls whether a web page can request resources from a different origin. By default, browsers block cross-origin requests. The server must include specific HTTP headers like Access-Control-Allow-Origin to permit them. If you are building an API, you must configure CORS to allow your frontend to access it.