Idempotency
Idempotency ensures that multiple identical requests produce the same result as a single request. By attaching unique idempotency keys to API calls, you prevent duplicate resource creation when requests are retried due to network failures or timeouts. Retried requests with the same key return the original result instead of creating new resources.
Implementation
Provide a unique key in the header. Keys expire after 24 hours.
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
Conflict Response (409)
{
"code": 409,
"statusText": "Conflict",
"message": "Request already processed with this idempotency key"
}
Client Examples
- Node.js
- Python
- Java
- Bash
const crypto = require('crypto');
function generateIdempotencyKey(data) {
const hash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
return `req_${hash}`;
}
import hashlib
import json
def generate_idempotency_key(data):
hash_obj = hashlib.md5(json.dumps(data, sort_keys=True).encode())
return f"req_{hash_obj.hexdigest()}"
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public String generateIdempotencyKey(Object data) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(data);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(json.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return "req_" + sb.toString();
}
generate_idempotency_key() {
local data="$1"
local hash=$(echo -n "$data" | md5sum | cut -d' ' -f1)
echo "req_$hash"
}