Script Examples
Copy-paste recipes for everyday API work. Each one says which script it goes in.
Most recipes use httpbin.org, a free service that echoes back what you send, so you can try them without your own API. Its /anything endpoint returns your request (URL, headers, and body under json), which lets the examples pretend to be a real API.
Contents
- Log in once and reuse the token
- Create a resource, then use its ID
- Add a timestamp and request ID to every call
- Sign a request with HMAC
- Stop if the token has expired
- Block write requests on production
- Walk through pages with a cursor
- Build a JSON body from variables
- A full test suite for one endpoint
Log in once and reuse the token
The most common chain: a login request saves a token, and every other request uses it.
Request 1: Login
POST https://httpbin.org/anything/login
{"username":"ada","token":"demo-token-123"}Post-Response
const data = dotfetch.response.json();
// A real API returns the token directly, e.g. data.access_token.
// httpbin echoes our body back under "json":
const token = data.json.token;
test('Login returned a token', () => {
assert(token, 'No token in the response');
});
dotfetch.env.set('ACCESS_TOKEN', token);
console.log('Saved ACCESS_TOKEN');Request 2: Any protected call
GET https://httpbin.org/bearer
Auth tab: Bearer Token = {{ACCESS_TOKEN}}
Send Request 1, then Request 2. httpbin answers:
{ "authenticated": true, "token": "demo-token-123" }The token lives in memory until you close the Request Builder, and it's never written to .env. Save both requests in one collection and the flow is two clicks.
Create a resource, then use its ID
Request 1: Create
POST https://httpbin.org/anything/users
{"id": 1234, "name": "Ada"}Post-Response
const created = dotfetch.response.json().json; // real API: dotfetch.response.json()
test('User was created', () => {
assert(dotfetch.response.status === 200, `Status ${dotfetch.response.status}`); // real API: 201
assert(created.id, 'No id returned');
});
dotfetch.env.set('CREATED_USER_ID', String(created.id));Request 2: Fetch it
GET https://httpbin.org/anything/users/{{CREATED_USER_ID}}
httpbin shows "url": "https://httpbin.org/anything/users/1234".
Add a timestamp and request ID to every call
Pre-Request
dotfetch.request.headers['X-Request-Id'] = dotfetch.crypto.uuid();
dotfetch.request.headers['X-Timestamp'] = new Date().toISOString();Send to https://httpbin.org/headers:
"X-Request-Id": "3b241101-e2bb-4255-8caf-4136c566a962",
"X-Timestamp": "2026-11-04T10:15:30.123Z"Want the same value in a header and the body? Set a variable and use it in both places:
dotfetch.env.set('REQ_ID', dotfetch.crypto.uuid());Header: X-Request-Id: {{REQ_ID}}
Body: {"requestId":"{{REQ_ID}}","item":"book"}Sign a request with HMAC
The API expects X-Signature = HMAC-SHA256 of timestamp.body, hex-encoded, with a shared secret.
# .env
API_SECRET=my-shared-secret
ORDER_ID=A-1001POST https://httpbin.org/anything/orders
{"orderId":"{{ORDER_ID}}","amount":250}Pre-Request
const secret = dotfetch.env.get('API_SECRET');
assert(secret, 'API_SECRET is missing from the active environment');
const ts = String(Math.floor(Date.now() / 1000));
const body = dotfetch.env.resolve(dotfetch.request.body); // {"orderId":"A-1001","amount":250}
dotfetch.request.headers['X-Timestamp'] = ts;
dotfetch.request.headers['X-Signature'] = dotfetch.crypto.hmac('sha256', secret, `${ts}.${body}`);Why it works:
env.resolve()signs the body after{{ORDER_ID}}is filled in, which is exactly what's sent.- DotFetch sends the body byte for byte, so the server computes the same signature.
- If
API_SECRETis missing, theassertstops the request instead of sending a bad signature.
To check the signature on the server side (Node.js):
const expected = crypto.createHmac('sha256', SECRET).update(`${ts}.${rawBody}`).digest('hex');Stop if the token has expired
Save the expiry time when you log in, and check it before every other request.
Post-Response (on the login request)
const { access_token, expires_in } = dotfetch.response.json(); // expires_in in seconds
dotfetch.env.set('ACCESS_TOKEN', access_token);
dotfetch.env.set('TOKEN_EXPIRES_AT', String(Date.now() + expires_in * 1000));Pre-Request (on the other requests)
const expiresAt = Number(dotfetch.env.get('TOKEN_EXPIRES_AT') ?? 0);
assert(Date.now() < expiresAt - 30_000, 'Token expired or about to expire: run the Login request again');The 30-second margin avoids sending a token that expires mid-flight.
Block write requests on production
Add a flag to your production environment only:
# .env.production
READ_ONLY=truePre-Request
const readOnly = dotfetch.env.get('READ_ONLY') === 'true';
const method = dotfetch.request.method;
assert(
!readOnly || ['GET', 'HEAD', 'OPTIONS'].includes(method),
`${method} is blocked: this environment is READ_ONLY`
);With production active, a DELETE stops with:
⚠️ Pre-request script failed (line 4): DELETE is blocked: this environment is READ_ONLY
and nothing reaches the server. Other environments are unaffected.
Walk through pages with a cursor
GET https://api.example.com/items?limit=50&cursor={{NEXT_CURSOR}}
Pre-Request: on the first run, there's no cursor yet, so drop the parameter.
if (!dotfetch.env.get('NEXT_CURSOR')) {
dotfetch.request.params.delete('cursor');
}Post-Response: remember where the next page starts.
const { items, next_cursor } = dotfetch.response.json();
console.log(`Got ${items.length} items`);
if (next_cursor) {
dotfetch.env.set('NEXT_CURSOR', next_cursor);
} else {
dotfetch.env.unset('NEXT_CURSOR');
console.log('Last page reached');
}Press Send repeatedly to walk through the pages. After the last page the cursor is cleared, so the next Send starts from the beginning.
Build a JSON body from variables
When the body needs logic (a computed date, an optional field), build it in the script instead of the Body tab:
Pre-Request
const start = new Date();
const end = new Date(start.getTime() + 7 * 24 * 60 * 60 * 1000);
const body = {
customerId: dotfetch.env.get('CUSTOMER_ID'),
from: start.toISOString().slice(0, 10),
to: end.toISOString().slice(0, 10),
};
if (dotfetch.env.get('COUPON')) {
body.coupon = dotfetch.env.get('COUPON');
}
dotfetch.request.body = body; // objects are sent as JSONSent:
{"customerId":"C-77","from":"2026-11-04","to":"2026-11-11"}Content-Type: application/json is added automatically if you haven't set one.
A full test suite for one endpoint
GET https://httpbin.org/json
Post-Response
const res = dotfetch.response;
test('Status is 200', () => {
assert(res.status === 200, `Got ${res.status}`);
});
test('Responds within 1 second', () => {
assert(res.time < 1000, `Took ${res.time} ms`);
});
test('Content-Type is JSON', () => {
const type = res.headers['content-type'] ?? '';
assert(type.includes('application/json'), `Got "${type}"`);
});
test('Has a slideshow with slides', () => {
const { slideshow } = res.json();
assert(slideshow, 'slideshow is missing');
assert(Array.isArray(slideshow.slides), 'slides is not an array');
assert(slideshow.slides.length > 0, 'slides is empty');
});
test('Every slide has a title', () => {
res.json().slideshow.slides.forEach((s, i) => {
assert(typeof s.title === 'string' && s.title.length > 0, `slides[${i}] has no title`);
});
});Tests tab:
✓ 5 passed 5 total tests
More detail on each API: dotfetch.env · request & response · Tests · Crypto & Utils