DEV Community

Cover image for 12 Essential Web APIs Every Developer Should Know
Vishal Yadav
Vishal Yadav

Posted on

12 Essential Web APIs Every Developer Should Know

Mastering various Web APIs can significantly enhance your web application's functionality and user experience. These APIs provide developers with tools to interact with browsers in ways that were previously impossible. Here, we’ll explore 12 essential Web APIs, explain their functionality, and provide code examples to help you implement them in your projects.


1. Storage API

The Web Storage API (including localStorage and sessionStorage) allows you to store key-value pairs in a web browser. It's useful for saving user preferences or persisting data between sessions.

Code Example:

// Save data to localStorage
localStorage.setItem('userName', 'Vishal');

// Retrieve data from localStorage
const user = localStorage.getItem('userName');

// Clear localStorage
localStorage.removeItem('userName');
Enter fullscreen mode Exit fullscreen mode

Learn More about Storage API


2. Payment Request API

The Payment Request API simplifies the process of accepting payments on the web by providing a consistent user experience across various payment methods.

Code Example:

if (window.PaymentRequest) {
  const payment = new PaymentRequest([{
    supportedMethods: 'basic-card'
  }], {
    total: { label: 'Total', amount: { currency: 'USD', value: '10.00' } }
  });

  payment.show().then(result => {
    // Process payment result
    console.log(result);
  }).catch(error => {
    console.error('Payment failed:', error);
  });
}
Enter fullscreen mode Exit fullscreen mode

Learn More about Payment Request API


3. DOM API

The DOM (Document Object Model) API allows you to manipulate the structure, style, and content of the document. This is one of the most widely used APIs in web development.

Code Example:

// Select and update an element
const element = document.querySelector('#myElement');
element.textContent = 'Hello, World!';
Enter fullscreen mode Exit fullscreen mode

Learn More about DOM API


4. HTML Sanitizer API

The HTML Sanitizer API helps clean up untrusted HTML content to avoid security risks like XSS (Cross-Site Scripting) attacks.

Code Example:

const dirtyHTML = '<img src="javascript:alert(1)">';
const cleanHTML = sanitizer.sanitize(dirtyHTML);
console.log(cleanHTML); // Safe HTML output
Enter fullscreen mode Exit fullscreen mode

Learn More about HTML Sanitizer API


5. Canvas API

The Canvas API allows you to draw graphics and animations on a web page using the <canvas> element, perfect for creating games, visualizations, or custom graphics.

Code Example:

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.fillStyle = 'blue';
context.fillRect(10, 10, 150, 100);
Enter fullscreen mode Exit fullscreen mode

Learn More about Canvas API


6. History API

The History API lets you interact with the browser’s session history, allowing you to manipulate the browser's history stack (e.g., pushState, replaceState).

Code Example:

history.pushState({ page: 1 }, 'title', '/page1');
history.replaceState({ page: 2 }, 'title', '/page2');
Enter fullscreen mode Exit fullscreen mode

Learn More about History API


7. Clipboard API

The Clipboard API allows you to read from and write to the clipboard, enabling features like copy-paste functionality.

Code Example:

navigator.clipboard.writeText('Hello, Clipboard!').then(() => {
  console.log('Text copied to clipboard');
}).catch(err => {
  console.error('Failed to copy text:', err);
});
Enter fullscreen mode Exit fullscreen mode

Learn More about Clipboard API


8. Fullscreen API

The Fullscreen API allows you to present a specific element or the entire webpage in fullscreen mode, useful for videos or immersive experiences like games.

Code Example:

document.getElementById('myElement').requestFullscreen().catch(err => {
  console.error(`Error attempting to enable full-screen mode: ${err.message}`);
});
Enter fullscreen mode Exit fullscreen mode

Learn More about Fullscreen API


9. FormData API

The FormData API simplifies the process of constructing key/value pairs representing form fields and their values for easier form data submission via XHR or Fetch.

Code Example:

const form = document.querySelector('form');
const formData = new FormData(form);
fetch('/submit', {
  method: 'POST',
  body: formData
}).then(response => {
  if (response.ok) {
    console.log('Form submitted successfully!');
  }
});
Enter fullscreen mode Exit fullscreen mode

Learn More about FormData API


10. Fetch API

The Fetch API provides a modern and flexible way to make asynchronous network requests, offering a simpler, promise-based alternative to XMLHttpRequest.

Code Example:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));
Enter fullscreen mode Exit fullscreen mode

Learn More about Fetch API


11. Drag and Drop API

The Drag and Drop API allows you to implement drag-and-drop functionality in your web applications, enhancing user interactions with intuitive UI elements.

Code Example:

const item = document.getElementById('item');
item.addEventListener('dragstart', (e) => {
  e.dataTransfer.setData('text/plain', item.id);
});
Enter fullscreen mode Exit fullscreen mode

Learn More about Drag and Drop API


12. Geolocation API

The Geolocation API provides access to geographical location information from the user’s device, enabling location-based services and features.

Code Example:

navigator.geolocation.getCurrentPosition((position) => {
  console.log(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`);
}, (error) => {
   console.error(`Error getting location: ${error.message}`);
});
Enter fullscreen mode Exit fullscreen mode

Learn More about Geolocation API


Conclusion

These Web APIs open up a world of possibilities for creating highly interactive, user-friendly web applications. From storage and payments to geolocation and graphics, mastering these APIs can take your web development skills to the next level.

By understanding how to effectively implement these APIs in your projects, you can significantly enhance both functionality and user experience.

References:

If you found this content helpful and would like to support, you can buy me a coffee 😊


This blog provides an updated overview of essential Web APIs every developer should know while incorporating clear explanations and practical code examples for each one.

Top comments (10)

Collapse
 
martinbaun profile image
Martin Baun

Fantastic work compiling this. APIs are about knowing the concepts behind them, so you know which objects/methods/concepts to look up the details of when you need them. Love that you put a lot of detail into this piece.

Collapse
 
vyan profile image
Vishal Yadav

Thanks

Collapse
 
richard_anballez_d14b38e8 profile image
Richard Anballez

Did a LLM write this article?
There's no Sanitizer API references on MDN and the link is broken.
Is sanitizer.sanitize() in the room with us?

Collapse
 
kvothethm profile image
kvothethm

Likely, a quick Google search shows that HTML Sanitizer API is a proposed API with the goals of achieving what is described here.

Collapse
 
mitch1009 profile image
Mitch Chimwemwe Chanza

Awesome post

Collapse
 
vyan profile image
Vishal Yadav

Nice

Collapse
 
raulpenate profile image
The Eagle 🦅

Wow, the drag and drop API looks to easy now, thanks!

Collapse
 
vishtar profile image
Vishtar • Edited
  1. HTML Sanitizer API

The link is broken.

Collapse
 
usman_awan profile image
USMAN AWAN

Excellent brother ... ♥️🖤

Collapse
 
vyan profile image
Vishal Yadav

Thanks