Skip to main content

Python library for API key rotation, rate limit control and load balancing

Project description

APIRotater

APIRotater is a Python library that helps you manage your API keys and control rate limits. By managing multiple API keys, it automatically performs key rotation in case of rate limit exceedance.

Key Features

  • Automatic API Key Rotation: Uses multiple API keys in rotation.
  • Rate Limit Control: You can set a maximum number of uses for each API key within a specific time window.
  • Automatic .env File Loading: Automatically loads API keys from .env files located in the current working directory or parent directory.
  • Usage Statistics: Tracks usage counts of API keys by variable names.
  • RateLimitExceeded Exception: Throws an error when all keys have exceeded their rate limit.

Installation

pip install apirotater

Usage

Define your API keys in a .env file as follows:

API_KEY_1=your_api_key_1
API_KEY_2=your_api_key_2
API_KEY_3=your_api_key_3

Basic Usage

import apirotater

# Get an API key
api_key = apirotater.key()

# Make API request
# ...

# Report API key usage
apirotater.hit(api_key)

# Next time you call key(), it will automatically use a different key
next_api_key = apirotater.key()  # This will be a different key due to rotation

Automatic Key Rotation

APIRotater automatically rotates through your API keys to ensure even distribution and avoid rate limit issues:

  1. When you call key(), it returns the most suitable key based on current usage
  2. After you call hit(api_key), the library automatically moves to the next key
  3. The next key() call will use a different key, maintaining rotation
  4. If a key has reached its rate limit, it will be skipped automatically
import apirotater

# First request - gets first available key
key1 = apirotater.key(time_window=60, max_uses=2)
# Use key1 for API request
apirotater.hit(key1)  # Marks key1 as used and rotates to next key

# Second request - gets next key due to rotation
key2 = apirotater.key()  # This will be a different key than key1
# Use key2 for API request
apirotater.hit(key2)  # Marks key2 as used and rotates to next key

# Third request - continues rotation
key3 = apirotater.key()  # This will be the next key in rotation
# Use key3 for API request
apirotater.hit(key3)

# Fourth request - completes the rotation cycle
key4 = apirotater.key()  # This might be the first key again if you have 3 keys

Usage With Rate Limit

import apirotater

# Get a key with maximum 2 uses in 60 seconds
api_key = apirotater.key(time_window=60, max_uses=2)

# Make API request
# ...

# Report API key usage - this also rotates to the next key
apirotater.hit(api_key)

Handling Rate Limit Exceedance

import apirotater
import time

try:
    # Get a key with rate limit
    api_key = apirotater.key(time_window=60, max_uses=2)
    
    # Make API request
    # ...
    
    # Report API key usage
    apirotater.hit(api_key)
    
except apirotater.RateLimitExceeded as e:
    print(f"Rate limit exceeded: {e}")
    # Wait for a while and try again
    time.sleep(60)

Checking Usage Statistics

import apirotater

# Get and use an API key
api_key = apirotater.key()
apirotater.hit(api_key)

# Get all usage statistics (returns a dictionary with API_KEY_* names)
all_stats = apirotater.usage()
print(all_stats)  # {'API_KEY_1': 1, 'API_KEY_2': 0, ...}

# Get usage for a specific key by index (0-based)
first_key_usage = apirotater.usage(0)
print(first_key_usage)  # 1

# Get usage for a specific key by name
usage_of_key1 = apirotater.usage("API_KEY_1")
print(usage_of_key1)  # 1

# Alternative way to get all statistics
all_stats_alt = apirotater.usage("all")
print(all_stats_alt)  # {'API_KEY_1': 1, 'API_KEY_2': 0, ...}

# Check the current key being used
current_key = apirotater.get_current_key_name()
print(f"Current key: {current_key}")  # Current key: API_KEY_2

API

  • key(time_window=60, max_uses=100): Gets an API key (with rate limit)
  • hit(api_key): Reports API key usage and rotates to the next key in sequence
  • usage(key_index=None): Returns usage statistics:
    • usage() or usage("all"): All keys' usage statistics
    • usage(0), usage(1), etc.: Usage of a specific key by index
    • usage("API_KEY_1"): Usage of a specific key by name
  • get_all_keys(): Lists all loaded API keys
  • get_key_names(): Returns a mapping of API keys to their variable names
  • get_current_key_name(): Returns the variable name of the currently selected API key

License

MIT License

Copyright (c) 2025 APIRotater

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

apirotater-0.4.6.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

apirotater-0.4.6-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file apirotater-0.4.6.tar.gz.

File metadata

  • Download URL: apirotater-0.4.6.tar.gz
  • Upload date:
  • Size: 7.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for apirotater-0.4.6.tar.gz
Algorithm Hash digest
SHA256 a096a58b6bac3dd1811bb0a9294b79b8d7e652fde331d45c026b3eec859841e3
MD5 68972101b33b31c7b9ee653b04af42c3
BLAKE2b-256 f4ea5d1f0f9852f8fefb5a37cfa7f1658b9b0a6821bf828e082c71d47b2bcdb4

See more details on using hashes here.

File details

Details for the file apirotater-0.4.6-py3-none-any.whl.

File metadata

  • Download URL: apirotater-0.4.6-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for apirotater-0.4.6-py3-none-any.whl
Algorithm Hash digest
SHA256 0e11e394fb5678c351e61aaeb2bc4a9844266a43f39a53359f7e0ec8f3b6a3dc
MD5 5ecb7626e37b3b3133b70ccb42ad948a
BLAKE2b-256 003394d386c85f54eccf091012d76bea97e693bb6de68ce6b8979f1533ade459

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page