API integration examples Free template
Fetch API client with error handling
A tiny, reusable JavaScript API client: JSON in and out, timeouts, readable errors and a simple page to try it.
About this template
A small wrapper around fetch that every API integration needs: it sends and receives JSON, adds a timeout so a slow server cannot hang your page, turns HTTP errors into real Error objects with the status and the server's message, and keeps the base URL and headers in one place. The page lets you type an address and see the result. Note: the playground preview blocks all network access on purpose, so run this template on your own computer (download it) to talk to a real API.
Look under the hood
Included source files
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>API client</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>API client</h1>
<p>Enter the path of a resource on the API below and press Get. Run this page from your own computer: browsers allow calls to public APIs that permit it.</p>
<form id="form">
<label for="base">API base address</label>
<input id="base" value="https://jsonplaceholder.typicode.com">
<label for="path">Path</label>
<input id="path" value="/todos/1">
<button type="submit">Get</button>
</form>
<p id="state" role="status"></p>
<pre id="result"></pre>
</main>
<script src="api-client.js"></script>
<script src="app.js"></script>
</body>
</html>
/**
* A small API client.
*
* const api = createApiClient({ baseUrl: 'https://jsonplaceholder.typicode.com', headers: { Authorization: 'Bearer ...' } });
* const todo = await api.get('/todos/1');
* const created = await api.post('/posts', { title: 'Hello' });
*
* Failed requests throw an ApiError with .status (0 for network problems and timeouts), .body and a readable message.
*/
class ApiError extends Error {
constructor(message, status, body) {
super(message);
this.name = 'ApiError';
this.status = status;
this.body = body;
}
}
function createApiClient({ baseUrl = '', headers = {}, timeoutMs = 10000 } = {}) {
async function request(method, path, body) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
let response;
try {
response = await fetch(baseUrl + path, {
method,
headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
} catch (error) {
if (error.name === 'AbortError') throw new ApiError('The request took longer than ' + timeoutMs / 1000 + ' seconds.', 0, null);
throw new ApiError('The server could not be reached. Check your connection.', 0, null);
} finally {
clearTimeout(timer);
}
const text = await response.text();
let data = null;
if (text) {
try { data = JSON.parse(text); } catch (error) { data = text; }
}
if (!response.ok) {
const detail = data && typeof data === 'object' ? (data.message || data.error || '') : '';
throw new ApiError('Request failed (' + response.status + ')' + (detail ? ': ' + detail : ''), response.status, data);
}
return data;
}
return {
get: (path) => request('GET', path),
post: (path, body) => request('POST', path, body ?? {}),
put: (path, body) => request('PUT', path, body ?? {}),
patch: (path, body) => request('PATCH', path, body ?? {}),
delete: (path) => request('DELETE', path),
};
}
const form = document.getElementById('form');
const state = document.getElementById('state');
const result = document.getElementById('result');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const api = createApiClient({ baseUrl: document.getElementById('base').value.trim(), timeoutMs: 8000 });
state.textContent = 'Loading...';
result.textContent = '';
try {
const data = await api.get(document.getElementById('path').value.trim());
state.textContent = 'Done.';
result.textContent = JSON.stringify(data, null, 2);
} catch (error) {
// ApiError carries the status, so you can react differently to 404 and 500.
state.textContent = error.message;
console.error(error);
}
});
body { font-family: system-ui, -apple-system, 'Segoe UI', sans-serif; line-height: 1.5; color: #141c20; }
main { max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
label { display: block; margin-top: 0.8rem; font-weight: 600; }
input { width: 100%; padding: 0.5rem 0.7rem; font: inherit; border: 1px solid #b9c0c5; border-radius: 0.5rem; }
button { margin-top: 1rem; padding: 0.6rem 1.4rem; font: inherit; font-weight: 600; color: #fff; background: #c00000; border: 0; border-radius: 0.5rem; cursor: pointer; }
pre { padding: 1rem; overflow: auto; background: #f4f5f7; border-radius: 0.5rem; }
Update history
- 1.0.0
First release.