Network errors, timeouts, and client crashes can leave you unsure whether a request succeeded. Idempotency keys let you safely retry any POST request. If the API has already processed a request with the same key, it returns the cached response instead of executing the operation again.
If you send a request with the same idempotency key but different request body parameters, the API rejects it with a 422 status:
Copy
Ask AI
# First request - succeedscurl -X POST https://api.leanrails.com/v1/payment_intents \ -u "$API_KEY:" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: my-unique-key-123" \ -d '{"amount": 5000, "currency": "usd"}'# Second request with SAME key but DIFFERENT amount - rejectedcurl -X POST https://api.leanrails.com/v1/payment_intents \ -u "$API_KEY:" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: my-unique-key-123" \ -d '{"amount": 9999, "currency": "usd"}'
Error response (422):
Copy
Ask AI
{ "error": { "type": "invalid_request_error", "code": "idempotency_key_reuse", "message": "This idempotency key has already been used with different request parameters.", "param": null, "doc_url": "https://docs.leanrails.com/errors/idempotency_key_reuse" }}
For some operations, it makes sense to derive the key from a business identifier to ensure a specific operation only happens once.
Copy
Ask AI
// Ensure a specific order is only charged onceconst key = `charge-order-${orderId}`;
Store the key before sending
Persist the idempotency key alongside the operation in your database before making the API call. If your process crashes, you can retry with the same key.