.env Secret & Syntax Checker · Python / FastAPI

FastAPI & Pydantic Settings .env Validator (Fix ValidationError & Delimiters)

Lint your Python / FastAPI .env file locally in your browser to catch secret leaks, syntax truncation, and missing .env.example keys. Copy an auto-fixed .env or sanitized template below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Paste .env or load a test scenario2. Inspect live diagnostics3. Copy cleaned config
Quick-Test Scenarios:

1. Source .env Input

.env.example Parity Diff6 matched key(s)
Missing Required Keys:
OPENAI_API_KEY
Undocumented Keys:
None
APP_ENV=production
DEBUG=True
CORS_ORIGINS=http://localhost:3000
DATABASE_URL="postgresql+asyncpg://app:pass#word@postgres:5432/app_db"
REDIS_URL=redis://redis:6379/0
JWT_SECRET_KEY=replace_me_with_64_hex_chars
JWT_SECRET_KEY=duplicate_overwritten_secret
Critical
2
Warnings
4
Valid Keys
1
Missing Keys
1

Line-by-Line Diagnostics

Runs locally in your browser. Pasted .env values are never uploaded or saved to localStorage.

Typical Runtime Error (Python / FastAPI .env Failure)

When syntax errors, unquoted special characters, missing keys, or public-prefix secret leaks slip into a Python / FastAPI .env file, your runtime or audit pipeline surfaces an error like the output below:

Runtime Exception / Audit Output

pydantic_core._pydantic_core.ValidationError: 2 validation errors for Settings — OPENAI_API_KEY: Field required [type=missing] | DATABASE_URL: Input should be a valid URL

How Python / FastAPI Loads .env Files, Precedence & Security Boundaries

Modern Python FastAPI backends use pydantic-settings (BaseSettings backed by python-dotenv) to load, coerce, and strictly type-check environment variables at application startup. While Pydantic's fail-fast ValidationError prevents booting with missing credentials, subtle .env formatting bugs; such as unquoted # characters truncating PostgreSQL passwords, duplicate keys silently overriding JWT secrets, or spaces around =; frequently trigger cryptic parsing failures.

Pydantic Settings v2 also introduces powerful nested model parsing via env_nested_delimiter="__" (for example, DB__HOST=postgres mapping to settings.db.host) and JSON decoding for complex list fields like CORS_ORIGINS=["https://app.example.com"]. Leaving a raw comma-separated string when Pydantic expects a JSON list, or misaligning nested delimiters, throws immediate SettingsError JSONDecodeError crashes on startup.

Another frequent FastAPI security oversight is leaving DEBUG=True in production .env files (enabling verbose OpenAPI exception hooks or SQLAlchemy echo=True query logging) or leaving CORS_ORIGINS pointing at http://localhost:3000 instead of your production Next.js or Vite frontend domain.

Running your FastAPI .env through this zero-upload browser linter validates syntax, detects duplicate keys and unquoted hashes, compares required fields against .env.example to prevent pydantic_core.ValidationError crashes, and outputs both a clean .env and a Git-safe .env.example.

Always cache your Pydantic Settings instance with @lru_cache inside a dedicated app/core/config.py module and wrap secret strings with Pydantic's SecretStr type so accidental print(settings) or structured logs mask passwords automatically as **********.

As FastAPI microservices evolve across local development, pytest suites, Docker Compose, and Kubernetes deployments, keeping your .env file aligned with Pydantic BaseSettings and .env.example eliminates the most common startup ValidationError outages. Use distinct .env.test fixtures for CI pipelines with fake non-live keys, verify that nested __ delimiters and JSON list formats parse cleanly before container rollout, and rely on Pydantic SecretStr plus runtime secret mounts so database passwords and JWT signing keys never leak into structured application logs.

Step-by-Step Python / FastAPI .env Configuration & Hardening Guide

