{"id":13424726,"url":"https://github.com/long2ice/fastapi-limiter","last_synced_at":"2026-02-06T08:20:56.239Z","repository":{"id":44370862,"uuid":"310551010","full_name":"long2ice/fastapi-limiter","owner":"long2ice","description":"A request rate limiter for fastapi","archived":false,"fork":false,"pushed_at":"2024-04-11T07:46:38.000Z","size":169,"stargazers_count":568,"open_issues_count":38,"forks_count":59,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-04-14T22:19:36.735Z","etag":null,"topics":["asyncio","fastapi","limiter"],"latest_commit_sha":null,"homepage":"https://github.com/long2ice/fastapi-limiter","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/long2ice.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-06T09:27:57.000Z","updated_at":"2025-04-12T20:50:02.000Z","dependencies_parsed_at":"2024-01-03T02:29:58.415Z","dependency_job_id":"fbf54ca4-e3e6-41b9-86e0-3b6346d2e5ef","html_url":"https://github.com/long2ice/fastapi-limiter","commit_stats":{"total_commits":37,"total_committers":6,"mean_commits":6.166666666666667,"dds":0.4054054054054054,"last_synced_commit":"940c1528f4cde7b1b12801ff9cc22978d0d09281"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/long2ice%2Ffastapi-limiter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/long2ice%2Ffastapi-limiter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/long2ice%2Ffastapi-limiter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/long2ice%2Ffastapi-limiter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/long2ice","download_url":"https://codeload.github.com/long2ice/fastapi-limiter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254337613,"owners_count":22054253,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncio","fastapi","limiter"],"created_at":"2024-07-31T00:00:58.415Z","updated_at":"2026-02-06T08:20:56.209Z","avatar_url":"https://github.com/long2ice.png","language":"Python","readme":"# fastapi-limiter\n\n[![pypi](https://img.shields.io/pypi/v/fastapi-limiter.svg?style=flat)](https://pypi.python.org/pypi/fastapi-limiter)\n[![license](https://img.shields.io/github/license/long2ice/fastapi-limiter)](https://github.com/long2ice/fastapi-limiter/blob/master/LICENCE)\n[![workflows](https://github.com/long2ice/fastapi-limiter/workflows/pypi/badge.svg)](https://github.com/long2ice/fastapi-limiter/actions?query=workflow:pypi)\n[![workflows](https://github.com/long2ice/fastapi-limiter/workflows/ci/badge.svg)](https://github.com/long2ice/fastapi-limiter/actions?query=workflow:ci)\n\n## Introduction\n\nFastAPI-Limiter is a rate limiting tool for [fastapi](https://github.com/tiangolo/fastapi) routes with lua script.\n\n## Requirements\n\n- [redis](https://redis.io/)\n\n## Install\n\nJust install from pypi\n\n```shell script\n\u003e pip install fastapi-limiter\n```\n\n## Quick Start\n\nFastAPI-Limiter is simple to use, which just provide a dependency `RateLimiter`, the following example allow `2` times\nrequest per `5` seconds in route `/`.\n\n```py\nimport redis.asyncio as redis\nimport uvicorn\nfrom contextlib import asynccontextmanager\nfrom fastapi import Depends, FastAPI\n\nfrom fastapi_limiter import FastAPILimiter\nfrom fastapi_limiter.depends import RateLimiter\n\n@asynccontextmanager\nasync def lifespan(_: FastAPI):\n    redis_connection = redis.from_url(\"redis://localhost:6379\", encoding=\"utf8\")\n    await FastAPILimiter.init(redis_connection)\n    yield\n    await FastAPILimiter.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\", dependencies=[Depends(RateLimiter(times=2, seconds=5))])\nasync def index():\n    return {\"msg\": \"Hello World\"}\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(\"main:app\", debug=True, reload=True)\n```\n\n## Usage\n\nThere are some config in `FastAPILimiter.init`.\n\n### redis\n\nThe `redis` instance of `aioredis`.\n\n### prefix\n\nPrefix of redis key.\n\n### identifier\n\nIdentifier of route limit, default is `ip`, you can override it such as `userid` and so on.\n\n```py\nasync def default_identifier(request: Request):\n    forwarded = request.headers.get(\"X-Forwarded-For\")\n    if forwarded:\n        return forwarded.split(\",\")[0]\n    return request.client.host + \":\" + request.scope[\"path\"]\n```\n\n### callback\n\nCallback when access is forbidden, default is raise `HTTPException` with `429` status code.\n\n```py\nasync def default_callback(request: Request, response: Response, pexpire: int):\n    \"\"\"\n    default callback when too many requests\n    :param request:\n    :param pexpire: The remaining milliseconds\n    :param response:\n    :return:\n    \"\"\"\n    expire = ceil(pexpire / 1000)\n\n    raise HTTPException(\n        HTTP_429_TOO_MANY_REQUESTS, \"Too Many Requests\", headers={\"Retry-After\": str(expire)}\n    )\n```\n\n## Multiple limiters\n\nYou can use multiple limiters in one route.\n\n```py\n@app.get(\n    \"/multiple\",\n    dependencies=[\n        Depends(RateLimiter(times=1, seconds=5)),\n        Depends(RateLimiter(times=2, seconds=15)),\n    ],\n)\nasync def multiple():\n    return {\"msg\": \"Hello World\"}\n```\n\nNot that you should note the dependencies orders, keep lower of result of `seconds/times` at the first.\n\n## Rate limiting within a websocket.\n\nWhile the above examples work with rest requests, FastAPI also allows easy usage\nof websockets, which require a slightly different approach.\n\nBecause websockets are likely to be long lived, you may want to rate limit in\nresponse to data sent over the socket.\n\nYou can do this by rate limiting within the body of the websocket handler:\n\n```py\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    ratelimit = WebSocketRateLimiter(times=1, seconds=5)\n    while True:\n        try:\n            data = await websocket.receive_text()\n            await ratelimit(websocket, context_key=data)  # NB: context_key is optional\n            await websocket.send_text(f\"Hello, world\")\n        except WebSocketRateLimitException:  # Thrown when rate limit exceeded.\n            await websocket.send_text(f\"Hello again\")\n```\n\n## Lua script\n\nThe lua script used.\n\n```lua\nlocal key = KEYS[1]\nlocal limit = tonumber(ARGV[1])\nlocal expire_time = ARGV[2]\n\nlocal current = tonumber(redis.call('get', key) or \"0\")\nif current \u003e 0 then\n    if current + 1 \u003e limit then\n        return redis.call(\"PTTL\", key)\n    else\n        redis.call(\"INCR\", key)\n        return 0\n    end\nelse\n    redis.call(\"SET\", key, 1, \"px\", expire_time)\n    return 0\nend\n```\n\n## License\n\nThis project is licensed under the\n[Apache-2.0](https://github.com/long2ice/fastapi-limiter/blob/master/LICENCE) License.\n","funding_links":[],"categories":["Third-Party Extensions","Async","Python"],"sub_categories":["Utils"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flong2ice%2Ffastapi-limiter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flong2ice%2Ffastapi-limiter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flong2ice%2Ffastapi-limiter/lists"}