Secure API and Idempotency Mechanism
Idempotency-Key Header
What is it?
TheIdempotency-Key is a unique, cryptographically generated value added to each API request header.It ensures that retries of the same request are not executed more than once by the server.
This is especially important for operations that create or modify resources (e.g., payments, transactions, device records), where duplicate processing could lead to inconsistent data or unintended side effects.
Why is it used?
- Prevents duplicates: If a client retries a request due to a timeout or network error, the server can detect the same
Idempotency-Keyand ignore duplicate executions. - Ensures consistency: Clients can safely retry requests without worrying about unintended multiple writes.
- Improves reliability: Makes APIs more resilient against network instability.
Example Postman Pre-request script for API clients
How is it calculated in the Pre-request Script?
The provided Postman pre-request script generates theIdempotency-Key as follows:
-
Payload extraction
- Uses the raw request body as the payload.
- If the body is empty, falls back to the request URL path.
-
SHA256 hashing
- Computes a SHA256 hash of the payload string.
- Converts the result into an uppercase hex string.
- This ensures a deterministic and unique base for the key.
-
Timestamp inclusion
- Takes the current epoch time in milliseconds.
- Pads the string to make its length a multiple of 8.
- This adds uniqueness per request, even if the payload is identical.
-
TripleDES encryption
- Uses the SHA256 hash as the key for 3DES encryption.
- Encrypts the padded timestamp in ECB mode without padding.
- Produces an encrypted value as a hex string.
-
Final header assignment
- The resulting encrypted hex string becomes the
Idempotency-Key. - Added to the request headers automatically:
- The resulting encrypted hex string becomes the
Example Output (from console logs)
Summary
- Purpose: Guarantees safe retries by preventing duplicate request execution.
- Mechanism: Combines request payload + timestamp + encryption to create a unique key.
- Usage: Always included in the request header automatically when running an API client.