8

In Fast API documentation it is recommended to use .env to load the config. Only that it only supports string as far as I understand it.

from fastapi import FastAPI
from pydantic import BaseSettings


class Settings(BaseSettings):
    api_tokens = []

    class Config:
        env_file = ".env"


settings = Settings()
app = FastAPI()

I usually change the API tokens every few months, by adding a new one to the list and after some time I remove the older ones. That gives the users enough time to upgrade to latest edition without any disruption. In the meanwhile both API tokens will be valid for some time.

But I can't define a list in the .env file.

API_TOKENS = abc123,abc321

Am I missing something?

UPDATE:

It actually is possible. The answer below is correct, however I still had to change the type like this:

class Settings(BaseSettings):
    api_tokens: list
Houman
  • 64,245
  • 87
  • 278
  • 460

2 Answers2

9

This should work,

API_TOKENS = ["abc123","abc321"]
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Thanks, what do you put as type for ```api_tokens = []``` because this is still failing for me. – Houman Jan 30 '21 at 15:39
  • I didn't change any code at all. Changing `.env` file work for me, and it should. Because this is some kind of weird (oh!!) syntax of *dotenv* package – JPG Jan 30 '21 at 15:43
  • I added an update to the question how I solved it. Because if I leave the type as `str` I get this instead: `"api_tokens":"[\"abc123\",\"abc321\"]"`. – Houman Jan 30 '21 at 16:52
  • Just for those who are using nested Config this won't work, since there is a bug in pydantic https://github.com/pydantic/pydantic/issues/3971 – machin Dec 14 '22 at 19:35
3

You can use json module to convert string variable to a list in python.

.env file

LIST_VAR='["Foo", "bar"]'

Python code

import os
import json
from dotenv import load_dotenv
load_dotenv()
list_var = json.loads(os.environ['LIST_VAR'])
Aashutosh Kumar
  • 615
  • 9
  • 13