Skip to content

Commit

Permalink
add slowapi
Browse files Browse the repository at this point in the history
  • Loading branch information
baniasbaabe committed Nov 2, 2024
1 parent b6100af commit d88ad55
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions book/cooltools/Chapter.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -2325,6 +2325,60 @@
"\n",
"skill_extractor.describe(annotations)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Rate Limiting FastAPI with `slowapi`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Preventing abuse of your API is crucial.\n",
"\n",
"To implement rate limiting for FastAPI, you can use `slowapi`.\n",
"\n",
"`slowapi` offers utility functions to limit your FastAPI or Starlette app based on e.g. the IP address.\n",
"\n",
"In the example below, we limit our API to 5 requests per minute.\n",
"\n",
"A note from the author: This is alpha quality code still, the API may change, and things may fall apart while you try it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install slowapi"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from fastapi import FastAPI\n",
"from slowapi import Limiter, _rate_limit_exceeded_handler\n",
"from slowapi.util import get_remote_address\n",
"from slowapi.errors import RateLimitExceeded\n",
"\n",
"# Limiting based on user's IP address\n",
"limiter = Limiter(key_func=get_remote_address)\n",
"app = FastAPI()\n",
"app.state.limiter = limiter\n",
"app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)\n",
"\n",
"@app.get(\"/home\")\n",
"@limiter.limit(\"5/minute\")\n",
"async def hello(request: Request):\n",
" return {\"response\":\"Hello\"}"
]
}
],
"metadata": {
Expand Down

0 comments on commit d88ad55

Please sign in to comment.