Idempotency
Send POST requests of the simple API again after a timeout without creating anything twice, with the Idempotency-Key header.
A request can time out or lose its connection after switchfile has already started the conversion. Sent again, it would convert the file twice. With an Idempotency-Key, a repeated request returns the first result instead.
Send a key#
Every POST request of the simple API takes the header Idempotency-Key: 1 to 255 visible ASCII characters. A UUID works well. Make a new key for every new request and keep it until the request has succeeded.
KEY=$(uuidgen)
curl https://api.switchfile.io/v1/convert \
-H "Authorization: Bearer $SWITCHFILE_API_KEY" \
-H "Idempotency-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/report.docx", "to": "pdf"}'import { randomUUID } from "node:crypto";
const key = randomUUID();
const send = () =>
fetch("https://api.switchfile.io/v1/convert", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SWITCHFILE_API_KEY}`,
"Idempotency-Key": key,
"Content-Type": "application/json",
},
body: JSON.stringify({ url: "https://example.com/report.docx", to: "pdf" }),
});
let res;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
res = await send();
if (res.status !== 409 && res.status < 500) break;
} catch (err) {
if (attempt === 3) throw err;
}
await new Promise((r) => setTimeout(r, 1000 * attempt));
}
console.log(res.status, res.headers.get("idempotent-replayed"), await res.json());What you get back#
| Case | Response |
|---|---|
| Same key, same request | The same conversion, batch, upload or archive, with Idempotent-Replayed: true. Nothing is created twice and no credits are used twice |
| Same key, different request | 422 IDEMPOTENCY_KEY_REUSED |
| Same key while the first request is still running | 409 IDEMPOTENCY_KEY_IN_USE with Retry-After: 1 |
A repeated request shows the current state, so it can already return the finished result. Keys are kept for 24 hours per account. A request that failed does not use up its key, so you can send it again with the same key.
Jobs and tasks (v2)#
/v2 requests do not take an Idempotency-Key. To avoid duplicate jobs after a timeout, set a tag on the job and look for it with GET /v2/jobs and filter[tag] before you create the job again.