0Pricing
FastAPI Backend Development Bootcamp · レッスン

環境変数とシークレットの管理

環境変数とシークレット管理を使い、異なる環境向けにFastAPIを安全に設定する方法を学びます。

「環境変数とシークレットの管理」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFastAPI Backend Development Bootcamp学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Externalize Configuration?

Hardcoding database URLs, API keys, or debug flags into your code is dangerous and inflexible.

The 12-factor app approach stores configuration in the environment, so the same image runs in dev, staging, and production with different settings.

Reading Environment Variables

Python reads variables via os.environ or os.getenv with a default.

import os

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./dev.db")
DEBUG = os.getenv("DEBUG", "false").lower() == "true"

Pydantic Settings

FastAPI projects commonly use pydantic-settings to load and validate config into a typed object.

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    secret_key: str
    debug: bool = False

Loading from a .env File

Configure the settings class to read a local .env file during development.

class Settings(BaseSettings):
    database_url: str
    secret_key: str

    class Config:
        env_file = ".env"

Caching the Settings Object

Use lru_cache so settings are parsed once and reused as a dependency.

from functools import lru_cache

@lru_cache
def get_settings() -> Settings:
    return Settings()

Injecting Settings into Routes

Treat settings as a FastAPI dependency for clean access and easy testing.

from fastapi import Depends

@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
    return {"debug": settings.debug}

Never Commit Secrets

Add .env to .gitignore. Committed secrets are extremely hard to fully remove from git history and may leak credentials.

# .gitignore
.env
*.pem
secrets/

Production Secret Stores

In production, prefer a managed secret store over plain files:

  • AWS Secrets Manager or Parameter Store
  • HashiCorp Vault
  • Docker or Kubernetes secrets

These inject secrets at runtime without writing them to disk in plain text.

Different Configs per Environment

Use a single variable like ENV to branch behavior, keeping all values in the environment.

ENV = os.getenv("ENV", "development")
if ENV == "production":
    LOG_LEVEL = "warning"
else:
    LOG_LEVEL = "debug"

Validating Required Variables

Pydantic settings raise a clear error at startup if a required variable is missing, failing fast instead of crashing later.

try:
    settings = Settings()
except Exception as e:
    print("Config error:", e)
    raise

Typed Lists and Nested Config

Settings can parse complex values too, like comma-separated origins into a list, keeping parsing logic out of your routes.

class Settings(BaseSettings):
    cors_origins: list[str] = []

# CORS_ORIGINS=https://a.com,https://b.com

Quick Check

Test your configuration knowledge.

Recap

You learned to manage configuration safely:

  • Read config from the environment, not source code
  • Use pydantic-settings for typed, validated config
  • Never commit .env; use a secret store in production

Solid config management keeps deployments portable and secure.

よくある質問

「環境変数とシークレットの管理」レッスンは無料ですか?

はい。「環境変数とシークレットの管理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。

「環境変数とシークレットの管理」で何を学びますか?

環境変数とシークレット管理を使い、異なる環境向けにFastAPIを安全に設定する方法を学びます。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

FastAPI Backend Development Bootcampを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのFastAPI Backend Development Bootcampは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「環境変数とシークレットの管理」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このFastAPI Backend Development Bootcampレッスンでコードを書いて実行できますか?

はい。すべてのFastAPI Backend Development Bootcampレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. FastAPIアプリケーションのDocker化
  2. GunicornとUvicornによるデプロイ
  3. クラウドデプロイ戦略
  4. 環境変数とシークレットの管理
← FastAPI Backend Development Bootcampに戻る