8000 Fixed and improvements · symfony/symfony-docs@f0c7b06 · GitHub
[go: up one dir, main page]

Skip to content

Commit f0c7b06

Browse files
committed
Fixed and improvements
1 parent 1101910 commit f0c7b06

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

rate_limiter.rst

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -219,15 +219,16 @@ When using a rate limiter in APIs, it's common to include some standard HTTP
219219
headers in the response to expose the limit status (e.g. remaining tokens, when
220220
new tokens will be available, etc.)
221221

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::
224226

225227
// src/Controller/ApiController.php
226228
namespace App\Controller;
227229

228230
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
229231
use Symfony\Component\HttpFoundation\Response;
230-
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
231232
use Symfony\Component\RateLimiter\RateLimiter;
232233

233234
class ApiController extends AbstractController
@@ -236,18 +237,20 @@ object which you can use to get the value of those HTTP headers::
236237
{
237238
$limiter = $anonymousApiLimiter->create($request->getClientIp());
238239
$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+
239246
if (false === $limit->isAccepted()) {
240-
throw new TooManyRequestsHttpException();
247+
return new Response(null, Response::HTTP_TOO_MANY_REQUESTS, $headers);
241248
}
242249

243250
// ...
244251

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);
251254

252255
return $response;
253256
}

0 commit comments

Comments
 (0)
0