Generate API keys with python

How can i generate API keys with python? i would like to generate 20 different keys for my students, possibly with some restrictions.
Thanks!

1 Like

Here for you, from ChatGPT–>
Alright, here’s the lowdown on how to generate API keys in Python, including adding restrictions if needed. You can use Python’s secrets module for secure key generation, and a bit of logic to customize restrictions. Here’s a step-by-step example:


Code to Generate API Keys

Code–

"""
import secrets
import string
import json

def generate_api_keys(num_keys=20, key_length=32, restrictions=None):
    """
    Generate API keys with optional restrictions.

    Args:
        num_keys (int): Number of keys to generate.
        key_length (int): Length of each API key.
        restrictions (dict): Dictionary of restrictions to assign to keys.

    Returns:
        dict: A dictionary of API keys and their associated restrictions.
    """
    keys = {}
    for _ in range(num_keys):
        # Generate a random API key
        key = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(key_length))
        
        # Assign restrictions if provided
        keys[key] = restrictions if restrictions else {}

    return keys

def save_keys_to_file(keys, filename="api_keys.json"):
    """
    Save API keys to a file in JSON format.

    Args:
        keys (dict): API keys and their restrictions.
        filename (str): File name to save the keys.
    """
    with open(filename, "w") as file:
        json.dump(keys, file, indent=4)
    print(f"API keys saved to {filename}")

# Example usage
if __name__ == "__main__":
    # Define restrictions (optional)
    restrictions_example = {
        "usage_limit": 1000,  # Max API calls
        "valid_until": "2025-12-31"  # Expiration date
    }

    # Generate 20 API keys with restrictions
    api_keys = generate_api_keys(num_keys=20, key_length=40, restrictions=restrictions_example)

    # Save to a file
    save_keys_to_file(api_keys)
"""


How to Use the Keys

Store these keys in a secure database.

On every API call, validate the key and apply the restrictions (like checking usage_limit or valid_until).

This setup is flexible and secure, and it scales well for your classroom use case.

I was asking to create API keys by obtaining them from OpenAI, not generate random keys (which I think is what your code is doing)

But above, you asked it to generate from python, not by OpenAI–

“How can i generate API keys with python? i would like to generate 20 different keys for my students, possibly with some restrictions.
Thanks!”

This currently cannot be done programmatically:

Manage API keys for a given project. Supports listing and deleting keys for users. This API does not allow issuing keys for users, as users need to authorize themselves to generate keys.

There is no method for “create” in the admin API endpoint system.

OpenAI seems to have confused themselves, as the only way to securely offer access and protect your organization is to NOT use the user invite system, but instead only to distribute per-user API keys, in per-project containment units of model rights and usage limitations.

“Users need to authorize themselves”: forcing minor children to create OpenAI accounts and credentials? Verify phone device ownership, limited account number for a lifetime? How about heck no.