@@ -219,15 +219,16 @@ When using a rate limiter in APIs, it's common to include some standard HTTP
219
219
headers in the response to expose the limit status (e.g. remaining tokens, when
220
220
new tokens will be available, etc.)
221
221
222
- That's why the ``consume() `` object returns a :class: `Symfony\\ Component\\ RateLimiter\\ RateLimit `
223
- object which you can use to get the value of those HTTP headers::
222
+ Use the :class: `Symfony\\ Component\\ RateLimiter\\ RateLimit ` object returned by
223
+ the ``consume() `` method (also available via the ``getRateLimit() `` method of
224
+ the :class: `Symfony\\ Component\\ RateLimiter\\ Reservation ` object returned by the
225
+ ``reserve() `` method) to get the value of those HTTP headers::
224
226
225
227
// src/Controller/ApiController.php
226
228
namespace App\Controller;
227
229
228
230
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
229
231
use Symfony\Component\HttpFoundation\Response;
230
- use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
231
232
use Symfony\Component\RateLimiter\RateLimiter;
232
233
233
234
class ApiController extends AbstractController
@@ -236,18 +237,20 @@ object which you can use to get the value of those HTTP headers::
236
237
{
237
238
$limiter = $anonymousApiLimiter->create($request->getClientIp());
238
239
$limit = $limiter->consume();
240
+ $headers = [
241
+ 'X-RateLimit-Remaining' => $limit->getRemainingTokens(),
242
+ 'X-RateLimit-Retry-After' => $limit->getRetryAfter()->getTimestamp(),
243
+ 'X-RateLimit-Limit' => $limit->getLimit(),
244
+ ];
245
+
239
246
if (false === $limit->isAccepted()) {
240
- throw new TooManyRequestsHttpException( );
247
+ return new Response(null, Response::HTTP_TOO_MANY_REQUESTS, $headers );
241
248
}
242
249
243
250
// ...
244
251
245
- $reponse = new Response($responseContents);
246
- $response->headers->add([
247
- 'X-RateLimit-Remaining' => $limit->getRemainingTokens(),
248
- 'X-RateLimit-Reset' => $limit->getRetryAfter()->getTimestamp(),
249
- 'X-RateLimit-Limit' => $limit->getLimit(),
250
- ]);
252
+ $reponse = new Response('...');
253
+ $response->headers->add($headers);
251
254
252
255
return $response;
253
256
}
0 commit comments