Validate Environment Variables with Pydantic

Validate Environment Variables with Pydantic

Tip! Validate your env vars from your .env files before they hit your application by using Pydantic. This also eliminates the need to call python-dotenv manually.

Here's an example:

# uv add pydantic pydantic-settings python-dotenv
from pydantic import Field, AnyHttpUrl, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict

# Define settings schema
class Settings(BaseSettings):
    device_host: AnyHttpUrl = Field(..., alias="DEVICE_HOST")
    device_username: str = Field(..., alias="DEVICE_USERNAME")
    device_password: str = Field(..., alias="DEVICE_PASSWORD")
    device_platform: str = Field(..., alias="DEVICE_PLATFORM")

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore"
    )

try:
    settings = Settings()
    print(settings.device_username)
    # admin
except ValidationError as e:
    print(e)

# Validation Error example
# 1 validation error for Settings
# device_host
#   Input should be a valid URL, scheme required [type=url_scheme, input_value='192.168.1.10', input_type=str]
#     For further information visit https://errors.pydantic.dev/2.12/v/url_scheme

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!