1.About this Standard
This document defines the WebAPI Standard. It is a Living Standard that provides interfaces and methods for web applications to interact with network resources.
The WebAPI Standard defines a set of interfaces and methods that enable web applications to:
- Make network requests
- Handle responses
- Process data streams
- Cache resources
- Work offline
This standard aims to provide a consistent API across browsers and platforms, making web development more predictable and reliable.
https://ngiotsas.github.io/webapihtml/?page=about
1.1History
The WebAPI Standard evolved from various XMLHttpRequest and related specifications. It represents a modern approach to network communication for web applications.
Key milestones in the development of this standard:
- 2025
- Current Living Standard with enhanced security features
https://ngiotsas.github.io/webapihtml/?page=history
1.2Target Audience
This standard is primarily intended for:
- Web browser implementers
- Web application developers
- Web framework authors
- Web API documentation writers
Some sections are more relevant to specific audiences, as indicated in the section introductions.
https://ngiotsas.github.io/webapihtml/?page=audience
2.Fetch API
The Fetch API provides an interface for fetching resources across the network. It is a more powerful and flexible replacement for XMLHttpRequest.
The fetch() method is the primary entry point to the Fetch API. It returns a Promise that resolves to the Response object representing the response to the request.
Syntax
fetch(resource [, options])
.then(response => {
// Handle response
})
.catch(error => {
// Handle error
});
Parameters
- resource
- The resource that you wish to fetch. This can be a URL string or a Request object.
- options (optional)
- An object containing any custom settings you want to apply to the request. The possible options are:
method
: The request method, e.g.,GET
,POST
.headers
: Headers to send with the request.body
: The request body.mode
: The mode of the request, e.g.,cors
,no-cors
,same-origin
.credentials
: Controls whether credentials are sent with the request.cache
: Controls how the request interacts with the browser's cache.redirect
: Controls how redirects are handled.referrer
: Specifies the referrer of the request.referrerPolicy
: Specifies the referrer policy of the request.integrity
: Contains the subresource integrity value of the request.keepalive
: Allows the request to outlive the page.signal
: An AbortSignal object instance; allows you to abort the fetch request.
Example: Basic Fetch Request
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
Console output (assuming successful response with JSON data):
{ "id": 1, "name": "Example Data", "status": "active" }
https://ngiotsas.github.io/webapihtml/?page=fetch-api
2.1Promises
The Fetch API is built on Promises, which provide a way to handle asynchronous operations.
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Promises have three states:
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Promises provide methods to handle these states:
then()
: Handles fulfillment.catch()
: Handles rejection.finally()
: Executes code regardless of the Promise's state.
https://ngiotsas.github.io/webapihtml/?page=promises
2.2Async/Await
The async/await syntax provides a more elegant way to work with Promises.
The async keyword declares an asynchronous function that returns a Promise.
The await keyword pauses the execution of an async function until a Promise is settled.
Example: Fetch with Async/Await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
throw error;
}
}
Error handling with async/await is done using try/catch blocks, which provides a more synchronous-like code structure for handling errors.
https://ngiotsas.github.io/webapihtml/?page=async-await
3.Request Interface
The Request interface represents a resource request.
A Request object represents a request for a resource. It can be created explicitly using the Request constructor or implicitly by the fetch() method.
Constructor
new Request(input [, options])
Properties
method
: The request method (GET, POST, etc.).url
: The URL of the request.headers
: The headers of the request.destination
: The type of content being requested.referrer
: The referrer of the request.referrerPolicy
: The referrer policy of the request.mode
: The mode of the request (cors, no-cors, same-origin, navigate).credentials
: The credentials mode of the request (omit, same-origin, include).cache
: The cache mode of the request.redirect
: The redirect mode of the request.integrity
: The integrity metadata of the request.keepalive
: Indicates whether the request can outlive the page.signal
: An AbortSignal object instance.bodyUsed
: Indicates whether the body has been used.
Methods
clone()
: Creates a copy of the request object.arrayBuffer()
: Returns a promise that resolves with an ArrayBuffer representation of the request body.blob()
: Returns a promise that resolves with a Blob representation of the request body.formData()
: Returns a promise that resolves with a FormData representation of the request body.json()
: Returns a promise that resolves with a JSON representation of the request body.text()
: Returns a promise that resolves with a text representation of the request body.
https://ngiotsas.github.io/webapihtml/?page=request-interface
4.Response Interface
The Response interface represents the response to a request.
A Response object represents the response to a request, including headers, status, and the response body.
Constructor
new Response(body [, options])
Properties
headers
: The headers of the response.ok
: Indicates whether the response was successful (status in 200-299 range).redirected
: Indicates whether the response is the result of a redirect.status
: The status code of the response.statusText
: The status message corresponding to the status code.type
: The type of the response (basic, cors, error, opaque, opaqueredirect).url
: The URL of the response.bodyUsed
: Indicates whether the body has been used.
Methods
clone()
: Creates a copy of the response object.arrayBuffer()
: Returns a promise that resolves with an ArrayBuffer representation of the response body.blob()
: Returns a promise that resolves with a Blob representation of the response body.formData()
: Returns a promise that resolves with a FormData representation of the response body.json()
: Returns a promise that resolves with a JSON representation of the response body.text()
: Returns a promise that resolves with a text representation of the response body.
Example: Creating a Response
// Create a JSON response
const jsonResponse = new Response(JSON.stringify({
message: 'Success',
data: { id: 1, name: 'Example' }
}), {
headers: {
'Content-Type': 'application/json'
},
status: 200,
statusText: 'OK'
});
https://ngiotsas.github.io/webapihtml/?page=response-interface
5.Headers
The Headers interface represents HTTP headers, allowing you to perform various actions on HTTP request and response headers.
The Headers interface represents a collection of HTTP headers. It provides methods to get, set, add, and delete headers.
Constructor
new Headers([init])
Methods
append(name, value)
: Appends a new value to an existing header, or adds the header if it doesn't exist.delete(name)
: Deletes a header from the Headers object.get(name)
: Returns the first value of a given header name.has(name)
: Returns a boolean indicating whether the Headers object contains the specified header.set(name, value)
: Sets a new value for an existing header, or adds the header if it doesn't exist.entries()
: Returns an iterator for all name/value pairs in the Headers object.keys()
: Returns an iterator for all header names.values()
: Returns an iterator for all header values.
Example: Working with Headers
// Create headers object
const headers = new Headers();
// Add headers
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer token123');
// Check if header exists
if (headers.has('Content-Type')) {
console.log('Content-Type:', headers.get('Content-Type'));
}
// Use headers in fetch
fetch('/api/data', {
method: 'POST',
headers: headers,
body: JSON.stringify({ key: 'value' })
});
https://ngiotsas.github.io/webapihtml/?page=headers
6.Streams API
The Streams API allows JavaScript to programmatically access streams of data received over the network and process them chunk by chunk.
The Streams API provides a standard way to break down a resource into small chunks and process them bit by bit, without needing to load the entire resource into memory.
Types of Streams
- ReadableStream: Represents a readable stream of data.
- WritableStream: Represents a writable stream of data.
- TransformStream: Represents a transform stream that can modify data as it passes through.
ReadableStream Methods
getReader()
: Returns a ReadableStreamDefaultReader.cancel(reason)
: Cancels the stream.pipeTo(destination)
: Pipes the stream to a WritableStream.pipeThrough(transform)
: Pipes the stream through a TransformStream.tee()
: Splits the stream into two branches.
Example: Processing a Stream
fetch('/large-file.json')
.then(response => {
const reader = response.body.getReader();
function readChunk() {
return reader.read().then(({ done, value }) => {
if (done) {
console.log('Stream complete');
return;
}
// Process chunk
console.log('Received chunk:', value.length, 'bytes');
// Continue reading
return readChunk();
});
}
return readChunk();
});
https://ngiotsas.github.io/webapihtml/?page=streams
7.Service Workers
Service Workers act as a proxy between web applications, the browser, and the network, enabling features like offline support, background sync, and push notifications.
A Service Worker is a script that your browser runs in the background, separate from a web page, enabling features that don't need a web page or user interaction.
Lifecycle
- Registration: The service worker is registered using the navigator.serviceWorker.register() method.
- Installation: The service worker is installed and the install event is triggered.
- Activation: The service worker is activated and the activate event is triggered.
- Idle: The service worker is idle until it receives events.
- Termination: The service worker is terminated when not in use to save memory.
Events
install
: Triggered when the service worker is installed.activate
: Triggered when the service worker is activated.fetch
: Triggered when a request is made from the web page.message
: Triggered when a message is sent to the service worker.push
: Triggered when a push notification is received.sync
: Triggered when a background sync is requested.
Example: Registering a Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
}
https://ngiotsas.github.io/webapihtml/?page=service-workers
8.Cache API
The Cache API provides a mechanism for storing and retrieving network requests and responses, allowing for offline access to cached content.
The Cache API provides a storage mechanism for Request/Response object pairs that are cached, for example as part of the ServiceWorker lifecycle.
Methods
CacheStorage (accessed via caches global)
open(cacheName)
: Returns a Promise that resolves to the Cache object matching the cacheName.match(request, options)
: Checks if a given Request is a key in any of the Cache objects.has(cacheName)
: Returns a Promise that resolves to true if a Cache object matching the cacheName exists.delete(cacheName)
: Finds the Cache object matching the cacheName and deletes it.keys()
: Returns a Promise that resolves to an array of strings containing the names of all Cache objects.
https://ngiotsas.github.io/webapihtml/?page=cache-api
9.Basic Fetch Example
This section provides a complete example of using the Fetch API for a basic GET request.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fetch API Example</title>
</head>
<body>
<h1>Fetch API Example</h1>
<button id="fetchButton">Fetch Data</button>
<div id="result">Results will appear here...</div>
</body>
</html>
JavaScript
document.getElementById('fetchButton').addEventListener('click', () => {
const resultDiv = document.getElementById('result');
// Show loading state
resultDiv.innerHTML = '<p>Loading...</p>';
// Fetch data from an API
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
resultDiv.innerHTML = `
<h2>${data.title}</h2>
<p>${data.body}</p>
<p><strong>User ID:</strong> ${data.userId}</p>
`;
})
.catch(error => {
resultDiv.innerHTML = `<p>Error: ${error.message}</p>`;
});
});
https://ngiotsas.github.io/webapihtml/?page=basic-fetch
10.POST Request Example
This section demonstrates how to make a POST request using the Fetch API.
JavaScript Example
// Create the data object to send
const postData = {
title: 'My Post Title',
body: 'This is the content of my post.',
userId: 1
};
// Make the POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Post created:', data);
})
.catch(error => {
console.error('Error:', error);
});
https://ngiotsas.github.io/webapihtml/?page=post-request
11.Streaming Response Example
This section demonstrates how to process a response using streams for efficient handling of large data.
Example: Processing Streamed Data
async function fetchWithProgress(url) {
const response = await fetch(url);
const contentLength = response.headers.get('content-length');
const total = parseInt(contentLength, 10);
let loaded = 0;
const reader = response.body.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
loaded += value.length;
// Update progress
const progress = Math.round((loaded / total) * 100);
console.log(`Downloaded: ${progress}%`);
}
// Combine chunks
const allChunks = new Uint8Array(loaded);
let position = 0;
for (const chunk of chunks) {
allChunks.set(chunk, position);
position += chunk.length;
}
return new Response(allChunks);
}
https://ngiotsas.github.io/webapihtml/?page=streaming-response
12.Browser Compatibility
This section provides information about browser compatibility for the WebAPI features described in this standard.
Fetch API
Feature | Chrome | Firefox | Safari | Edge |
---|---|---|---|---|
Basic fetch() | 42+ | 39+ | 10.1+ | 14+ |
Response.body (Streams) | 43+ | 65+ | 10.1+ | 79+ |
AbortController | 66+ | 57+ | 11.1+ | 16+ |
Browser compatibility information is current as of August 2025. For the most up-to-date information, consult browser-specific documentation.
https://ngiotsas.github.io/webapihtml/?page=browser-compatibility
13.References
This section provides references to related specifications, documentation, and resources.
Related Specifications
- Fetch Standard - The official Fetch API specification
- Service Workers Specification - The official Service Workers specification
- Streams Standard - The official Streams API specification
Documentation
https://ngiotsas.github.io/webapihtml/?page=references