When creating APIs, you may want to implement rate limiting within your API to prevent excessive requests being made to your API and exhausting server resources. This is extremely important if your API is dependent upon another API that has rate limits already in place. Rate limiting in Yii2 is implemented by yii\filters\RateLimiter
and yii\filters\RateLimitInterface
.
To get started with rate limiting, we first need to add yii\filters\Ratelimiter
to our controller behaviors. The yii\filters\RateLimiter
class is coupled to our user identity class. Consequently, rate limiting will only be applied to actions that are protected by authentication. Any action that is not protected by an authenticate filter will not have rate limiting applied to it. The following example illustrates the code blocks required to implement yii\filters\RateLimiter
within our controller:
<?php
namespace app\controllers;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\RateLimiter;
use yii\rest\ActiveController...