Fetch & APIs
Most useful apps get their data from somewhere else: weather forecasts, exchange rates, football scores, your own server. An API (Application Programming Interface) is a web address that returns data instead of a web page, usually as JSON. The browser's fetch() function sends a request to an API and gives you back a promise of the response.
How a request works
Your page sends an HTTP request to a URL. The server sends back an HTTP response made of a status code (200 means OK, 404 means not found, 500 means a server error), some headers, and a body containing the data.
fetch resolves as soon as the response arrives. You still have to check the status and then read the body, which is a second promise.Your first fetch
JSONPlaceholder is a free practice API. This code asks it for one to-do item:
async function getTodo() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log(response.status, response.ok);
const todo = await response.json();
console.log(todo.title);
console.log(todo.completed);
}
getTodo();
Two awaits are needed. fetch() resolves with a Response object once the headers arrive; response.json() reads the rest of the body and parses it from JSON into a JavaScript object, which also takes time. Logging the whole todo object would show {userId: 1, id: 1, title: 'delectus aut autem', completed: false}.
Other ways to read the body include response.text() for plain text and response.blob() for images and files. You can read a body only once.
fetch doesn't reject on HTTP errors
This surprises almost everyone. The promise from fetch only rejects when the request couldn't be made at all: no internet, a blocked request, a mistyped domain. A 404 or 500 reply is still a reply, so the promise fulfils.
async function checkMissing() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/99999");
console.log(response.ok, response.status);
}
checkMissing();
So always check response.ok (true for statuses 200–299) and throw your own error when it is false. A small helper keeps this tidy:
async function getJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
Forgetting the second await: const data = response.json(); gives you a pending promise, so data.current is undefined. Write const data = await response.json();.
A real API: today's weather
Open-Meteo provides free weather data with no API key. Build the query string with URLSearchParams, which also encodes special characters for you:
async function nairobiWeather() {
const params = new URLSearchParams({
latitude: -1.29,
longitude: 36.82,
current: "temperature_2m"
});
const url = `https://api.open-meteo.com/v1/forecast?${params}`;
console.log(url);
try {
const data = await getJSON(url);
console.log(`Nairobi now: ${data.current.temperature_2m} °C`);
} catch (error) {
console.log("Could not load the weather:", error.message);
}
}
nairobiWeather();
Example output (the temperature is live data, so yours will differ):
The response contains more than the temperature, including latitude, longitude, current_units and a current object with time and temperature_2m. Open the URL in your browser to see the raw JSON.
Sending data with POST
To send data, pass an options object: the method, a Content-Type header, and a body converted to a JSON string.
async function createPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Habari", body: "Hello from Nairobi", userId: 1 })
});
const saved = await response.json();
console.log(response.status, saved);
}
createPost();
Status 201 means "created". JSONPlaceholder only pretends to save, so it always answers with id 101.
Browsers only let a page read responses from another website if that site allows it, a rule called CORS (Cross-Origin Resource Sharing). Public APIs like the two above allow everyone. If you see a "blocked by CORS policy" error, the server hasn't given your site permission; it isn't a bug in your fetch code. Also, never put secret API keys in browser JavaScript, because anyone can read them.
Try it: weather in East African capitals
Pick a city and fetch its current temperature. The page shows a loading message and handles errors. Try adding another city, or request wind_speed_10m as well (separate names with a comma: current: "temperature_2m,wind_speed_10m").
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
#result { margin-top: 10px; font-size: 1.2em; }
.error { color: #b3261e; }
</style>
</head>
<body>
<h2>Weather now</h2>
<select id="city">
<option value="-1.29,36.82">Nairobi</option>
<option value="0.35,32.58">Kampala</option>
<option value="-6.79,39.21">Dar es Salaam</option>
<option value="-1.94,30.06">Kigali</option>
</select>
<button id="get">Get temperature</button>
<p id="result"></p>
<script>
const select = document.querySelector("#city");
const result = document.querySelector("#result");
async function showWeather() {
const [latitude, longitude] = select.value.split(",");
const params = new URLSearchParams({ latitude, longitude, current: "temperature_2m" });
result.className = "";
result.textContent = "Loading...";
try {
const response = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const city = select.selectedOptions[0].text;
result.textContent = `${city}: ${data.current.temperature_2m} °C`;
} catch (error) {
result.className = "error";
result.textContent = `Could not load the weather (${error.message})`;
}
}
document.querySelector("#get").addEventListener("click", showWeather);
</script>
</body>
</html>
Key points
fetch(url)returns a promise of aResponse;await response.json()gives you the data.fetchonly rejects on network failure. Checkresponse.okand throw on 4xx/5xx statuses.- Wrap requests in
try/catchand show loading and error messages to the user. - For POST, send
method, aContent-Typeheader and aJSON.stringify'd body.
Tip: use the ← and → keys to move between pages.
