Web APIs and Local Storage Documentation
Categories: CSSEComprehensive guide to Web APIs and Local Storage implementation in JavaScript
Web APIs and Local Storage Documentation
Comprehensive guide to Web APIs and Local Storage implementation in JavaScript
Author: Zhengji Li
Contents
Web APIs Overview
Web APIs (Application Programming Interfaces) serve as bridges between different software components. In web development, they come in two main forms:
- Browser APIs
- Built into web browsers
- Extend browser functionality
- Examples: Geolocation, Local Storage, Fetch API
- Server APIs
- Run on web servers
- Provide data and services
- Examples: REST APIs, GraphQL APIs
Crypto API Example
const myArray = new Uint32Array(10);
crypto.getRandomValues(myArray);
console.log(myArray);
This API generates cryptographically secure random values for security implementations, random key generation, and secure token creation
Geolocation API
The Geolocation API provides the user’s current location after getting their permission.
Getting User Location
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation not supported");
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
}
This code demonstrates how to request and display a user's geographic coordinates
Try it yourself:
Fetch API
The Fetch API provides a modern interface for making HTTP requests.
Making HTTP Requests
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
This example shows how to fetch data from an API endpoint using async/await
Try it yourself:
Local Storage
Local Storage is a web storage API that allows websites to store key-value pairs persistently in a user’s browser.
Key Features
- Persistence
- Data remains after browser closes
- Survives page refreshes
- Browser-specific storage
- Storage Limit
- Typically 5-10 MB
- Varies by browser
- Per-origin storage
- Data Format
- Stores strings only
- Requires JSON conversion for objects
- Key-value pairs
Basic Storage Operations
// Storing data
localStorage.setItem('username', 'pika43');
// Complex data
const user = { name: "pika43", age: 15 };
localStorage.setItem('user', JSON.stringify(user));
// Retrieving data
const username = localStorage.getItem('username');
const storedUser = JSON.parse(localStorage.getItem('user'));
// Removing data
localStorage.removeItem('username');
localStorage.clear();
Examples of storing, retrieving, and removing data from Local Storage
Practical Applications
Here are some real-world applications of Web APIs and Local Storage.
Theme Preference
// Save user theme preference
function saveThemePreference(isDark) {
localStorage.setItem('darkMode', isDark);
}
// Load theme preference
function loadThemePreference() {
return localStorage.getItem('darkMode') === 'true';
}
Implementation of dark mode preference using Local Storage
Form Data Persistence
// Save form data
function saveFormData(formData) {
localStorage.setItem('formData', JSON.stringify(formData));
}
// Restore form data
function restoreFormData() {
const saved = localStorage.getItem('formData');
return saved ? JSON.parse(saved) : null;
}
Saving and restoring form data using Local Storage
Practice Questions
Web APIs Understanding
What is the difference between Browser APIs and Server APIs? Provide examples of each.
Local Storage Implementation
How would you implement a shopping cart that persists across page refreshes using Local Storage?
API Integration
Write a function that fetches data from an API and caches it in Local Storage for future use.
Web APIs and Local Storage Documentation
This documentation provides a comprehensive overview of Web APIs and Local Storage, based on our notebooks. It covers key concepts, implementation details, and practical examples.
Web APIs Overview
What is a Web API?
Web APIs (Application Programming Interfaces) serve as bridges between different software components. In web development, they come in two main forms:
- Browser APIs
- Built into web browsers
- Extend browser functionality
- Examples: Geolocation, Local Storage, Fetch API
- Server APIs
- Run on web servers
- Provide data and services
- Examples: REST APIs, GraphQL APIs
Key Browser APIs
1. Crypto API
const myArray = new Uint32Array(10);
crypto.getRandomValues(myArray);
console.log(myArray);
This API generates cryptographically secure random values, useful for:
- Security implementations
- Random key generation
- Secure token creation
2. Geolocation API
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation not supported");
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
}
Features:
- Gets user’s current location
- Requires user permission
- Returns coordinates object
3. Fetch API
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
Key aspects:
- Makes HTTP requests
- Returns Promises
- Supports async/await
- Handles various data formats
Local Storage
Understanding Local Storage
Local Storage is a web storage API that allows websites to store key-value pairs persistently in a user’s browser.
Key Features
- Persistence
- Data remains after browser closes
- Survives page refreshes
- Browser-specific storage
- Storage Limit
- Typically 5-10 MB
- Varies by browser
- Per-origin storage
- Data Format
- Stores strings only
- Requires JSON conversion for objects
- Key-value pairs
Basic Operations
1. Storing Data
// Simple data
localStorage.setItem('username', 'pika43');
// Complex data
const user = { name: "pika43", age: 15 };
localStorage.setItem('user', JSON.stringify(user));
2. Retrieving Data
// Simple data
const username = localStorage.getItem('username');
// Complex data
const storedUser = JSON.parse(localStorage.getItem('user'));
3. Removing Data
// Remove specific item
localStorage.removeItem('username');
// Clear all data
localStorage.clear();
Best Practices
- Data Handling
- Always use try-catch when parsing JSON
- Check for storage availability
- Handle storage quota exceeded errors
- Security Considerations
- Don’t store sensitive information
- Validate stored data before use
- Clear sensitive data when needed
- Performance
- Minimize storage operations
- Batch updates when possible
- Use appropriate data structures
Practical Applications
1. User Preferences
// Save user theme preference
function saveThemePreference(isDark) {
localStorage.setItem('darkMode', isDark);
}
// Load theme preference
function loadThemePreference() {
return localStorage.getItem('darkMode') === 'true';
}
2. Form Data Persistence
// Save form data
function saveFormData(formData) {
localStorage.setItem('formData', JSON.stringify(formData));
}
// Restore form data
function restoreFormData() {
const saved = localStorage.getItem('formData');
return saved ? JSON.parse(saved) : null;
}
3. API Data Caching
async function getCachedData(url) {
const cached = localStorage.getItem(url);
if (cached) {
return JSON.parse(cached);
}
const response = await fetch(url);
const data = await response.json();
localStorage.setItem(url, JSON.stringify(data));
return data;
}
Common Challenges and Solutions
- Storage Limits
- Implement data cleanup strategies
- Use compression when needed
- Monitor storage usage
- Data Type Limitations
- Convert objects to JSON
- Handle complex data structures
- Validate data integrity
- Browser Compatibility
- Check for feature support
- Implement fallbacks
- Test across browsers
Conclusion
Web APIs and Local Storage are fundamental tools in modern web development. They enable:
- Rich browser interactions
- Persistent data storage
- Enhanced user experiences
- Efficient data handling
Understanding these technologies is crucial for building robust web applications that can work offline, maintain state, and provide seamless user experiences.