Apply these four concrete safeguards to eliminate silent dotenv truncation, prevent secret leaks, and keep local and production environments synchronized.

  1. 1Define Strongly Typed BaseSettings With SecretStr and Nested Delimiters

    app/core/config.py

    Use pydantic-settings v2 with SettingsConfigDict(env_file=".env", extra="ignore") and SecretStr for passwords and JWT secrets so logs never print raw credentials.

    app/core/config.pypython
    from functools import lru_cache
    from pydantic import AnyHttpUrl, SecretStr
    from pydantic_settings import BaseSettings, SettingsConfigDict
    
    class Settings(BaseSettings):
        model_config = SettingsConfigDict(
            env_file=".env",
            env_file_encoding="utf-8",
            env_nested_delimiter="__",
            extra="ignore",
        )
    
        app_env: str = "production"
        debug: bool = False
        database_url: SecretStr
        redis_url: str = "redis://redis:6379/0"
        jwt_secret_key: SecretStr
        cors_origins: list[AnyHttpUrl] = []
    
    @lru_cache
    def get_settings() -> Settings:
        return Settings()
  2. 2Format Complex Lists as Valid JSON and Quote Special Characters in .env

    .env

    In Pydantic Settings v2, list[str] fields expect JSON array syntax unless a custom validator splits commas. Always double-quote URLs or passwords containing #.

    .envdotenv
    APP_ENV=production
    DEBUG=false
    CORS_ORIGINS='["https://app.example.com"]'
    DATABASE_URL="postgresql+asyncpg://app:pass%23word@postgres:5432/app_db"
    REDIS_URL=redis://redis:6379/0
    JWT_SECRET_KEY="replace_with_openssl_rand_hex_32"
  3. 3Validate Settings in CI Before Deploying Docker Images

    terminal

    Verify your .env matches your Pydantic Settings schema before restarting Uvicorn workers.

    terminalbash
    python -c "from app.core.config import get_settings; print(get_settings().app_env)"
  4. 4Inject Settings via FastAPI Depends() for Clean Unit Testing

    app/main.py

    Inject get_settings via FastAPI Depends() so pytest suites can cleanly override settings with app.dependency_overrides without mutating os.environ globally.

    app/main.pypython
    from fastapi import Depends, FastAPI
    from app.core.config import Settings, get_settings
    
    app = FastAPI()
    
    @app.get("/health")
    def health(settings: Settings = Depends(get_settings)):
        return {"env": settings.app_env, "debug": settings.debug}

Common Python / FastAPI .env Pitfalls

Check these three framework-specific traps before deploying updated environment variables to staging or production.

Pitfall 1

Pydantic v2 JSONDecodeError on Comma-Separated CORS_ORIGINS

For list[str] fields, pydantic-settings v2 parses the env string as JSON by default. Writing CORS_ORIGINS=http://localhost:3000 instead of '["http://localhost:3000"]' (or adding a field_validator) crashes startup immediately.

Pitfall 2

OS Environment Variables Silently Overriding .env Values

By design, real OS environment variables (such as Docker Compose environment: or shell exports) take higher priority than values inside .env. Check printenv inside your container when a .env edit appears ignored.

Pitfall 3

Leaking Database Passwords in FastAPI Logs Without SecretStr

Logging settings.model_dump() prints plain strings in plaintext to Docker stdout and Datadog/CloudWatch logs. Using Pydantic SecretStr masks sensitive values unless .get_secret_value() is called explicitly.

Related Tools

Pair Your Validated .env With Webhook HMAC, Docker Compose & CORS Tools

Now that your environment variables are syntax-clean and leak-free, verify webhook raw-body HMAC signatures, container healthchecks, and browser cross-origin rules:

Frequently Asked Questions

Why does pydantic-settings fail with "Extra inputs are not permitted"?
Pydantic BaseSettings defaults to extra="forbid". If your .env file also holds Docker Compose variables (like COMPOSE_PROJECT_NAME or DB_ROOT_PASSWORD), set extra="ignore" inside SettingsConfigDict.
How do nested environment variables work with env_nested_delimiter="__"?
Setting env_nested_delimiter="__" maps double-underscore keys like DATABASE__POOL_SIZE=20 directly into a nested Pydantic BaseModel field settings.database.pool_size.
Does python-dotenv truncate values at unquoted # characters?
Yes. Unquoted # characters in python-dotenv are parsed as inline comments when preceded by whitespace or inside unquoted values. Always wrap passwords and connection strings containing # in double quotes.
Should I mount .env inside a production FastAPI Docker image?
Never COPY .env into a Docker image layer (add .env to .dockerignore). Inject environment variables at runtime using Docker Compose env_file: or your cloud orchestrator secret store.
Browse all 10 .env guides →