Everything so far has lived in the browser. The calculator’s food list is local. But real apps get data from somewhere else: a server, a database, an API.
An API is just a set of URLs that return data. You send a request; it sends back a response, usually JSON.
Request and response
GET https://example.com/v1/foods?q=chicken
GETis the method. You’re asking to read something.- The URL is the endpoint.
?q=chickenis a query parameter — extra information for the server.- The response usually looks like JSON:
{
"foods": [
{ "id": "chicken-breast", "name": "Chicken breast", "calories": 165 }
]
}
JSON looks like a JavaScript object, but it’s text. response.json() parses it into real objects.
Synchronous vs asynchronous
Some code finishes immediately:
const total = 2 + 2;
Network requests don’t. The data might take 50ms or 5 seconds. JavaScript doesn’t freeze the whole page waiting; it gives you a Promise — a placeholder for a value that will arrive later.
async and await let you write asynchronous code that reads like normal code:
async function loadFoods() {
const response = await fetch("/v1/foods");
const data = await response.json();
console.log(data);
}
asyncmarks the function as asynchronous.awaitpauses that function until the promise settles.- The rest of the page keeps working while it waits.
fetch, step by step
async function loadFoods() {
try {
const response = await fetch("https://example.com/v1/foods");
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
const data = await response.json();
console.log(data.foods);
} catch (error) {
console.error("Something went wrong:", error);
}
}
Status codes worth knowing:
200— OK.400— bad request (your input is wrong).404— not found.500— server error.
Loading and error states
A good UI tells the user what’s happening:
button.disabled = true;
status.textContent = "Loading...";
try {
// fetch and render
status.textContent = "Loaded 4 foods.";
} catch (error) {
status.textContent = "Could not load foods. Try again.";
} finally {
button.disabled = false;
}
The finally block runs whether it worked or not. Re-enable the button there, not inside try, or it stays disabled after an error.
Try it
This demo loads recipes from a public API. Press the button, watch the loading state, then read the response in the console.
Console
Console is quiet. Run the code to see output.
Edit the code, then hit Run (or Ctrl + Enter) and watch the preview. This is a safe sandbox — you can't break the page.
Search the API
the plan's verify stepAdd a text input and a search button. When the user searches for 'pizza', fetch https://dummyjson.com/recipes/search?q=pizza and render the names. Show a loading message while it runs, and a friendly error message if the request fails.
Encode the query with encodeURIComponent(input.value) so spaces and special characters don't break the URL.
The mistakes everyone makes
- Forgetting
await. You get a Promise instead of the data. - Not checking
response.ok. A 404 is treated as success. - Calling
.json()twice. The body can only be read once. - Assuming the data is an array. Many APIs wrap it:
data.recipes,data.foods,data.items. - No loading state. The user clicks and nothing happens for two seconds.
- No error handling. One failed request leaves the UI stuck.
- Blocking the page. Don’t use synchronous requests; they don’t exist in modern fetch anyway.
- Storing the response in a global you never use. Render it.
An API is a URL (or set of URLs) that returns data, usually JSON.
Network requests are asynchronous; async/await makes them readable.
fetch resolves even on 404 — check response.ok.
response.json() parses the body; await it.
Handle loading, success, and error states.
CORS is the browser's rule for cross-origin responses.
Next: capstone time. We’ll write the calculator’s math as clean functions and test it before touching the UI.
Up next
Capstone part 1: calculator logic
Before touching the page, write the calculator's math as small, testable functions: BMR, activity multiplier, daily target, totals, and remaining calories.