Package: fastapi-request-limiter
FastAPI Request Limiter MiddlewareThis middleware provides request limiting functionality for FastAPI applications, allowing you to control and manage the rate of incoming requests based on client IP addresses.Installationpipinstallfastapi-request-limiterFeaturesRequest Limiting: Control the rate of incoming requests by applying a waiting penalty to clients who exceed predefined thresholds.Whitelisting: Allow certain IP addresses to bypass rate limiting restrictions.Blacklisting: Disallow certain IP addresses to access the API on web-server level.Flexible Configuration: Customize the middleware behavior by specifying parameters such as waiting time, whether to limit HTTP or WebSocket requests, and whitelisted IP addresses.Backups: Allows to generate and load backups of request histories.Usage ExamplefromfastapiimportFastAPIfromrequest_limiter_middlewareimportRequestLimitMiddlewarefromrequest_limiter_middlewareimportBackup,BanHammerapp=FastAPI()# blocking addressBanHammer.block_it(ip="127.0.0.2")# saving current IP requests historyBackup.save_archive('file.json')# Enabling request limitingapp.add_middleware(RequestLimitMiddleware,whitelisted_ip_addresses=("127.0.0.1",),limit_http=True,limit_websocket=True,seconds=7)# loading history backupBackup.load_archive('file.json')@app.get(path='/')asyncdefhome():return{"message":"Welcome home"}This example demonstrates how to integrate and use the middleware in your FastAPI application.It includes blocking a specific IP address, saving the current IP requests history to a file, enabling request limiting with specified configurations, and loading the history backup from the file.Parametersapp: The FastAPI application instance.whitelisted_ip_addresses: Tuple of whitelisted IP addresses that will bypass rate limiting.seconds: Time interval between two requests in seconds (default: 5 seconds).limit_http: Boolean flag to enable/disable request limiting for HTTP requests (default: True).limit_websocket: Boolean flag to enable/disable request limiting for WebSocket connections (default: True).DetailedScheme:FastAPI Request Limiter Middleware contains of three parts:Requests ArchiveRequestsArchiveis a singleton class containing ahistorydictionary with history of requests, which are  in according to following structure:{
    'ip': {
        "expiration_time": float | bool
    },
}waiting_timeis the number of seconds to waitexpiration_timeis the remaining secondstime.time() + secondsorFalseif the IP is blocked.RequestsArchivehas three methods:extend_time: Extends the cooldown of the given ip forNseconds, by default it's 5.get_remaining_time: Converts the remaining cooldown infloat(expiration_time's value) tointand returns it.If aboolvalue found, which means the IP is permanently blocked, it raisesHTTPExceptionwith400status_code and"Goodbye"detail.add_ip:Adds the given ip to history withNseconds of cooldown, by default it's 5. Used for unknown IP addresses requesting the API for the first time.BanHammer and BackupBanHammerandBackup, both are derived classes from Requests Archive.BanHammerBanHammerallows to block the user permanently. It has one methodblock_itwhich changes the"expiration_time"for the particular IP fromfloattoFalse.
This allows to raise errors in case of findingboolvalue instead offloatwithout further proceeding.BanHammeras well as the entire library doesn't have anyunblockingmechanisms, which is an essential nuance in request limiting and managing the security of the API.AsRequestsArchiveis a singleton class, you block IP addresses before and during runtime from any part of your code usingBanHammer.BTW: this mechanism perfectly matches with my another original library calledinput-armorwhere you can check user input for maliciousness.BackupBackupprovidessave_archiveandload_archivemethods.
As well asBanHammerthis class can be used any time from any part of the code.RequestLimitMiddlewareIf you want to find an instantiation example ofRequestLimitMiddlewareas well as with its parameters and their explanations: Look atUsage Examplesection of this document to find.First of all,RequestLimitMiddlewarechecks the incoming request type, whether it'shttporwebsocketand if the request should or should not be request limited, and proceeds the request if it should not.
Then it obtains the client IP usingRequest(scope).client.host.
- Addition: If you are usingFlaskorDjangoyou need to modify the way of invoking the IP address. As that's the onlyFastAPI-related dependency of this library. However, instead of installing withpipyou need to clone this repo.
In the next step it checks if the IP is white-listed, and proceeds the request if it is.
Then it checks for the active waiting penalty, if yes raises an error with429status code.LicenseThis project is licensed under the terms of theBSD license.AuthorArmen-Jean AndreasianLinks:GitHub RepositoryPyPI Package