From the docs posted here, you need call the variables from the .env class in the Settings class.
config.py
from pydantic import BaseSettings
class Settings(BaseSettings):
foo: str
class Config:
env_file = "config.env"
where config.env has the following:
foo="bar"
Then you pass the contents to the get_settings function wrapped by a lru_cache decorator and return those values.
@lru_cache()
def get_settings():
return config.Settings()
After that you can inject those parameters into the "/info" path of the fastapi app:
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
return {"foo": settings.foo}
The full main.py should be like this:
from functools import lru_cache
from fastapi import Depends, FastAPI
import config
app = FastAPI()
@lru_cache()
def get_settings():
return config.Settings()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
return {"foo": settings.foo}
Then just start your app without calling the env file in the command:
python -m uvicorn main:app --reload
The curl output should be something like this:
curl http://127.0.0.1:8000/info
{"foo":"bar"}