Reference
Idempotent requests
Networks fail. If a request to send times out, you cannot know whether it was accepted. Send POST /v1/messages and POST /v1/batches with an Idempotency-Key header, and retry with the same key.
curl https://bulksmsapi.cc/v1/messages \
-H "Authorization: Bearer $BULKSMSAPI_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-55102-shipped" \
-d '{"to": "+14155550123", "text": "Order 55102 has shipped."}'Rules
- A key is any string up to 255 characters. Use something that names the event: an order id and step, or a UUID made before the first try.
- An accepted request (202) is remembered for 24 hours per account. The same key with the same body returns the first answer again, with the header
Idempotent-Replayed: true, and sends nothing. - The same key with a different body answers
409 idempotency_conflict. - Requests that fail with an error are not remembered, so you can fix them and retry with the same key.
How a replay is matched
- The match is on the method, the path and the JSON body. Field order in the body does not matter, so a client that rebuilds the same object in a different order still gets the replay.
- Keys belong to the account, not to one API key: a retry from a second server or a second key with the same Idempotency-Key gets the same first answer.
- The replayed answer has the same status and body as the first one, including the message or batch id, so your code reads it the same way.
- After 24 hours the key is free again, and a request that uses it is treated as new.
- A key longer than 255 characters answers
400 invalid_requestwithparamset toIdempotency-Key.
Choosing keys
Make the key in your own system before the first try and store it with the job, so every retry reuses it. Good keys name the event, such as order-55102-shipped or invoice-8812-reminder-1, or are a UUID kept in your job queue. A new random key on every retry gives no protection, because each try then looks like a new request.
A safe retry loop
- Send the request with its Idempotency-Key.
- On a timeout or a 5xx answer, wait a few seconds and send the same request with the same key.
- On 202, read the id from the body, whether it is the first answer or a replay.
- On
409 idempotency_conflict, the body changed under an old key: give the changed request a new key.