DEV Community

loading...

Idempotence in API design

stillwey profile image Weyler Maldonado ・2 min read

When you develop any kind of API, for some reason, idempotence it's an aspect that usually goes unnoticed, but indeed that aspect could make more robust and safe your piece of software. Let me explain it.

APIs based on REST use HTTP to communicate with the different clients. So, HTTP has a property called safe; an HTTP request it's safe if doesn't mutate the application state. Consider the table below.

HTTP verb Common use Safe
GET Get resources Yes
POST Add resources No
PUT Modify resources No
PATCH Modify resources No
DELETE Delete resources No

Having said that, what's idempontence? Idempotence make that multiple identical requests has the same effect as making a single request, minimizing or preventing observable side effects, if you're a functional programming enthusiast, a good analogy could be pure functions. Mathematically speaking, consider the function:

f(x) = x^2 + 2

If we say x = 2, no matter how many times use the function, the result always will be 6. Now, this could be seen in programming, for example in the JavaScript case, Math.cos(x) always return the same value of x. The REST specification indicates that methods GET, PUT, DELETE should be idempotent.

So, how can implement idempotence in our projects?

There's no perfect recipe, but REST has some features that can help us:

  • The header If-None-Match: * when it is created or updated a resource, this to avoid identifier collisions and return 412 Precondition failed if the operation fails.
  • The header ETag: {etag-hash} in the resposponses of GET methods.

But we can learn from big companies like Stripe, they have a simple implementation for their APIs, they make that clients generate a random and unique hash (like UUID) and attached in a header called Idempotency-Key for every request. This can be stored, in cache engines for example, like Redis or Memcached and handled like one unique request.

Maybe never have the need to implement this, but it's important to know that exists and when you facing a similar problem, look back and consider if idempontence could solve the problem.

Discussion (0)

pic
Editor guide