Simple and fully tested Laravel middleware for implementing idempotency in your API requests.
This library is installed via Composer and to install, run the following command:
composer require eufaturo/idempotency-middlewareThe package will automatically register itself.
You can now optionally publish the config file with:
php artisan vendor:publish --tag="eufaturo-idempotency-config"This will create a file at config/eufaturo/idempotency.php, where you can adjust the header names, the TTL of the cached response, and the HTTP methods considered idempotent.
Or if you prefer, without publishing the config file, you can define the following on your .env file:
IDEMPOTENCY_MAIN_HEADER="X-Idempotency-Key"
IDEMPOTENCY_REPEATED_HEADER="X-Idempotent-Replayed"
IDEMPOTENCY_EXPIRATION=720 # 12 hours (define in minutes)To use it, just apply the middleware in your route groups or a single route.
<?php
use Eufaturo\IdempotencyMiddleware\Idempotency;
Route::middleware(['auth:api', Idempotency::class])->group(function () {
Route::post('/create-user', function () {
// Create the user ...
});
});<?php
use Eufaturo\IdempotencyMiddleware\Idempotency;
Route::post('/create-user', function () {
// Create the user ...
})->middleware(Idempotency::class);To perform an idempotent request, provide an additional Idempotency-Key header through the request options where the value should be a valid UUID v4.
POST /api/create-user HTTP/1.1
Content-Type: application/json
Idempotency-Key: 6b3fd36c-24c6-4eb2-a764-bb6c91b33e56
{
"name": "John Doe",
"email": "john.doe@example.com",
"password": "secret"
}Note: If an idempotency key is reused with the same content body and endpoint, the original response, which is cached, will be returned, instead of continuing the normal execution and the header Idempotent-Replayed will be appended to the response.
The middleware will throw a Eufaturo\IdempotencyMiddleware\IdempotencyException in some scenarios:
- If the idempotency key is not a valid UUID V4
- If the idempotency key was used before but the content body is different
- If the idempotency key was used before but the endpoint is different
Please see CHANGELOG for more information about recent changes.
composer testThank you for your interest. Here are some of the many ways to contribute.
- Check out our contributing guide
- Look at our code of conduct
This library is open-sourced software licensed under the MIT license.