Step-by-step tutorial: fetching public content using direct API web links
Public APIs return JSON documents over HTTPS. Browsers can request them with fetch when CORS headers allow,
or your PHP backend can proxy requests to hide keys and cache responses. This lesson uses a no-key JSON placeholder service for practice.
Client-side fetch with error handling
Always check response.ok before parsing JSON. Network failures throw—wrap calls in try/catch and show human-readable errors in the UI.
async function loadPosts() {
const list = document.getElementById('post-list');
list.textContent = 'Loading…';
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
if (!res.ok) throw new Error('HTTP ' + res.status);
const posts = await res.json();
list.innerHTML = posts
.map(p => `<article><h3>${escapeHtml(p.title)}</h3><p>${escapeHtml(p.body)}</p></article>`)
.join('');
} catch (err) {
list.textContent = 'Could not load data. Try again later.';
console.error(err);
}
}
function escapeHtml(str) {
return str.replace(/[&<>"']/g, c => ({
'&':'&','<':'<','>':'>','"':'"',"'":'''
})[c]);
}Below is how the output typically looks in a browser, terminal, or API client:
The escapeHtml helper prevents XSS when API strings contain unexpected markup—treat all remote text as untrusted.
Server-side proxy (PHP)
When APIs require secrets or block browser CORS, call the API from PHP with cURL and return sanitized JSON to your front end.
$ch = curl_init('https://globaltuts.com/public/courses');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
if ($body === false) {
http_response_code(502);
exit;
}
header('Content-Type: application/json');
echo $body;Below is how the output typically looks in a browser, terminal, or API client:
Example ran successfully.