skip to Main Content

I’m trying to make a file within visual studio code that holds my API key and secret key. so when I do future codes I can just import that file into my code without having to write my API keys every time.

I’ve tried this

api key = ‘cewhjhbdhbd’
secret key = ‘jhewbduywevb’

tried to save it.. it saved in documents and when I tried to import it nothing happened.. where am I going wrong?

I am a beginner at coding so sorry if this is obvious.

2

Answers


  1. You can use environment variables for this.

    import os
    
    # Set environment variables
    os.environ['API_USER'] = 'username'
    os.environ['API_PASSWORD'] = 'secret'
    
    # Get environment variables
    USER = os.getenv('API_USER')
    PASSWORD = os.environ.get('API_PASSWORD')
    

    You can then import this file or use the above block of code in your files.

    Login or Signup to reply.
  2. Use an environment file like .env to store your API keys. In a format like

    ENVIRONMENT='DEVELOPMENT'
    API_KEY='yourapikeygoeshere'
    DEBUG=True
    DB_NAME=''
    DB_USER=''
    DB_PASSWORD=''
    DB_HOST='localhost'
    DB_PORT='5432'
    

    Then you can use packages like dotenv to access them.

    from dotenv import load_dotenv
    from pathlib import Path
    
    dotenv_path = Path('path/to/.env')
    load_dotenv(dotenv_path=dotenv_path)
    API_KEY = os.getenv('API_KEY')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search