A tool to monitor the number of HTTP requests through an _apiKey_ in the HTTP Header.
Project description
requests-counter
A tool to monitor the number of HTTP requests through an apiKey in the HTTP Header.
Use cases
Scenario: A Company that sell a Service that is limited by a max amount of requests.
- As a Company, I would set a request limit for an api_key.
- As a Company, I would update/destroy/inspect the status of subscription via api.
Installation
Requirement
Install redis or run a docker container as below
$> docker run --name test-redis -p6379:6379 -ti redis redis-server --appendonly yes
Package Installation
$> pip install requests-counter
Usage
As request counter for fastapi
from fastapi import Depends, FastAPI, HTTPException,Header
#1. Import the library
from requests_counter.reqcounter import ReqCounter
import asyncio
app = FastAPI()
#2. Create an ReqCounter object with the url to redis instance as parameter
cl = ReqCounter("redis://localhost")
#3. populate the Object with a list of tuple (key, max_value)
asyncio.create_task(cl.setup([("my-api-key-test",10)]))
#4. Declare a function to inject to Depends module. It will decrease the max_value for each request. It will raise a 429 HTTPException when max_value is 0.
async def check_key(apiKey: str = Header(None)):
res = await cl.decrease(apiKey)
if res == False:
raise HTTPException(429, "Too Many Requests", headers={"Retry-After": "renew subscription"})
return apiKey
#5. Inject the check_key function to endpoint
@app.get("/consume")
async def consume_key(apiKey = Depends(check_key)):
return {"job": "done", "apiKey":apiKey}
To run this example
$> uvicorn requests_counter.example:app --reload --port 8080
As endpoint
Command below run the server to interact with your redis instance for
- Destroy a key
- Update the value (i.e. renewal)
- Get the status of all keys
$> uvicorn requests_counter.api:app --reload --port 8080
Run http://locahost:8080/docs
for documentation.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
requests-counter-1.1.1.tar.gz
(4.2 kB
view hashes)
Built Distribution
Close
Hashes for requests_counter-1.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d3d00f3a6e50e87b1ef37a558d17204a4dd28efd2c99360870e9f175883df15f |
|
MD5 | 217b7abc49401403639fcb1ad22a8fad |
|
BLAKE2b-256 | c606f8e5e80a5780452a3df306d8f93e071c9984e9a2f9ff63d98196f83c6a66 |