Learn about idempotency and how idempotency keys prevent unintended results from accidental duplicate requests.
An API call or operation is idempotent if it has the same result no matter how many times it's applied. That is, an idempotent operation provides protection against accidental duplicate calls causing unintended consequences.
For example, suppose CreatePayment
didn't require idempotency and you make a successful CreatePayment
request (Square successfully processes the payment). However, your connection fails before you receive success confirmation from Square. You don't know what happened to your request and therefore you make the request again, charging the customer twice.
Square supports idempotency by allowing API operations to provide an idempotency key (a unique string) to protect against accidental duplicate calls that can have negative consequences.
In the case of the preceding CreatePayment
example:
If you make the same
CreatePayment
request with the same idempotency key again, the endpoint knows it's a duplicate request. It doesn't take the payment again. Instead of getting an error, the endpoint returns the response as the first successfulCreatePayment
response.If you use the same idempotency key but change the
CreatePayment
request (for example, specify a different payment amount), you get an error indicating that you used the idempotency key previously. Note that this behavior might vary depending on the API.
Idempotency keys can be anything, but they need to be unique. Virtually all popular programming languages provide a function for generating unique strings. You should use one of these language calls.
Language | Recommended function |
---|---|
Ruby | SecureRandom.uuid |
PHP | uniqid |
Java | UUID.randomUUID |
Python | uuid |
C# | Guid.NewGuid |
Node.js | crypto.randomUUID |
There are other Square API patterns. For more information, see Common Square API Patterns.