How to setup Idempotency for Laravel APIs
So now you know about idempotency and you want to set up an idempotent API. Here’s how I did it, using a middleware in Laravel
STEP 1
Create a middleware
php artisan make:middleware Idempotency
STEP 2
Setup your cache. First, install predis
composer require predis/predis
STEP 3
Go to your .env file and set it to use predis
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
STEP 4
Put this content in your middleware.
It enables you to set the header to be passed by consumers of your API and when how long the request caching is in minutes. Here are the expected behaviours:
- It would set the “Is-Replay” header to true for responses that come out of the cache.
- It won't cache on your local environment for easy development
- It would respond with a 400 if the Idempotency key isn’t set
- If the Idempotency key is valid and the endpoint is different from the original request, it would respond with a 400
- If the Idempotency key is valid, and the endpoint is the same as the first request, it would return the same response it originally gave without reaching the endpoint.
Feel free to modify to your taste and tell me why. I’d love to know.
STEP 5
Put some endpoints behind it. Go to app/Http/Kernel.php
Add the class to your API middleware group
'api' => [
'throttle:60,1',
'bindings',
Idempotency::class,
],
All done!
Now you have resilient APIs.