Gradio Environment Variables & Secrets

Configure applications safely with environment variables, .env files, and secret management — with practical Python and Gradio examples.

Python · Gradio · Configuration

What are environment variables and secrets?

Environment variables are values supplied to a process from its environment rather than being hard-coded in source files. They are useful for configuration such as an application mode, a service URL, or a feature flag. Secrets are sensitive configuration values — for example, API tokens and database passwords — and should be handled with stricter access controls.

Gradio applications are ordinary Python processes: read configuration with os.environ or os.getenv(), validate required values at startup, and pass only the necessary configuration to the functions that need it.

Security rule: Never put real API keys in HTML, browser JavaScript, public repositories, screenshots, or Gradio output. The demos below use fake placeholder values and run locally in this page only.

1. Environment variable basics

Use os.getenv() to read a variable. Supply a default for optional settings and validate required settings explicitly.

Python · read_config.py
import os

APP_ENV = os.getenv("APP_ENV", "development")
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.example.com")

print("Environment:", APP_ENV)
print("Log level:", LOG_LEVEL)

Live example: read a configuration value

The value will appear here.

2. Set variables before launching Gradio

Set variables in the shell or deployment environment. The Python process inherits them when it starts.

macOS / Linux

Terminal
export APP_ENV=production
export LOG_LEVEL=INFO
python app.py

Windows PowerShell

PowerShell
$env:APP_ENV = "production"
$env:LOG_LEVEL = "INFO"
python app.py
Python · app.py
import os
import gradio as gr

environment = os.getenv("APP_ENV", "development")

def greet(name):
    return f"Hello, {name}! Running in {environment} mode."

demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="Your name"),
    outputs=gr.Textbox(label="Greeting"),
    title="Environment-aware Gradio app"
)

if __name__ == "__main__":
    demo.launch()

3. Use a .env file for local development

A .env file is a convenient local-development option. The python-dotenv package loads its entries into the process environment.

.env · local example (fake values)
APP_ENV=development
APP_TITLE=Knowledge Assistant
API_TOKEN=replace-with-your-local-token
Terminal
pip install python-dotenv gradio
Python · app.py
import os
import gradio as gr
from dotenv import load_dotenv

load_dotenv()  # Loads .env for local development

app_title = os.getenv("APP_TITLE", "My Gradio App")
app_env = os.getenv("APP_ENV", "development")

def status():
    return f"{app_title} is running in {app_env} mode."

demo = gr.Interface(fn=status, inputs=None, outputs="text", title=app_title)
demo.launch()
Important: Add .env to .gitignore. Do not commit it. Use your hosting platform's secret manager for deployed applications.

Live example: .env parser (illustrative)

Parsed keys will appear here. Values are masked in this preview.

4. Keep API keys secret

Read a key on the server side and use it inside the function that calls the external service. Do not return the key from a Gradio callback or place it in a component's value.

Python · secret_config.py
import os
import gradio as gr

API_KEY = os.getenv("MY_SERVICE_API_KEY")
if not API_KEY:
    raise RuntimeError("MY_SERVICE_API_KEY is not configured")

def call_service(prompt):
    # Use API_KEY in a server-side SDK/client request.
    # Never return or print the key.
    return f"Request prepared for: {prompt}"

demo = gr.Interface(
    fn=call_service,
    inputs=gr.Textbox(label="Prompt"),
    outputs=gr.Textbox(label="Status")
)
demo.launch()
Production tip: Configure MY_SERVICE_API_KEY in your hosting provider's secret/environment settings. Limit who can view or edit it, rotate it if exposed, and avoid logging request headers.

Live example: secret safety check

Secret value is hidden. This is only a browser-side illustration; do not enter a real key.

5. Validate required configuration at startup

Fail early with a clear message if a required setting is missing. Avoid printing the secret itself.

Python · validate_settings.py
import os

def required_env(name: str) -> str:
    value = os.getenv(name)
    if not value:
        raise RuntimeError(f"Missing required environment variable: {name}")
    return value

# Validate at application startup
service_key = required_env("MY_SERVICE_API_KEY")
database_url = required_env("DATABASE_URL")

print("Required configuration is present.")

Live example: configuration validator

Ready to validate.

6. Gradio app with environment-based settings

This example changes the title and greeting based on server-side configuration while keeping sensitive values out of the interface.

Python · complete Gradio example
import os
import gradio as gr

APP_TITLE = os.getenv("APP_TITLE", "Environment Demo")
APP_ENV = os.getenv("APP_ENV", "development")

def respond(message):
    if not message.strip():
        return "Please enter a message."
    return f"[{APP_ENV}] You said: {message}"

with gr.Blocks(title=APP_TITLE) as demo:
    gr.Markdown(f"# {APP_TITLE}")
    gr.Markdown("Configuration is loaded on the server.")
    chat_input = gr.Textbox(label="Message", placeholder="Type something...")
    output = gr.Textbox(label="Response")
    submit = gr.Button("Submit")
    submit.click(respond, inputs=chat_input, outputs=output)

if __name__ == "__main__":
    demo.launch()

7. Real-world configuration workflow

Define names: choose clear names such as APP_ENV, API_BASE_URL, and MY_SERVICE_API_KEY.
Separate values: keep ordinary configuration and sensitive credentials out of source code.
Configure the environment: use shell variables for local testing and the platform's secret manager for deployment.
Load and validate: read settings at startup, apply safe defaults only to optional values, and fail clearly for missing required values.
Protect and rotate: restrict access, never expose secrets in UI/logs, and rotate credentials after accidental disclosure.
SettingExampleSecret?Recommended handling
APP_ENVproductionNoEnvironment variable with a safe default where appropriate
APP_TITLESupport AssistantNoEnvironment variable or app configuration
API_BASE_URLhttps://api.example.comUsually noEnvironment variable; validate trusted destinations
MY_SERVICE_API_KEY••••••••YesDeployment secret manager; never commit or display
DATABASE_URL••••••••Often yesSecret manager; restrict access and redact logs

8. Common mistakes and fixes

Variable is None

Check the exact variable name, whether it was exported, and whether the process was restarted after changing it.

.env is not loading

Install python-dotenv, call load_dotenv(), and check the working directory or explicit .env path.

Secret appears in logs

Remove debug prints, redact headers and configuration dumps, rotate the exposed credential, and review access logs.

Works locally, fails in deployment

Set the variable in the deployment environment/secret settings. A local .env file is not automatically deployed.

9. Quick knowledge check

Which is the safest place for a production API token?

Choose an answer.

10. Useful references

Examples are educational templates. Adapt validation, permissions, and secret storage to your deployment platform and security requirements.