Fetch JSON From an API#
Call an HTTP API and work with the JSON it returns. This example uses JSONPlaceholder, a free fake REST API built for testing, so you can run it without signing up for anything.
The Script#
// fetch-json.js
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
const todo = await res.json();
console.log(`#${todo.id} ${todo.title}`);
console.log(`Completed: ${todo.completed}`);
How It Works#
fetchreturns a response. Checkres.okbefore reading the body, so an error page does not get parsed as JSON.res.json()parses the body for you. Useres.text()when the body is not JSON.- The response for this endpoint is a single object. Swap the URL for a
collection endpoint such as
/todosand the parsed value is an array you can iterate.
Setup#
For an API that requires a key, store it as a secret and read it with
env.get, as shown in
Post to a Custom Webhook. Schedule
the job weekly, for example 0 9 * * 1.