Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does FastAPI support config files with nested structures like yaml?

Python framework FastAPI supports config files of .env style. Can it work with a bit more structured config formats, like .yaml to ini/toml?

like image 273
AlexA Avatar asked Jul 26 '26 07:07

AlexA


1 Answers

While it is not implemented natively in the framework, you can do something like below:

YAML

import os
from pydantic import BaseSettings
import yaml

yaml_settings = dict()

here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "settings.yaml")) as f:
    yaml_settings.update(yaml.load(f, Loader=yaml.FullLoader))

class Settings(BaseSettings):
    setting_1: str = yaml_settings['setting_1']
    setting_2: str = yaml_settings['setting_2']

INI

import configparser
import os
from pydantic import BaseSettings

here = os.path.abspath(os.path.dirname(__file__))

config = configparser.ConfigParser()
config.read(os.path.join(here, "settings.ini"))

class Settings(BaseSettings):
   setting_1: str = config['dev']['setting_1']
   setting_2: str = config['dev']['setting_2']

TOML

import toml
import os
from pydantic import BaseSettings

here = os.path.abspath(os.path.dirname(__file__))
toml_settings = toml.load(os.path.join(here, "settings.toml"))

class Settings(BaseSettings):
   setting_1: str = toml_settings['dev']['setting_1']
   setting_2: str = toml_settings['dev']['setting_2']

Then you can pass Settings() in your routes as a dependency.

like image 82
phyominh Avatar answered Jul 28 '26 22:07

phyominh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!