Fetch from the page
Hub › AWS › Intermediate › Fetch from the page
Goal
After this page you will have an updated index.html that calls the API at runtime and renders the item list in the browser.
Prerequisites
- The HTTP API — your invoke URL returns JSON.
Updating index.html
Replace the static content in the index.html from the beginner tier with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Items</title>
</head>
<body>
<h1>Items</h1>
<ul id="items"></ul>
<script>
// Replace with your own API Gateway invoke URL.
const API_URL = "https://abcd1234.execute-api.us-east-1.amazonaws.com/items";
fetch(API_URL)
.then((r) => r.json())
.then((items) => {
const ul = document.getElementById("items");
for (const it of items) {
const li = document.createElement("li");
li.textContent = it.name;
ul.appendChild(li);
}
})
.catch((e) => {
document.getElementById("items").textContent = "Failed to load: " + e.message;
});
</script>
</body>
</html>API_URL is a placeholder. Paste your real invoke URL from the previous page before uploading.
How it works
- The browser loads
index.htmlfrom CloudFront (cached static file — fast). - The
<script>runs:fetch(API_URL)sends a GET request to API Gateway. - API Gateway invokes the Lambda; the Lambda returns the JSON array.
.then((items) => { ... })iterates over the array and appends a<li>for each item.- If the fetch fails, the
.catchhandler shows the error in place of the list.
Local checkpoint
To verify the JavaScript before uploading:
- Save the file above as
index.htmlwithAPI_URLset to your real invoke URL. - Serve it locally:
python3 -m http.server 8080- Open
http://localhost:8080in a browser. The list should render.
The fetch call goes out to your real API Gateway URL, so this test requires a live Lambda. If you prefer a fully offline test, point API_URL at a local stub:
# In a separate terminal: serve a static items.json
echo '[{"id":1,"name":"Notebook"},{"id":2,"name":"Pen"},{"id":3,"name":"Sticky notes"}]' > items
python3 -m http.server 9090Then set API_URL = "http://localhost:9090/items" temporarily, reload, and verify the list. Reset API_URL to your real invoke URL before uploading.
Upload to S3
# PLACEHOLDER bucket name — use your own from the beginner tier.
aws s3 cp index.html s3://your-bucket-name/index.htmlAfter uploading, the old index.html may still be cached at the CloudFront edge. The next page covers how to flush it.
Next → Cache invalidation