Direct answer
A Postman pre-request script cannot reliably prevent a duplicate write by itself. It can generate and send an idempotency key, but Postman has no built-in mechanism to track prior successful write events or block an outgoing request based on client-side state. Idempotency must be enforced by the API backend.
Confirmed behavior
- Postman pre-request and test scripts run in a JavaScript sandbox inside the Postman client.
pm.collectionVariables and pm.environment persist only within the Postman client or current collection run; the API server never sees them.
- Postman provides no native way to cancel a request after the pre-request script runs.
- A test script can read
pm.response.code and write the result to a collection variable, but that happens after the write has already reached the server.
Variable state to check
If you still want client-side bookkeeping, check pm.collectionVariables.get("lastWriteKey") or a similar flag in the pre-request script. This can warn a human tester or skip a locally generated payload, but it does not communicate with the backend and cannot prevent a duplicate HTTP request.
Steps for this case
- In the request's Pre-request script, set a key once per logical write and attach it to the request:
if (!pm.collectionVariables.get('idempotencyKey')) {
pm.collectionVariables.set('idempotencyKey', pm.variables.replaceIn('{{$guid}}'));
}
pm.request.headers.upsert({
key: 'Idempotency-Key',
value: pm.collectionVariables.get('idempotencyKey')
});
Verify header manipulation support in your Postman runtime via the Postman Console; dynamic variable support may vary by version.
- Send the same key with every retry of the same logical write.
- In the Tests tab, record the outcome without assuming it prevented anything:
var json = pm.response.json();
pm.collectionVariables.set('lastWriteStatus', pm.response.code);
pm.collectionVariables.set('lastWriteId', json && json.id ? json.id : null);
- Run the request twice with the same key and inspect the backend response. The server should return the original result or a duplicate error, not perform the write again.
Missing diagnostic detail
Does your API document an Idempotency-Key or equivalent deduplication header? If not, no client-side Postman script can make the write idempotent; you need backend support before this pattern is safe to use.
Verification
- Open the Postman Console and confirm the
Idempotency-Key header is identical across two runs.
- Confirm the backend returns the same response or a duplicate error on the second call with the same key.
- Treat any behavior where the backend processes the same key twice as unverified and not idempotent.
Assumptions: modern Postman desktop or web client with the pm.* scripting API. Collection variables reset between separate collection runs unless explicitly persisted.