Send a POST Request With a JSON Body#
Send data to an API with fetch. This example posts a JSON payload and
checks the response, the pattern behind most “report to a service” jobs.
The Script#
// post-json.js
import env from "env";
const payload = {
event: "daily-sync",
at: new Date().toISOString(),
count: 42,
};
const res = await fetch(env.get("API_URL"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${env.get("API_TOKEN")}`,
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const detail = await res.text();
throw new Error(`POST failed (${res.status}): ${detail}`);
}
console.log(`Sent. Server responded ${res.status}`);
How It Works#
JSON.stringifyturns the object into the request body, and theContent-Type: application/jsonheader tells the server how to read it.- The token is read from a secret, never written into the script.
- Reading the error body on failure makes debugging far easier than the status code alone.
Setup#
Create two secrets:
| Secret | Value |
|---|---|
API_URL |
The endpoint to post to |
API_TOKEN |
The bearer token for the API |
Create a job that points at post-json.js.