How to set environment variable based on development or production in FastAPI?

Question:

I want to have different environment variables based on development and production
but i can’t seem to find anything related to this topic for FastAPI.

Is it possible that i can have .env, .env.local, .env.prod to have different environment variables

Asked By: AhmetK

||

Answers:

I don’t think you need multiple files. Usually how it’s done is, have a single config file that has the default values, usually this is your "local" config file. For prod, staging and other environments, you can override these settings by setting environment variables, most hosts support it nowadays. It’s more secure and you don’t have to expose production secrets and keys in your repository.

This library is one example of what you code use:
https://github.com/theskumar/python-dotenv

EDIT

For example, if your application is hosted in Heroku, the heroku config commands of the Heroku CLI makes it easy to manage your app’s config vars:

heroku config:set SOME_CONFIG_I_NEED=value for production

You can also edit config vars from your app’s Settings tab in the Heroku Dashboard.

Heroku Dashboard

Please refer to the Heroku documentation for more information.

After you set the env vars in Heroku, this is how you would access them from your Python code (using python-dotenv):

First, install python-dotenv:

pip install python-dotenv

Now, create a file called .env in the root of your project with the following contents:

# Development settings
SOME_CONFIG_I_NEED=value for development

Now in your python file:

from dotenv import load_dotenv

load_dotenv()  # take environment variables from .env.

SOME_CONFIG_I_NEED = os.environ.get("SOME_CONFIG_I_NEED")

print(SOME_CONFIG_I_NEED)  # This will print "value for development" when running on local, and will print "value for production" when running in Heroku.
Answered By: AndreFeijo

An alternative approach could be to use the Pydantic Settings:
https://pydantic-docs.helpmanual.io/usage/settings/

There is also a bit about that in the FastAPI docs, but personally I choose not to ‘integrate’ the nice Pydantic Settings that way.
https://fastapi.tiangolo.com/advanced/settings/

Answered By: Janus Heide

The .env file

ADMIN_EMAIL="[email protected]"
APP_NAME="ChimichangApp"

Read settings from .env¶
And then update your config.py with:

from pydantic import BaseSettings
class Settings(BaseSettings):
    app_name: str = "Awesome API"
    admin_email: str

    class Config:
        env_file = ".env"

Here we create a class Config inside of your Pydantic Settings class, and set the env_file to the filename with the dotenv file we want to use.

Read variable

from config import Settings

app = FastAPI()


setting = Settings()
print(setting)

Learn more

Answered By: MD SHAYON