Fetch API GET Requests with JavaScript
The Fetch API provides a promise-based interface for HTTP requests. It works well with async and await and is the recommended starting point for most modern browser requests.
Basic GET request
async function getUsers() {
const response = await fetch('/api/users.php');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
getUsers().then(console.log).catch(console.error);
Understand response handling
Fetch rejects for network failures, but an HTTP 404 or 500 normally still resolves to a Response. Always inspect response.ok or response.status before parsing a response as successful.
Query parameters
Use URLSearchParams rather than manually concatenating untrusted values:
const params = new URLSearchParams({ q: 'php', page: '2' });
const response = await fetch(`/api/search.php?${params}`);
Practical guidance
Handle empty responses deliberately, set reasonable server and client timeouts where needed, and show users a useful error state. Do not assume JSON parsing will succeed for every response.