Search code examples
pythonenvironment-variablesgpt-3

How to store API keys in environment variable? and call the same in google colab


I'm not sure how to make a ".json" file with my GPT-3 API key/environment variable, but I'd like to utilize it in Google Colab for automatic code generation.

Could someone please show me how to do this?

I want to get the API key from the.json file using the code below.

with open('GPT_SECRET_KEY.json') as f:
    data = json.load(f)
openai.api_key = data["API_KEY"]

Solution

  • To read from a json file you do the following:

    import json
    
    my_key = ''
    with open('GPT_SECRET_KEY.json', 'r') as file_to_read:
        json_data = json.load(file_to_read)
        my_key = json_data["API_KEY"]
    

    The structure of your json file should look something like this.

    {
        "API_KEY": "xxxxthis_is_the_key_you_are_targetingxxxx", 
        "API_KEY1": "xxxxxxxxxxxxxxxxxxxxxxx",
        "API_KEY2": "xxxxxxxxxxxxxxxxxxxxxxx"
    }
    

    Here is a link to a similar question if my answer was not clear enough.