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#

  • fetch returns a response. Check res.ok before reading the body, so an error page does not get parsed as JSON.
  • res.json() parses the body for you. Use res.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 /todos and 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.